0

I know there are a few easy ways to detect a click on any HTML element with something like this:

    document.getElementById("submit")
    .addEventListener("click", function(event) {
    alert("Submit button is clicked!");
    event.preventDefault();
  });

But what if I'm letting a user create html elements on a site where they can input custom strings and id's for these elements are generated at random like this:

    let unique_id = uuidv4()
    

    let invisibilityIcon = document.createElement("IMG")
    invisibilityIcon.setAttribute("src", "icons/eye-off.svg")
    invisibilityIcon.setAttribute("height", "24")
    invisibilityIcon.setAttribute("width", "24")
    invisibilityIcon.setAttribute("style", "float: right; margin-left: 20px; margin-top: 12px; 
    position: relative; margin-right: 20px")
    invisibilityIcon.setAttribute("id", unique_id )

this is just 1 of the many elements a user can create on my site, it is a eye svg icon which has a unique ID generated each time a user creates a new one. I want to detect whenever this icon is clicked and collect its id value to work with it further on, is this possible?

S..
  • 315
  • 4
  • 19

1 Answers1

0

add to invisibilityIcon Event Listener

let unique_id = uuidv4()
let arrayIds = []  

let invisibilityIcon = document.createElement("IMG")
invisibilityIcon.setAttribute("src", "icons/eye-off.svg")
invisibilityIcon.setAttribute("height", "24")
invisibilityIcon.setAttribute("width", "24")
invisibilityIcon.setAttribute("style", "float: right; margin-left: 20px; margin-top: 12px;position: relative; margin-right: 20px")
invisibilityIcon.setAttribute("id", unique_id )
invisibilityIcon.addEventListener("click",function(e){
    //do what you need
    arrayIds.push(e.target.id);
    //or
    arrayIds.push(this);
})
doronazu
  • 140
  • 1
  • 6