user2471366
user2471366

Reputation: 73

Call different events on an element depending on its id

I have a button:

<button id="end-action">End action</button>

And I am trying to change the text and id of the button in response to a click event.

$("#end-action").click(endAction);
$("#end-turn").click(endTurn);

When I click on the button, it successfully calls the endAction function (below) and correctly sets the id of the button to "end-turn". However, when the id of the button is "end-turn", if I click on the button, the "end-action" id event handler is still called.

       function endAction(){
    $("#end-action").text("End Turn");
    $("#end-action").attr("id", "end-turn");
       }

       function endTurn(){
    $("#end-turn").text("End Action");
    $("#end-turn").attr("id", "end-action");
       }

Do you know why this is and what I can do to fix this?

Upvotes: 0

Views: 46

Answers (2)

David Thomas
David Thomas

Reputation: 253307

I'd suggest:

function endAction() {
    $("#end-action").text("End Turn");
    $("#end-action").prop("id", "end-turn");
}

function endTurn() {
    $("#end-turn").text("End Action");
    $("#end-turn").prop("id", "end-action");
}
$("body").on('click', '#end-action, #end-turn', function(){
    switch (this.id) {
        case 'end-turn':
            endTurn();
            break;
        case 'end-action':
            endAction();
            break;
    }
});

JS Fiddle demo.

The problem, I think, is that you bound an event to the DOM node, after selecting it by its id, but that binding happens once; and while the id might change the DOM node stays the same (despite the id property changing) which means that only one function is bound to that node.

The alternative I've used, here, binds the click-handler to the body element (though you should bind to the closest ancestor element of the button, not the body, unless you have no alternative), and then assesses which element the click event originated on. In this case this refers to the event that was clicked, which has its id property checked and, if it matches, the relevant function is called.

References:

Upvotes: 2

Ani
Ani

Reputation: 4523

Okay - Is this what you want : http://jsfiddle.net/Fs24R/

$("#end-action").click(endAction);


function endAction(){
   $("#end-action").text("End Turn");
   $("#end-action").attr("id", "end-turn");
   $("#end-turn").click(endTurn);
 }


function endTurn(){
  $("#end-turn").text("End Action");
  $("#end-turn").attr("id", "end-action");
  $("#end-action").click(endAction);

}

Explanation: When you change the id - you have to set the onclick function - because the page is not being loaded again - hence the initial onload function won't run.

When you add the call onload: for second id - it's not present in the DOM at that time - hence the function is not bind to the second id.

Therefore, you have to bind the function at the point where you change the ID of the element.

Upvotes: 1

Related Questions