Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

call a specific function only once on an event which may be called many times?

Tags:

jquery

I have a live click function that needs to do certian things always but one thing must only execute on the first click, after that, it needs to be disabled.

$('.theImage').live("click", function(){ 
            // The commands within the if statement must only happen on the first click.
    if (!chkHeightOnceOnly){
        var containerHeight = $(this).children(".postInfo").height();
        $(this).children(".postInfo").height(containerHeight - 2);
        var chkHeightOnceOnly = true; 
    }
            // other commands which need to fire on every click go here
});

So currently every-time i click on the div, it's subtracting a further 2px. It only needs to subtract 2px the first time.

EDIT - This is for many instances of .theImage, which are coming in via ajax, hence the need for .live()

like image 614
RGBK Avatar asked Jan 19 '23 10:01

RGBK


1 Answers

I would store the flag in the HTML tag itself.

$('.theImage').live("click", function(){ 
    // The commands within the if statement must only happen on the first click.
    if ($(this).attr('data-once')!='already' ){
        var containerHeight = $(this).children(".postInfo").height();
        $(this).children(".postInfo").height(containerHeight - 2);

        $(this).attr('data-once', 'already');
    }
    // other commands which need to fire on every click go here
});
like image 90
Moe Sweet Avatar answered Jan 30 '23 11:01

Moe Sweet