Question

Since Firefox doesn't support window.event, is there any way to return the ID of any div that is clicked on? I hope it's clear.

Was it helpful?

Solution

@user3621590 wanted to add couple of things.

1."How would you access the variable outside of the function?" Be careful not to pollute the Global Namespace if you do not have to. For example - if you are just looking to perform an action like an alert(). You do not need to make the elementID variable global - (initiated without the var in the function). For example it could look like this.

document.addEventListener('click', function(event) {
  var elementID = event.target.id; 
  alert(elementID);
  // or console.log(elementID);
}, false); 

2.Since the question includes the subject of cross browser coding issues. You should also look into shortly after or during learning JS to include in your workflow a JS library like jQuery. The libraries do the heavy lifting when it comes to working with the DOM in all browsers. IE. The same requirement can be done with the following jQuery code.

$(document).click(function(e) {
  var elementID = e.target.id;
  console.log(elementID);
}); 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top