niksos niksos - 25 days ago 18
jQuery Question

Image switch with data-attribute

$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll >= 50) {
$("header").addClass("sticky");
$('header .logo a img').attr('src', $('header .logo a img').data("hover"));
} else {
$("header").removeClass("sticky");
$("header").addClass("");
$('header .logo a img').attr('src', $('header .logo a img').data("src"));
}
});


The first one works but the src is not coming back anymore. How should this be done?

<img src="img/logo2.png" data-hover="img/logo.png" alt="" class="img-responsive" />

Answer

You should add the data-src attribute that you try to access.

<img src="img/logo2.png" data-src="img/logo2.png" data-hover="img/logo.png" alt="" class="img-responsive" />
Comments