0

I'm trying to get a jQuery even to only fire once per click of that event, but if the user clicks another element and then comes back to the same one it will fire again.

For example:

$( '.summary' ).on( "touchstart mousedown", function(event) {
    var data_summary = $(this).attr('data-summary');
    $('#info').empty().stop(true, true).fadeOut().html('<p>'+data_summary+'</p>').fadeIn();
});

I know about one(), but this will disable it permanently. What this code does is fade in a bubble, but I don't want it to keep doing that if the user clicks it multiple times. However if a user clicks another element, it will fade a new one in, thus making the previous one valid again if clicked.

Update:

The fade in and out was also off, here is the final working code from the answer below with tweaks if anyone else needs it.

var prev = null;
$( '.summary' ).on( "touchstart mousedown", function(event) {
    if(this !== prev) {
        prev = this;
        var data_summary = $(this).attr('data-summary');
        $('#info').stop(true, true).fadeOut('fast', function() {
            $(this).html('<p>'+data_summary+'</p>').fadeIn();
        });
    }
});

1 Answer 1

3

Just keep track of the previously clicked element:

var prev = null;
$( '.summary' ).on( "touchstart mousedown", function(event) {
    if(this !== prev) {
        prev = this;
        var data_summary = $(this).attr('data-summary');
        $('#info').empty().stop(true, true).fadeOut().html('<p>'+data_summary+'</p>').fadeIn();
    }
});

There are various ways to do this. An other one would be to add (and remove) a class to the element (which you then could also use for styling it, if desired).

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! This is exactly what I wanted and was toying with, but my code was off.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.