skip to Main Content

I have this method for creating new buttons:

function createButton(buttonId, buttonClass, clickEvent) {
    var button = document.createElement("button");
    button.id = buttonId;
    button.className = buttonClass;
    button.onclick = function(){
        clickEvent;
    };

    return button;
 }

That I call in this way:

var editButton = createButton(
      "edit-" + string + "-allow",
      "btn btn-sm btn-primary btn-edit-lg",
      allowEdit("edit-" + string + "-allow")
);

But checking on the element inspector the onclick property is not added
enter image description here

What’s the problem?

2

Answers


  1. You need to pass the function name and the parameter. Otherwise it will execute when assigned

    Also I suggest to use eventListener instead of onclick

    const allowEdit = str => console.log(str)
    
    const createButton = (buttonId, buttonClass, clickEvent, parameter) =>{
      var button = document.createElement('button');
      button.textContent = buttonId
      button.id = buttonId;
      button.className = buttonClass;
      button.addEventListener("click", () => clickEvent(parameter))
      return button;
    };
    
    let string = 'temp';
    let editButton = createButton(
      `edit-${string}-allow`,
      "btn btn-sm btn-primary btn-edit-lg",
      allowEdit, `edit-${string}-allow`
    );
    
    document.body.appendChild(editButton);

    If the button click is the same and only the parameter changes; I suggest delegation:

    const allowEdit = str => console.log(str)
    
    const createButton = (buttonId) => {
      var button = document.createElement('button');
      button.textContent = buttonId;
      button.id = buttonId;
      return button;
    };
    
    const container = document.getElementById("buttonContainer");
    let strings = ['temp1','temp2','temp3'].forEach(str => container.appendChild(createButton(`edit-${str}-allow`)));
    
    container.addEventListener("click",(e) => {
      const tgt = e.target.closest("button");
      if (!tgt) return; // not a button
      allowEdit(tgt.textContent.trim());
    })
    <div id="buttonContainer"></div>
    Login or Signup to reply.
  2. you can try

    button.onclick = clickEvent;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search