Handling Click Events
Handling Click Events
Notice how the addEventListener() function is used to add a click event handler to a button DOM element:
HTML:
<button id="mybutton">Click</button>
JavaScript:
let value = 0;
document.getElementById('myButton').addEventListener('click', function(){
value++;
document.getElementById('myButton').innerHTML = value;
//sets the HTML text inside the button to display the number of times it has been clicked
});
The above code adds a click event listener that increments the value variable every time the button is clicked. The value of the value variable is then displayed inside the button.
The click event can also be handled with an event attribute.
Notice how an anonymous event handler is assigned to the "onclick" event attribute:
let value = 0;
document.getElementById('myButton').onclick = function(){
value++;
document.getElementById('myButton').innerHTML = value;
//sets the HTML text inside the button to display the number of times it has been clicked
}
The click event can also be handled by defining the event attribute in HTML.
Notice how the the handleClick() event handler is assigned to the "onclick" event attribute in HTML:
HTML:
<button id="myButton" onclick = "handleClick()">click </button>
JavaScript:
let value = 0;
function handleClick(){
value++;
document.getElementById('myButton').innerHTML = value;
//sets the HTML text inside the button to display the number of times it has been clicked
}