DOM - Click Event (OnClick)
Table of Contents
About
1001 ways to handle a the click event.
The click event occurs when the pointing device button is clicked over an element.
The onclick on attribute may be used with most elements.
- The difference between a swipe/drag and a click is the distance traveled by the mouse. See How to make the difference between a Swipe/Drag vs Click/Tap event
Example
Event Listener
The DOM - Event Listener function and preventing the click to navigate away
- The Javascript
var element = document.querySelector('a');
element.addEventListener("click",
function (event) {
event.preventDefault(); // don't navigate away
console.log('Ouch! Stop poking me!');
}
);
- The HTML
<a href="#">Poke me!</a>
OnClick Event handler Property
document.querySelector('html').onclick = function() {
console.log('Ouch! Stop poking me!');
}
// Equivalent to
var myHTML = document.querySelector('html');
myHTML.onclick = function() {
console.log('Equivalent Alert. Stop poking me!');
}
<p style="border-radius:50%;background:deepskyblue;padding:1rem;display:inline-block">Poke me!</p>
Jquery
- Click method
$( document ).ready(function() {
$( "a" ).click(function( event ) {
alert( "Thanks for visiting!" );
});
- or on
$( document ).ready(function() {
$( "html" ).on( "click", function( event ) {
console.log('Ouch! Stop poking me!');
});
});
<p style="border-radius:50%;background:deepskyblue;padding:1rem;display:inline-block">Poke me!</p>