Search code examples
javascriptjqueryloadslidetoggle

How to prevent repeat in jQuery function?


I have a simple jQuery function as

$('.button').click(function(){
   $("#target").slideToggle().load('http://page');
});

By slideToggle behavior, every click cause a slide, but the problem is that it will load url again too.

How can I limit the load() function to be performed only once, but slideToggle() on every click. In other words, how to prevent load() (only load, not the entire function) in the subsequent clicks?


Solution

  • $('.button')
        .on('click.loadPage', function() {
            $("#target").load('http://page');
            $(this).off("click.loadPage");
        })
        .on('click.slideToggle', function(){
            $("#target").slideToggle();
        });
    

    and another way without global vars:

    $('.button')
        .on('click', function() {
            if ( !$(this).data("loaded") ) {
                $("#target").load('http://page');
                $(this).data("loaded", true);
            }
            $("#target").slideToggle();
        });