In JavaScript, an event is an action or occurrence detected by the program that can be handled by a block of code, known as an event handler.
Common examples of events include a user clicking a button, a page finishing loading, or an element finishing loading.
Event handlers can be added to elements in the HTML document using event listeners, which are assigned to specific events and executed when those events occur.
JavaScript event handling refers to the process of listening for and responding to events that occur in the browser.
In JavaScript, event handling is typically done using event listeners, which are functions that are registered to listen for specific events on specific elements.
For example, to listen for a button click, you would add an event listener to the button element that listens for the "click" event, and then define a callback function to execute when the event occurs. The addEventListener()
method is used to register the event listener on the element.
Below is an example of an event listener, this method is registered to listen for the event of mouse moving.
Cool, huh?
Show me the code you say...
Well okay, check this out!
(function() {
// Add event listener
document.addEventListener("mousemove", parallax);
const elem = document.querySelector("#parallax");
// Magic happens here
function parallax(e) {
let _w = window.innerWidth/2;
let _h = window.innerHeight/2;
let _mouseX = e.clientX;
let _mouseY = e.clientY;
let _depth1 = `${50 - (_mouseX - _w) * 0.01}% ${50 - (_mouseY - _h) * 0.01}%`;
let _depth2 = `${50 - (_mouseX - _w) * 0.02}% ${50 - (_mouseY - _h) * 0.02}%`;
let _depth3 = `${50 - (_mouseX - _w) * 0.06}% ${50 - (_mouseY - _h) * 0.06}%`;
let x = `${_depth3}, ${_depth2}, ${_depth1}`;
console.log(x);
elem.style.backgroundPosition = x;
}
})();
Let me know your thoughts in the comment or drop some love... it's free!
bye, for now, ๐ Diki