简体   繁体   中英

Execute two divs in same javascript

I'm trying fade effect in two different div classes at same same-time. For that i need two different scripts, and executing same script for two div(s), it lags. Is there any way to execute both divs in same script like (.fadein,.fadeo)? FIDDLE- jsfiddle.net/562am/ .

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script> //Function 1
$(function(){
    $('.fadeo img:gt(0)').hide();
    setInterval(function(){$('.fadeo :first-child').fadeOut().next('img').fadeIn().end().appendTo('.fadeo');}, 2000);
});
</script>

<script> //Function 2
$(function(){
    $('.fadein img:gt(0)').hide();
    setInterval(function(){$('.fadein :first-child').fadeOut().next('img').fadeIn().end().appendTo('.fadein');}, 2000);
});
</script>

Is this what you meant by combining the two into 1 function?

$(function(){
    var classes = ['.fadeo', '.fadein'];

    $.each(classes, function (index, elem){
        var selectorToHide = elem + ' img:gt(0)',
            selectorToFadeOut = elem + ' :first-child';

        $(selectorToHide).hide();
        setInterval(function() {
            $(selectorToFadeOut)
                .fadeOut()
                .next('img')
                .fadeIn()
                .end()
                .appendTo(elem);
            }, 
            2000);
    });
});

2 setInterval run on their own - they may produce lags. The correct way is to use 1 interval and do the whole logic there.
With appendTo you're changing the DOM every 2 seconds. This method causes extra performance issues and leads to slower application run. I would suggest you to keep an index with the current image, and change it as you want (this is shown below).
In my example I've calculated the minimum number of images (if separate divs have different image count).

$(function () {
    // a value can be fixed - a constant 
    var imagesCount = Math.min($('.fadeo > img').size(),
                           $('.fadein > img').size());
    var i = 0;
    display(i);
    setInterval(function () {
        i = (i+1) % imagesCount;
        display(i);
    }, 2000);
});

function display(nth) {
    $('.fadeo > img').hide().eq(nth).show();
    $('.fadein > img').hide().eq(nth).show();    
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM