Collecting elements for onclick events with eventListener

I’ve generated an HTML map with several elements which should be clickable and which should trigger a modal (“layer”).

This is the HTML

<map name="my-map" id="my-map">
  <area class="open" target="" alt="name1" title="name1"  href=""  coords="176,74,30" shape="circle"/>
      <area class="open" target="" alt="name2"  title="name2"  href="" coords="116,119,31" shape="circle"       /> </area>

(…)

So when clicking on of these elements with the class of “open” a modal should be triggerd serving specific information which are related to this element.

But I don’t even get the addEventListener work properly.

This is the JS (with help of Stack Overflow but without desired result)

const open = document.querySelectorAll("area");
const openArr = Array.from(open);
document.body.addEventListener("click", function(event) {
  if (event.target.classList.contains("open")) {
***// Why is this not consoling for exampple name1? I get not specific result ***
    console.log(area.title);
}
});

When clicking no error is logged. The page is just reloading with noting happening in console. I tried it too with console.log("Generic message"); to see whether the syntax is wrong.

So how can I add an eventListener to nearly 90 HTML-area elements where every element shares the same class “open” - but every element triggers a modal with specific infos related only to the clicked element?

Best and thank you

The reason why console.log isn’t showing much is because the area variable doesn’t refer to anything.

Let’s start over, with a single event handler that’s added to each area element.

function areaClickHandler(event) {
	event.preventDefault();
    const area = event.target;
    console.log(area.title);
}
const open = document.querySelectorAll("area.open");
open.forEach(function addHandler(area) {
    area.addEventListener("click", areaClickHandler);
});

If you want instead, you can use a single document handler that checks if the element is suitable.

function areaClickHandler(event) {
	event.preventDefault();
    const area = event.target;
    console.log(area.title);
}
 function pageClickHandler(event) {
     var el = event.target;
     if (el.nodeName === "AREA" && el.classList.contains("open")) {
     	areaClickHandler(event);
     }
 }
document.addEventListener("click", pageClickHandler);

Each function keeps tight and contained control over what it’s supposed to achieve.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.