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

180
Views
use fetch API and event handler

I loaded my local .json file with fetch, and I registered an event handler on a button element.

Here is my code:

        let tagName;
        function start(){
            fetch("./product.json")
            .then(response=>response.json())
            .then(data=>addItem(data,tagName))
            .catch(error=>console.log(error));            
        }
        start();
        
        function addItem(data,tagName){                
            var container = document.getElementById("itemBox");
            for(let i=0;i<data.length;i++){                       
                var div = document.createElement("div");
                var img = data[i].itemImg;                                  
                div.className = "imgBox";
                div.innerHTML = "<img src= "+img+">";
                container.appendChild(div);
            }
        };
        
        let tagBtn = document.getElementById("tagsubmit");
        tagBtn.onclick = function(){
            document.getElementById("tmp").innerHTML = "HELPME";
        }

When I opened this html file, json file is loaded&rendered succesfully, but the button with event handler doesn't work.

How can I make both of them work successfully?

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

0

Try to use the event delegation feature, like this:

document.getElementById('itemBox').addEventListener('click', (event) => {
    if (event.target.id === 'tagsubmit') {
        document.getElementById('tmp').innerHTML = 'HELPME';
    }
});

Nice tutorial by Dmitri Pavlutin: https://dmitripavlutin.com/javascript-event-delegation/

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!