Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fadein() effect to a function: how to?

I have this function that works well for lazy loading.

panel.find('img[data-src]').each(function(){
            element = $(this);
            element.attr('src', element.data('src'));
            element.removeAttr('data-src');

How can I give a fadeIn() effect to that removeAttr function?
I tried:

element.removeAttr('data-src').fadeIn();

but it doesn't work. The img code looks like this and I simply want the dot.png to fadeOut and the original.jpg to fade in.

<img src="dot.png" data-src="original.jpg">

http://jsfiddle.net/7s1yb1un/6/
Thanks in advance

like image 538
Federico Avatar asked Nov 14 '16 15:11

Federico


People also ask

How do you use fadeIn in JavaScript?

The jQuery fadeIn() method is used to fade in a hidden element. Syntax: $(selector). fadeIn(speed,callback);

What is fadeIn function in jQuery?

The fadeIn() Method in jQuery is used to change the opacity of selected elements from hidden to visible. The hidden elements will not be display. Syntax: $(selector).fadeIn( speed, easing, callback )


2 Answers

You cannot fade a src change on an img element. To acheive this you'll need two img elements. The second one will have a the src "original.jpg" and will have a higher z-index and start with display: none for a style. Then you can fade it in and it will fade in over the dot.

EDIT Given your new question, you could do the following:

  1. Add an onload listener for the image
  2. Just before changing the "src", fade the image out
  3. Then change the "src" to "original.jpg"
  4. In your onload function, do a fadeIn
like image 112
Don Rhummy Avatar answered Oct 05 '22 18:10

Don Rhummy


Here is what I have done.

Added a fadeOut(5000), the img with original src will fadeout after 5 sec. Called a function with timeout of 6sec, which changes the src with data-src and fadeIn(5000) in 5 sec, I hope this solves your problem.

JS code is below

var myVar;
function myFunction() {
    myVar = setTimeout(function(){ 
        var src = $("img.hide").attr("data-src");
        $("img.hide").attr("src",src);
        $("img.hide").fadeIn(5000); 
    }, 6000);
}

function myStopFunction() {
    clearTimeout(myVar);
}

$(document).ready(function() {
  $(".hide").fadeOut(5000);
  myFunction();  
});
like image 42
Niranjan Kumar Avatar answered Oct 05 '22 18:10

Niranjan Kumar