Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a jquery click event fire only on first click

Tags:

jquery

I have two divs (.basic1 and .basic2). I want .basic1 to fadeout on click, and .basic2 to fade in which I have working wonderfully. The only problem is that once .basic2 fades in, if the user continues to click the link (.navbar1), it will fade in this div over and over. I know that I need to use the .bind() function, but I can't seem to figure out where in my code to put it. Thanks!

$(document).ready(function() {     $('.navbar1').click(function(e){         e.preventDefault();          $('.basic2').hide().load('.basic2', function() {             $(this).delay(600).fadeIn(1000);             $('.basic1').fadeOut(1000);         });     }); }); 
like image 669
user1745398 Avatar asked Oct 14 '12 19:10

user1745398


People also ask

How do I run a method only once in jQuery?

jQuery one() method The one() method attaches one or more event handlers for the selected elements and specifies a function to run when the event occurs. When using the one() method, the event handler function is only run Once for each element.

How do I trigger a click event without clicking?

If you want native JS to trigger click event without clicking then use the element id and click() method of JavaScript.

How do you fire a click event on an element?

click() method simulates a mouse click on an element. When click() is used with supported elements (such as an <input> ), it fires the element's click event. This event then bubbles up to elements higher in the document tree (or event chain) and fires their click events.


1 Answers

Use .one():

$('.navbar1').one('click', function(e) { 

It unbinds the click event once you trigger it.

If you don't want an element to be double-clicked, something like this should work:

$(document).on('click', '.navbar1:not(.clicked)', function() {     // ... }); 

To make .navbar1 unclickable, just run $('.navbar1').addClass('clicked'). To make it clickable, do the opposite.

like image 195
Blender Avatar answered Sep 18 '22 11:09

Blender