How to prevent repetition in jQuery function?

I have a simple jQuery function like

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

According to the behavior of slideToggle each click triggers a slide, but the problem is that it will load the url again.

How to restrict the load() function, which will be executed only once, but slideToggle() with each click. In other words, how to prevent load() (only loading, not the whole function) in subsequent clicks?

+7
source share
3 answers
 $('.button') .on('click.loadPage', function() { $("#target").load('http://page'); $(this).off("click.loadPage"); }) .on('click.slideToggle', function(){ $("#target").slideToggle(); }); 

and in another way without global vars:

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

Have a variable (global) that says whether it has been loaded or not. For example:

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

This will cause slideToggle to appear on every click, and to be loaded on the page only once. :)

+8
source

An easy way to get only the last action is to use the stop method before the desired method:

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

All Articles