Skip to content Skip to sidebar Skip to footer

How To Execute A Function When Clicking An Area Inside An Object?

I created an object with map Areas by using DOM-Elements. Now I want to execute a function when clicked on an area(coordinates). I think I also Need to check the area if it is clic

Solution 1:

See the comments I added to your code ;)

var _images = { //Object-MapAreastart: {
    path: 'start.jpg',
    areas: [{
      coords: '18,131,113,140',
      text: 'Homepage',
      clickHandler: doSomething // I changed the name to avoid confusion but you can keep onclick 
    }]
  },
}

// ..... there is more code not shown here//Creating DOM-Elementsvar areaElem = document.createElement('AREA');

// Set attributes
areaElem.coords = area.coords;
areaElem.setAttribute('link', area.goto);
areaElem.setAttribute("title", area.text);
areaElem.setAttribute("shape", "rect");

// Add a listener on click event (using the function you defined in the area object above)
areaElem.addEventListener('click', area.clickHandler);

// Add your other click handler
areaElem.addEventListener('click', onArea_click);

_map.appendChild(areaElem);


functiondoSomething(e) {
  // Get the area clickedvar areaClicked = e.target;

  // I dont understand the following code...var r = confirm("Data will get lost!");
  if (r == true) {
    window.open("homepage.html", "_parent");
  } else {
    window.open(" ", "_parent"); // here I want to stay in the current pictures. I mean the current object map area. But how can I refer to it so it stays there ?  
  }

}

Hope it helps ;)

Solution 2:

I think I also Need to check the area if it is clicked or not

You are creating an element areaElem and attaching event to the same dom. So there may not be need of any more check

You may not need to add both onclick & addEventListner on same element and for same event. Either onclick function or addEventListener will be sufficient to handle the event.

areaElem.onclick = function(event){
// Rest of the code// put an alert to validate if this function is responding onclick

}


areaElem.addEventListener('click', onArea_click);
functiononArea_click(){
// Rest of the code

}

Post a Comment for "How To Execute A Function When Clicking An Area Inside An Object?"