ferronrsmith
ferronrsmith

Reputation: 1110

click() firing multiple times

I am using a document.getElementById("val").click() to invoke a click event, but it keeps firing multiple times.

Here I add the eventHandler:

try {
    //add mousedown event handler to navigation buttons
    addEventHandler(oPrevArrow, "mousedown", handlePrevDayClick);
    addEventHandler(oNextArrow, "mousedown", handleNextDayClick);
    addEventHandler(oLogout, "mousedown", handleLogoutClick);
} 
catch (err) {
}

In the click event I am performing a "auto click"

function handleNextDayClick(e) {
    e = e || window.event;
    stopEvent(e);
    document.getElementById("btn_nextday").click();
}

I need help to figure out what is making it call multiple times and a possible fix.

NB: the button that is auto-clicked calls a method in the ASP.NET Code-Behind

Upvotes: 3

Views: 7141

Answers (3)

Pupil
Pupil

Reputation: 23958

It happens due to the particular event is bound multiple times to the same element.

The solution which worked for me is:

Kill all the events attached using .die() method.

And then attach your method listener.

Thus,

$('.arrow').click(function() {
// FUNCTION BODY HERE
}

should be:

$('.arrow').die("click")
$('.arrow').click(function() {
// FUNCTION BODY HERE
}

Upvotes: 1

Mechlar
Mechlar

Reputation: 4974

Usually when you have an event firing multiple times it is because the event is attached to an element more than once or the element you are auto clicking is a child of another element with the same event attached. Check to see if they are wrapped by each other and if so you will need to detect that the current target is equal to the target to make sure it only happens once. Or you can stop the event propagation.

Upvotes: 3

Daniel Dyson
Daniel Dyson

Reputation: 13230

try hooking it up with JQuery:

 $(document).ready(function() {
    $('#oPrevArrow').click(function() {
        $('#btn_prevday').trigger('click');
    });
    $('#oNextArrow').click(function() {
        $('#btn_nextday').trigger('click');
    });
    $('#oLogout').click(function() {
        $('#btn_logout').trigger('click');
    });
 });

This could be even more concise, depending on how your arrows and Buttons are laid out in the DOM. Potentially it could be a single line of jQuery.

Something like:

 $(document).ready(function() {
    $('.arrow').click(function() { //note css class selector
        $('this + button').trigger('click');
    });
 });

Upvotes: 1

Related Questions