Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 607
Googlebot Avatar asked Jan 03 '12 13:01

Googlebot


2 Answers

$('.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();
    });
like image 152
Andreas Louv Avatar answered Oct 02 '22 05:10

Andreas Louv


Have a variable (global) which says whether it has been loaded or not. E.g:

var loaded = false;
$('.button').click(function(){
   if(!loaded){
      $('#target').load('http://page');
      loaded = true;
   }
   $("#target").slideToggle();
});

This will cause the slideToggle to occur on every click, but the page to load only the once. :)

like image 21
Thomas Clayson Avatar answered Oct 02 '22 04:10

Thomas Clayson