Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery .load() How to prevent double loading from double clicking

I am using jQuery load() function to load some pages into container. Here is the code:

$('div.next a').live('click',function() {

    $('.content').load('page/3/ #info','',function(){
        //do something
    });

return false;

});

Everything works just fine but the problem is when I quickly double click the div.next link, from console I see that it loads the page twice because I did a quick double click. I could even make it 3 clicks and it will load it 3 times and show in console smth like that:

GET http://site/page/3/     200     OK  270ms   
GET http://site/page/3/     200     OK  260ms

My question is how to prevent such double clicking and not to let load the target page more then once no matter how many times it was clicked.

Thank you.

like image 295
devjs11 Avatar asked Oct 10 '22 00:10

devjs11


2 Answers

Whatever happened to good ol' JavaScript? Why are you all trying to figure it out with pure jQuery?

var hasBeenClicked = false;

$('div.next a').live('click',function() {

    if(!hasBeenClicked){
        hasBeenClicked = true;
        $('.content').load('page/3/ #info','',function(){
            //do something
            //If you want it clickable AFTER it loads just uncomment the next line
            //hasBeenClicked = false;
        });
    }

    return false;
});

As a side note, never never never use .live(). Use .delegate instead like:

var hasBeenClicked = false;

$('div.next').delegate('a','click',function() {

    if(!hasBeenClicked){
        hasBeenClicked = true;
        $('.content').load('page/3/ #info','',function(){
            //do something
            //If you want it clickable AFTER it loads just uncomment the next line
            //hasBeenClicked = false;
        });
    }

    return false;
});

Why? Paul Irish explains: http://paulirish.com/2010/on-jquery-live/

To answer your comment...

This could happen if you have your delegate function nested inside your AJAX call (.load(), .get(), etc). The div.next has to be on the page for this to work. If div.next isn't on the page, and this isn't nested, just do this:

$('#wrapper').delegate('div.next a','click',function() {

http://api.jquery.com/delegate/

Delegate needs the selector to be the parent of the dynamically added element. Then, the first parameter of delegate (div.next a in the last example) is the element to look for within the selected element (#wrapper). The wrapper could also be body if it's not wrapped in any element.

like image 122
Oscar Godson Avatar answered Oct 14 '22 01:10

Oscar Godson


You could try using the jquery one method:

$("a.button").one("click", function() {
       $('.content').load('page/3/ #info','',function(){
               //do something
       });
});
like image 44
SBerg413 Avatar answered Oct 14 '22 01:10

SBerg413