How to repeat (loop) jQuery fadein - fadeout - fadein

I am struggling with my first jQuery script. I have a DIV on my page that is hiding using CSS. Then I have this script that runs to make it disappear, disappear, and then disappear again:

<script type="text/javascript"> (function($) { $(function() { $('#abovelogo').fadeIn(1000).delay(2000).fadeOut(1500).delay(2000).fadeIn(1500); }); })(jQuery); </script> 

This part is working fine. Now, my question is:

How do I change it so that this script runs loops (forever), and not just once?

Thanks in advance! -Nate

+4
source share
3 answers

Put your code inside setInterval :

 $(function () { setInterval(function () { $('#abovelogo').fadeIn(1000).delay(2000).fadeOut(1500).delay(2000).fadeIn(1500); }, 5000); }); 

Since you will run this as long as the page is active, you should do everything possible to optimize your code, for example, you can cache the selection outside the interval:

 $(function () { var $element = $('#abovelogo'); setInterval(function () { $element.fadeIn(1000).delay(2000).fadeOut(1500).delay(2000).fadeIn(1500); }, 5000); }); 

Docs for setInterval : https://developer.mozilla.org/en/window.setInterval

Alternatively, instead of using .delay() you can use the callback functions in each animation to call one animation after another:

 $(function () { var $element = $('#abovelogo'); setInterval(function () { $element.fadeIn(1000, function () { $element.fadeOut(1500, function () { $element.fadeIn(1500) }); }); }, 5000); }); 

Here is a demo: http://jsfiddle.net/xsATz/

You can also use setTimeout and call the function recursively:

 $(function () { var $element = $('#abovelogo'); function fadeInOut () { $element.fadeIn(1000, function () { $element.fadeOut(1500, function () { $element.fadeIn(1500, function () { setTimeout(fadeInOut, 500); }); }); }); } fadeInOut(); }); 

Here is a demo: http://jsfiddle.net/xsATz/1/

+21
source
 <script type="text/javascript"> function doFade() { $('.foo').toggleClass('fooAct'); setTimeout(doFade, 1000); } $(document).ready(function(){ doFade(); }); </script> <style> div { height:200px; background:black; } .foo { transition: opacity 2s; -moz-transition: opacity 2s; /* Firefox 4 */ -webkit-transition: opacity 2s; /* Safari and Chrome */ -o-transition: opacity 2s; /* Opera */ opacity:0.1; } .fooAct { opacity:1; } </style> <div class="foo"></div> 

just for imagination. You can do this with css3. Hope this helps too. By doing such things, css should be more convenient for browser performance instead of jQuery.

+1
source

I have some problems with the setTimeout method. Maybe better with a β€œtrigger”:

 var $element = $('.banner'); $element.bind('cusfadeOut',function() { $(this).fadeOut(500,function() { $(this).trigger('cusfadeIn'); }); }); $element.bind('cusfadeIn',function() { $(this).fadeIn(1000, function() { $(this).trigger('cusfadeOut'); }); }); $element.trigger('cusfadeOut'); 
+1
source

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


All Articles