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 DOM - Event Listener function and preventing the click to navigate away
var element = document.querySelector('a');
element.addEventListener("click",
function (event) {
event.preventDefault(); // don't navigate away
console.log('Ouch! Stop poking me!');
}
);
<a href="#">Poke me!</a>
A click event is a click Pointer event definition and have the following properties:
document.addEventListener("click",
function (event) {
event.preventDefault(); // don't navigate away
console.log(`(screenX, screenY):(${event.screenX}, ${event.screenY})`);
console.log(`(clientX, clientY):(${event.clientX}, ${event.clientY})`);
}
);
<p style="max-width:300px">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam ipsum purus, bibendum sit amet vulputate eget, porta semper ligula. Donec bibendum vulputate erat, ac fringilla mi finibus nec. Donec ac dolor sed dolor porttitor blandit vel vel purus. Fusce vel malesuada ligula. Nam quis vehicula ante, eu finibus est. Proin ullamcorper fermentum orci, quis finibus massa. </p>
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>
$( document ).ready(function() {
$( "a" ).click(function( event ) {
alert( "Thanks for visiting!" );
});
$( 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>