var popup = '0'; if(popup == '0') { $(d...">

Run javascript function only once

I have this simple javascript function:

<script type="text/javascript"> var popup = '0'; if(popup == '0') { $(document).ready(function () { $(document).on('click', '.button', function(){ alert('test'); popup = '1'; }); }); } </script> <button class="button">Test</button> 

I want the function to be warned only on the first click, but it continues to work, although I changed the popup value to 1

+2
source share
3 answers

You need the .one() function. This ensures that the code runs only once for you.

Docs: http://api.jquery.com/one/

Example documents:

 $( "#foo" ).one( "click", function() { alert( "This will be displayed only once." ); }); 
+9
source

Enter the code as follows:

 <script type="text/javascript"> var popup = '0'; $(document).ready(function () { $(document).on('click', '.button', function(){ if(popup == '0') { alert('test'); popup = '1'; } }); }); </script> 

Once your click listener is installed, your previous if statement location was no longer running. Only code inside click function.

Alternatively, you can cancel the onClick listener instead of setting popup = '1' . Try the following:

 <script type="text/javascript"> var popup = '0'; $(document).ready(function () { $(document).on('click', '.button', function(){ alert('test'); //unbinds *all* listeners previously registered on "document" $(document).unbind('click'); }); }); </script> 

Significantly cleaner, as mentioned in Mathletics, cleans up unnecessary callbacks from memory.

+5
source

Try:

 <script type="text/javascript"> var popup = '0'; $(document).ready(function () { $(document).on('click', '.button', function(){ if(popup == '0') { alert('test'); } popup = '1'; }); }); </script> 

You had a function that set the popup to 1, but never checked its value again. Thus, it is checked and should work properly.

+1
source

All Articles