Cesare Cesare - 3 months ago 23
HTML Question

how to know if a button has been clicked in javascript?

I need to know if the button to draw points on this map ...

https://bl.ocks.org/danswick/083a0b48c2cc78c4a08d

is clicked.

I've tried to use this Javascript code ..

var editButton = document.getElementsByClassName('mapbox-gl-draw_ctrl-draw-btn mapbox-gl-draw_point'); // grab a reference to your element
editButton.onclick = function(){
alert("Clicked!");
}


... but nothing happens (no error ... ).

If I try to check for the editButton variable value in my Chrome console I can see that it's a HTMLCollection[1], so not empty ...

Suggestions / example / alternatives?

Answer

document.getElementsByClassName returns a collection. You need to set the click handler for the actual element.

var elements = document.getElementsByClassName('mapbox-gl-draw_ctrl-draw-btn mapbox-gl-draw_point');
var editButton = elements[0];