How to prevent repeat in jQuery function?
Asked Answered
W

2

6

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?

Wensleydale answered 3/1, 2012 at 13:28 Comment(0)
M
8
$('.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();
    });
Mertiemerton answered 3/1, 2012 at 13:32 Comment(0)
P
8

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. :)

Plasmasol answered 3/1, 2012 at 13:31 Comment(0)
M
8
$('.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();
    });
Mertiemerton answered 3/1, 2012 at 13:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.