Tony Hensler
Tony Hensler

Reputation: 1492

Stopping function event firing a second time

I am currently trying to trigger an event on a mouse click where the user clicks a button and it triggers an event, once the user clicks on an input field, Please see code below or jsFiddle Below:-

$('.button').click(function () {
    $('*').css( 'cursor', 'crosshair' );
    $('input').one("click",function (event) {
        alert(event.pageX, event.pageY);
    });
});

I have an example on jsfiddle

The issue that I am having is once the user clicks in the input field the function needs to stop/finish. But instead the if the user click the second input field after clicking the initial one it runs the function again.

I have attempted putting

return false;

Inside the code to stop further propagation but this has not worked.

Any help would be greatly appreciated.

Thanks in advance.

Upvotes: 1

Views: 684

Answers (3)

Dij
Dij

Reputation: 9808

you can use .off() to remove eventlistener after you click once on the input field. something like this:

$('.button').click(function () {
    $('*').css( 'cursor', 'crosshair' );
    $('input').one("click",function (event) {
        alert(event.pageX, event.pageY);
        $('input').off('click');
    });
});

Upvotes: 3

Anadi Sharma
Anadi Sharma

Reputation: 295

Try:

var buttonClicked = false;
$('.button').click(function () {
    $('*').css( 'cursor', 'crosshair' );
    buttonClicked = true;
});
$('input').one("click",function (event) {
    if (buttonClicked)
    {
       buttonClicked = false;
       alert(event.pageX, event.pageY);
    }
});

Upvotes: 0

treyBake
treyBake

Reputation: 6560

you can use event like this:

$('.myBtn').on('click', function(event)
{
    event.stopPropagation();
})

this stops all event propagation linked with the event handler. More information can be found here: http://api.jquery.com/event.stopPropagation/

Upvotes: 0

Related Questions