Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

214
Views
How to add onclick function with javascript append?

The onclick handler function closeTab() doesn't work on appended elements.

HTML:

<li id="listid" class="first-tab">
  <img class="cmd-icon" id="cmdicon" src="resources/img/cmd.png">
  <a id="atext">Mozilla Firefox</a> 
  <img onclick="closeTab()" id="deleteTab" class="deleteicon" src="resources/img/delete-icon.svg">
  <img onclick="addTab()" id="addTab" class="addplus" src="resources/img/add.svg">
</li>

JavaScript:

function closeTab() {
    var whereTab = document.getElementById('listid');
    if (whereTab.style.display == 'block') {
        whereTab.style.display = 'none';
    } else {
        whereTab.style.display = "none";
    }
}

function addTab() {
    var img = document.createElement("img");
    img.src = "resources/img/delete-icon.svg";

    var img2 = document.createElement("img");
    img2.src = "resources/img/cmd.png";

    img.className = 'deleteicon';
    img.id = "deletetab";
    img.onclick = closeTab();

    var ulLocation = document.getElementsByClassName('abc')[0];
    var whereTab = document.getElementById('listid');

    var addTab = document.createElement('li');
    addTab.className = 'first-tab';
    addTab.id = "listid";

    addTab.className = 'active';
  
    addTab.innerHTML = "mozilla-firefox/newtab";
    addTab.appendChild(img2);

    ulLocation.appendChild(addTab);

    addTab.appendChild(img);
}

Why doesn't the closeTab() function work on appended items via addTab()?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Instead of img.onclick = closeTab();, you need img.onclick = closeTab;- you need to assign the function not execution.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!