JQuery to change (with fade animation) background image div on hover

I am trying to change the background image of a div to hover using jQuery. This is what I came to, however, it does not work:

HTML

<div class="logo"></div> 

CSS

 .logo { width: 300px; height: 100px; background: url('http://placehold.it/300x100/ffffff/000000.png&text=first') no-repeat center top; } 

Js

 $('.logo').hover( function(){ $(this).animate({backgroundImage: 'http://placehold.it/300x100/ffffff/000000.png&text=second'},'fast'); }, function(){ $(this).animate({backgroundImage: 'http://placehold.it/300x100/ffffff/000000.png&text=first'},'fast'); }); 

jsfiddle here: http://jsfiddle.net/26j6P/1/

What am I doing wrong? If I animate the background color, it works fine ...

+6
source share
6 answers

You cannot use jQuery animations with images - it just doesn't work.

Use simple css like this ...

http://jsfiddle.net/26j6P/9/

Here css ...

 .logo { width: 300px; height: 100px; background: url('http://placehold.it/300x100/ffffff/000000.png&text=first') no-repeat center top; transition: 0.5s; } .logo:hover { background-image: url('http://placehold.it/300x100/ffffff/000000.png&text=second'); } 
+11
source

You cannot animate non-numerical properties with .animate()

+6
source

Demo

 $('.logo').hover( function () { $(this).animate({ opacity: 0 }, 'fast', function () { $(this) .css({ 'background-image': 'url(http://placehold.it/300x100/ffffff/000000.png&text=second)' }) .animate({ opacity: 1 }); }); }, function () { $(this).animate({ opacity: 0 }, 'fast', function () { $(this) .css({ 'background-image': 'url(http://placehold.it/300x100/ffffff/000000.png&text=first)' }) .animate({ opacity: 1 }); }); }); 
+4
source

I know I'm a little late. But if there is someone who needs to do this, there is a jquery plugin for that. Follow the link below, scroll down to the demo and select "Use Backstretch" as a slide show. It works great.

http://srobbin.com/jquery-plugins/backstretch/

+2
source

Try to do this: -

 $('.logo').hover( function() { $(this).css("background-image", "url(http://placehold.it/300x100/ffffff/000000.png&text=second)"); }, function() { $(this).css("background-image", "url(http://placehold.it/300x100/ffffff/000000.png&text=first)"); } ); 
+1
source

I saw someone say that you cannot do this using jQuery , well here is my example and it works. $(".bannerImages img") calls my image directly, so we can change its attribute with $(this) . After that, you can call $(this) and change its attr , as well as add animation.

 $(".bannerImages img").animate({opacity: 0}, 'slow', function() { $(this) .attr({'src': 'images/mainSlider/ps1.jpg'}) .animate({opacity: 1}); }); 
+1
source

Source: https://habr.com/ru/post/953687/


All Articles