What is an Event in JavaScript
JavaScript is designed to interact with the HTML pages, and events are one of the main features that allow JavaScript to interact with HTML documents. An event is a signal or thing which tells that something is happening to the HTML page or its elements. For example, when a page is loaded it's an event, when the user hovers over the button clicks it, is also an event.
There are various ways when an event occurs on the HTML page, it could be the browser or the user who activates those events. We as a JavaScript developer use the events to interact with the HTML document and make changes to modify or make the web-page more interactive.
Note: More than the JavaScript events are the part of HTML document.
Common HTML events
Although there are many events in HTML here is the list of the most common ones.
Event |
Description |
onchange | Occur When an HTML element is changed |
onclick | Occur when the user clicks on the HTML element. |
onmouseover | Occur when the user puts the mouse cursor over the HTML element. |
onmouseout | Occur when the user moves out the mouse cursor over the HTML element. |
onload | Occur when the browser finished loading the page. |
Events Examples
Now let's see some HTML events in action, and how they used with JavaScript. So what we do with JavaScript and HTML events, we execute a JavaScript function based on the event.
onclick
Event Type
onclick
is one of the most frequently used HTML events. This event occurs when the user clicks over the HTML element, it could either be a text, image, video, or button.
<script> function changeColor() { button = document.querySelector("button"); //get the button button.style.backgroundColor ="green"; button.style.color ="yellow"; } </script> <body> <!--call changeColor function when user click the button --> <button onclick ="changeColor() "> Change Color(Click) </button> </body>
changeColor()
the function of JavaScript will be called.
document.querySelector("button");
and
button.style.backgroundColor
statements are new that we have not discussed yet but for now, we are using those two statements to access the HTML button element and changing its style.
onmouseover
and
onmouseout
Events
onmouseover
event get triggered when the over place its mouse cursor over the element and the
onmouseout
event trigger when the user mover away the most over the element.
<script> function over() { para = document.querySelector("p"); //get the <p> element para.style.backgroundColor ="green"; para.style.color ="yellow"; } function out() { para = document.querySelector("p"); //get the <p> element para.style.backgroundColor ="yellow"; para.style.color ="green"; } </script> <body> <!--call over() and out() functions when mouse over or away from the element --> <p onmouseover ="over()" onmouseout ="out()" > Place the Mouse over me and move out </p> </body>