Rafael Calero
Rafael Calero

Reputation: 67

Javascript/jquery unintentionally loop, button onclick event

I have several buttons with action when you click (onclick) appears a menu with 4 options (like right click on any software):

<evento idevento="1000003" class="fc-day-grid-event fc-h-event fc-event
fc-start fc-draggable" draggable="true" ondragstart="drag(event)" 
data-start="08-23-2017T11:00" data-room="3" data-guestname="guest name 3" 
data-end="08-24-2017T12:00" onclick="mouseDown(event,1000003);">
<span class="fc-event eventoCalendario reserved">guest name 3</span></evento>

And the method called onclick:

function mouseDown(e,id){
//e = e || window.event;
if(e.which === 1){
    console.log(e);
    $("#menu").css({'display':'block', 'left':e.pageX, 'top':e.pageY});
}

//controlamos los botones del menú
$("#menu").click(function(e){
    // El switch utiliza los IDs de los <li> del menú
    switch(e.target.id){
        case "AddBooking":
            $("#bookingModal").modal();
            break;
        case "CheckIn":
            console.log('a');
            //$("#bookingModalcheck").modal();
            //checkinRoom(id);
            break;
        case "Move":
            console.log('a');
            $("#Move-dialog").modal();
            $("#move-original-room").attr('value', id);
            break;
        case "Remove":
            // Método cancelar
            cancelRoom(id);
            break;
    }
});}

The problem is that if I click on the others buttons with the same method several times, and then access the menu and press one of the options, for example chekin, this repeats the case checkin of the switch as many times as clicks have done previously anywhere on the others buttons. It is as if the clicks will be stored.

I'm curious to know why this happens.

Add a preview video: https://youtu.be/zDrWSkFKW04

Upvotes: 1

Views: 51

Answers (1)

Thomas
Thomas

Reputation: 2536

You are registering the click-listener mutliple times, so it is called multiple times. Try:

$("#menu").off('click').on('click', function(e){
// El switch utiliza los IDs de los <li> del menú
switch(e.target.id){
    case "AddBooking":
        $("#bookingModal").modal();
        break;
    case "CheckIn":
        console.log('a');
        //$("#bookingModalcheck").modal();
        //checkinRoom(id);
        break;
    case "Move":
        console.log('a');
        $("#Move-dialog").modal();
        $("#move-original-room").attr('value', id);
        break;
    case "Remove":
        // Método cancelar
        cancelRoom(id);
        break;
}
});

The .off('click') unregisters all current click-handlers and then assignes the needed. Good luck

Upvotes: 1

Related Questions