Laveena
Laveena

Reputation: 97

changing attribute using jquery

I am trying to change background attribute using jquery. It's something like this

$('.insta-icon').css('background' ,'-webkit-radial-gradient(circle at 30% 107%, #fdf497 0%, #fdf497 5%, #fd5949 45%, #d6249f 60%, #285AEB 90%)');

If I put a simple color it works fine but with above gradient properties it's not working. Can anyone help.

Upvotes: 2

Views: 83

Answers (3)

Andy Hoffman
Andy Hoffman

Reputation: 19109

I got this working using the { } inside the function call. More importantly, I removed the -webkit- prefix, which was causing the JavaScript call to silently fail. Because radial-gradient is supported in 93% 96.72% of browsers, the prefix can be ignored.

$('.insta-icon').css({
  background: 'radial-gradient(circle at 30% 107%, #fdf497 0%, #fdf497 5%, #fd5949 45%, #d6249f 60%, #285AEB 90%)'
});
.insta-icon {
  display: inline-block;
  width: 200px;
  height: 200px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="insta-icon"></div>

jsFiddle

Upvotes: 3

Abdelrahman Gobarah
Abdelrahman Gobarah

Reputation: 1589

use radial-gradient instead of -webkit-radial-gradient

and better if you use toggleClass instead of put static values into your code,

Solution for your question

$('.insta-icon').css({
  'background': '-webkit-radial-gradient(circle at 30% 107%, #fdf497 0%, #fdf497 5%, #fd5949 45%, #d6249f 60%, #285AEB 90%)',
    'background': 'radial-gradient(circle at 30% 107%, #fdf497 0%, #fdf497 5%, #fd5949 45%, #d6249f 60%, #285AEB 90%)'

});
<div class="insta-icon">
  <h1>HELLO WORLD</h1>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


Better Solution

function changeBackground() {

  $('.insta-icon').toggleClass('bg-primary bg-secondary');

}
.bg-primary {
  background: black;
  color: white;
}

.bg-secondary {
  background: -webkit-radial-gradient(circle at 30% 107%, #fdf497 0%, #fdf497 5%, #fd5949 45%, #d6249f 60%, #285AEB 90%);
  background: radial-gradient(circle at 30% 107%, #fdf497 0%, #fdf497 5%, #fd5949 45%, #d6249f 60%, #285AEB 90%)
}
<button onclick="changeBackground();">Change Background</button>

<div class="insta-icon bg-primary">
  <h1>HELLO WORLD</h1>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Upvotes: 1

Kevin
Kevin

Reputation: 1377

Maybe your gradient code is wrong or not formatted. I have added the fiddle, hope it helps.

N.B: Refer to ColorZilla. Easiest way to get codes for gradient.

$( document ).ready(function() {
$('.insta-icon').css({
    background: "-webkit-radial-gradient(center, ellipse cover, #fdf497 0%, #fdf497 5%, #fd5949 45%, #d6249f 60%, #285AEB 90%)" 
});
});
.insta-icon{width:200px; height:200px;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="insta-icon"></div>

Upvotes: 2

Related Questions