niksos niksos - 5 months ago 20
jQuery Question

JQuery how to get inline style value

I'm trying to do hover image but how do I get the original inline css background value returned?

<div style="background-image: url(orig.jpg)" data-alt-bg="orig_hover.jpg">

$("div[data-alt-bg]").hover(function() {
var backgroundnew = "url('" + $(this).attr('data-alt-bg') + "')";
$(this).css('background-image', backgroundnew)
}, function() {
var backgroundOrig = XXX??????????XXXXXX??????????
$(this).css('background-image', backgroundOrig)
});

Answer

Save the original background as custom data attribute and update based on the data attribute value in second callback function.

$("div[data-alt-bg]").hover(function() {
  $(this).data('bg', $(this).css('background-image'));
  var backgroundnew = "url('" + $(this).attr('data-alt-bg') + "')";
  $(this).css('background-image', backgroundnew)
}, function() {
  $(this).css('background-image', $(this).data('bg'))
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="background-image: url(orig.jpg)" data-alt-bg="orig_hover.jpg">hi</div>


FYI : Always it's better to use css since there is option with :hover pseudo-class.

Comments