Fedreg Fedreg - 29 days ago 9
HTML Question

Adding addtional content (+=) to an HTML attribute

I have an HTML onclick attribute and I'm trying to dynamically add additional properties to it on keypress without removing the existing property.
In other words....

Say I have

<button onclick="doThis(1)">


Every time a button is pressed I'd like to add to that so the first time the button is pressed you'd get

<button onclick="doThis(1), doThis(2)">


third time:

<button onclick="doThis(1), doThis(2), doThis(3)">


etc.

Is there some way to do

document.getElementById("mybtn").onclick += doThis($n{index};


or do I just have to build up the string independently?

I can't seem to figure it out without building up a big string to add to a setAttribute. When I try a variation of the JS code above I crash the browser :(

Thx for taking a look!!

Answer

Ok, I really don't like this answer, but it does do what you are looking for. I don't like it because it relies on setting event handlers as properties of DOM objects, rather than using the W3C DOM Level 2 Event Model. But, aside from that, here you go...

window.doThisCounter = 1;
var eventList = "";

function doThis(){
      console.log(eventList);
      window.doThisCounter++;
      eventList += "doThis(" + window.doThisCounter + ");";
      btnGo.setAttribute("onclick", eventList);
}


// This will execute once, when page is ready:
window.addEventListener("DOMContentLoaded", function(){
  
  var btn = document.getElementById("btnGo");

  (function(counter){
    eventList = "doThis(1);";
    btnGo.setAttribute("onclick", eventList);
  }(window.doThisCounter));
  
});
<button id="btnGo">Click Me!</button>