JavaScript - mouse click event
In this post, we can find different ways of how to handle click event in pure JavaScript.
Quick overview:
xxxxxxxxxx
// in HTML:
// 1.
// <button onclick="onButtonClick(this)">Click me!</button>
// in JavaScript:
// 2.
button.setAttribute('onclick', 'onButtonClick()');
// 3.
button.onclick = function() { /* code here... */ };
// 4. - this approach is strongly recommended
button.addEventListener('click', function() { /* code here... */ };
More detailed method description is placed in the below.
This approach uses onclick
element attrbute to assign event function. It is not recommended to assign event this way because of possible double assign mistakes from source code level later - second event function removes first one.
We can access onclick
element attribute from HTML level.
xxxxxxxxxx
<html>
<body>
<button onclick="onButtonClick(this)">Click me!</button>
<script>
function onButtonClick(button) {
button.innerText = 'Button clicked!';
}
</script>
</body>
</html>
We can access onclick
element attribute from JavaScript level.
xxxxxxxxxx
<html>
<body>
<button id="button">Click me!</button>
<script>
var button = document.querySelector('#button');
function onButtonClick() {
button.innerText = 'Button clicked!';
}
button.setAttribute('onclick', 'onButtonClick()');
</script>
</body>
</html>
This approach uses onclick property to assign event function. It allows to assign only one logic for element event. It is not recommended to assign event this way because of possible double assign mistakes in code - second event function removes first one.
xxxxxxxxxx
<html>
<body>
<button id="button">Click me!</button>
<script>
var button = document.querySelector('#button');
button.onclick = function() {
button.innerText = 'Button clicked!';
};
</script>
</body>
</html>
This approach is strongly recommended because it is possible to assign many onclick
events to one element.
xxxxxxxxxx
<html>
<body>
<button id="button">Click me!</button>
<script>
var button = document.querySelector('#button');
button.addEventListener('click', function() {
button.innerText = 'Button clicked!';
});
</script>
</body>
</html>