How to make a jquery click event fire only on first click
Asked Answered
D

4

29

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);
        });
    });
});
Danish answered 14/10, 2012 at 19:20 Comment(0)
B
62

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.

Bradytelic answered 14/10, 2012 at 19:21 Comment(4)
Bah, destroyed my response time. +1.Merrythought
What if i only want the click function to fire if you didn't just click on .navbar1? Is that possible?Danish
@user1745398: I'm not entirely sure what you mean, but see my edit.Bradytelic
explained better then explained on jQuery DocsPena
L
9

Use modern Js events, with "once"!

const navbar = document.getElementsByClassName("navbar1")[0];
navbar.addEventListener("click", function() {
    // Add one-time callback
}, {once : true});

Documentation, CanIUse

Lafayette answered 24/9, 2017 at 20:37 Comment(1)
If you need to support IE11, use events-polyfill from github.com/lifaon74/events-polyfillMarianomaribel
I
8

Please see jQuery one() for one-time event handlers. i.e.

$(document).ready(function() {
    $('.navbar1').one('click', function(e){
        e.preventDefault();

        $('.basic2').hide().load('.basic2', function() {
            $(this).delay(600).fadeIn(1000);
            $('.basic1').fadeOut(1000);
        });
    });
});
Igbo answered 14/10, 2012 at 19:22 Comment(0)
M
8

jQuery provides the .one() method for this exactly.

$(document).ready(function() {
    $('.navbar1').one('click', function(e){
        e.preventDefault();
        $('.basic2').hide() 
        .load('.basic2', function() {
            $(this).delay(600).fadeIn(1000);
            $('.basic1').fadeOut(1000);
        });
    });
});
Merrythought answered 14/10, 2012 at 19:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.