You can select the element through its ID and attach a click-event listener using the addEventListener
method.
document.getElementById("Button").addEventListener("click", callback, true);
function callback() {
// Do some stuff in here when clicked
alert("clicked");
// Return false to prevent the browser default
// click-behaviour, if that is desired
return false;
}
For legacy browsers
Older versions of IE doesn't support addEventListener
, so for those you might need to do something like this:
var el = document.getElementById("Button");
if (el.addEventListener) {
el.addEventListener('click', callback, false);
} else if (el.attachEvent) {
el.attachEvent('onclick', callback);
}
Wait for the DOM to be ready
If you plan to run this in the head of your page, you'll need to wrap it a DOM-ready event listener as well, otherwise there is a change that the click event isn't attached to the element, as that element doesn't exist in the DOM when your script is run.