简体   繁体   中英

How to get my function to execute on click

I have a simple function to loop thought a bunch of Divs fading them in and out. It works fine, but I'm trying to make the function also execute when a DIV is clicked.

I thought if I do something like

$('.content').click(InfiniteRotator());

or

$('.content').click(function(){
InfiniteRotator();
});

But no luck and suggestion would be most appreciated

$(window).load(function() {

    function InfiniteRotator() {

        //initial fade-in time (in milliseconds)
        var initialFadeIn = 1000;

        //interval between items (in milliseconds)
        var itemInterval = 5000;

        //cross-fade time (in milliseconds)
        var fadeTime = 1000;

        //count number of items
        var numberOfItems = $('.quote').length;

        //set current item
        var currentItem = 0;

        //show first item
        $('.quote').eq(currentItem).fadeIn(initialFadeIn);

        //loop through the items
        var infiniteLoop = setInterval(function(){
         $('.quote').eq(currentItem).fadeOut(fadeTime);

            if(currentItem == numberOfItems -1){
                 currentItem = 0;
            } else{
                 currentItem++;
            }

            $('.quote').eq(currentItem).fadeIn(fadeTime);

        }, itemInterval);
    }

    InfiniteRotator();


    $('.content').click(InfiniteRotator());


});

Just pass the reference of that function like,

$('.content').click(InfiniteRotator);

And by the way, as others mentioned there's no problem with the following code of yours,

$('.content').click(function(){
   InfiniteRotator();
});
$('.content').click(InfiniteRotator); //<----remove the "()" here

or

$('.content').click(function(){
    InfiniteRotator();
});

Both are fine this way now but you have to call it in doc ready wrapper and you can move your function in the global scope outside of doc ready:

function InfiniteRotator() {
   // your function
}

$(function(){
   $('.content').click(InfiniteRotator); //<---here you can call it
});

You are better to use $(function(){}) doc ready handler instead of $(window).load() because this does not wait for dom to fully loaded.

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