My HTML CODE HERE:
<i id="bgcolor" style="background-color: rgb(255, 146, 180)"></i>
I want to get the background-color value using jquery attr. What i tried is below:
$("#bgcolor").mouseleave(function(){
var bodyColor = $(this).attr("style");
$("body").css(bodyColor);
});
But this output is:
background-color: rgb(255, 146, 180);
And now that I've added it to my css it will not work. How can I achieve this task?
The attr() method sets or returns attributes and values of the selected elements. When this method is used to return the attribute value, it returns the value of the FIRST matched element. When this method is used to set attribute values, it sets one or more attribute/value pairs for the set of matched elements.
First, you need to select the element with querySelector . Then, you use getComputedStyle to get the element's styles. If you log style , you should see an object that contains every CSS property and their respective values. You can also see this object in Chrome's and Firefox's dev tools.
The attr() CSS function is used to retrieve the value of an attribute of the selected element and use it in the stylesheet. It can also be used on pseudo-elements, in which case the value of the attribute on the pseudo-element's originating element is returned.
Check out the documentation for .css: http://api.jquery.com/css/
var bodyColor = $(this).css("backgroundColor");
This is what you are looking for(this code works):
$("#bgcolor").mouseleave(function(){
var bodyColor = $(this).attr("style");
$("body").attr("style", bodyColor);
});
But, instead of using attr
you should use css
, so the code will be:
$("#bgcolor").mouseleave(function(){
var bodyColor = $(this).css("background-color");
$("body").css("background-color", bodyColor);
});
JSFiddle
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With