Xeen
Xeen

Reputation: 7003

How to fade image src attribute?

I found that it can be done like this:

$(".topImage img")
        .mouseover(function() { 
            var src = $(this).attr("src").match(/[^\.]+/) + "-bw.png";
            $(this).fadeOut("fast").attr("src", src).fadeIn("fast");
        })
        .mouseout(function() {
            var src = $(this).attr("src").replace("-bw.png", ".png");                
            $(this).fadeOut("fast").attr("src", src).fadeIn("fast");
        });
    });

but this makes it bad because it fades the previous src out completely. Is there a way I could transition that src change so that there is no "now it's a white background before the new src loads in" ?

Edit

<div class="topImage">
    <img src="<?=$img[0]?>">
</div>

This is how it must remain - only one image in the topImage container so haveing two images that change opacity, is not an option.

Upvotes: 0

Views: 2524

Answers (2)

Mehdi Brillaud
Mehdi Brillaud

Reputation: 1866

You can even do it without JS at all. There is a lot of way to do it, but here is one : http://codepen.io/mbrillaud/pen/MwwgWZ

HTML

<div class="container">
  <img src="//lorempicsum.com/futurama/350/200/2" alt="" />
  <img src="//lorempicsum.com/futurama/350/200/1" alt="" />
</div>

CSS

.container {
  position: relative;
}

.container img {
  position: absolute;
  top: 0;
  left: 0;
  transition: opacity 0.5s;
}
.container img:last-child:hover{
  opacity: 0;
}

Upvotes: 1

Bolza
Bolza

Reputation: 1944

There are better ways to handle this.

Look at this fiddle

One image is always visible. The second image is simply faded in or out.

This is the only jquery code you need to achieve the effect

  /* Set images to full screen */        
    $(".fader").mouseover(function() {
        $("#mask2").stop().fadeIn(800);
    });
    $(".fader").mouseout(function() {
        $("#mask2").stop().fadeOut(800);
    });

The rest of the work is done by the css

.fader {
    border: 5px solid blue;
    background-color: white;
    top: 0;
    right: 0;
    position: fixed;
}
.mask {
    position: absolute;
    z-index: -10;
    min-width: 100%;
    top: 0;
    left: 0;
    background-size: cover;
}
#mask1 {
    background-image: url("http://test.coffeeshop.abcde.biz/cascara/img/bg_start.jpg");
}
#mask2 {
    background-image: url("http://test.coffeeshop.abcde.biz/cascara/img/bg_start2.jpg");
    display: none; /* Initial state */
}

Upvotes: 0

Related Questions