JavaScript – Event Triggers

You can make a button or other element do something when it’s clicked, moused over, changed, or hovered on.

Click Event

First, we need an element with an onclick attribute. The following element will call the update() function whenever it’s clicked by the user.

This example uses <button>, but you can assign an onclick attribute to any other type of element such as <p> or <div>.

<button onclick="update()">Click Here</button>

So far we haven’t created a function called “update,” but we will do that soon.

Next we add an element that will be changed by this update() function. This element needs anĀ id attribute so the update() function can find it.

<button onclick="update()">Click Me</button>
<p id="status">Original Text</p>

Now we need a JavaScript function called “update” since that’s the name we chose in the onclick attribute. This can be any function name of your choice that describes what the function actually does.

function update(){
    s = document.getElementById('status');
    s.innerHTML = "Here's the new text!";
}

Remember to put this JavaScript function inside <script></script> tags. The <head> section of your HTML file would be a great place to put your function definition.

The function finds the ‘status’ paragraph that we created above, then changes its text.

Try loading this webpage and see if clicking on the first element changes the text of the second element.

<script>
function update(){
    s = document.getElementById('status');
    s.innerHTML = "Here's the new text!";
}
</script>	

<button onclick="update()">Click Here</button>
<p id="status">Original Text</p>

Mouse Over / Mouse Out Events

Similar to click events, you can make JavaScript do something when you mouse over or mouse out of an element.

w3schools mouse over / mouse out example

This example uses two separate events:

onmouseover sets a function to be called when the users moves the pointer over the element.

onmouseout sets a JavaScript function to be called when the user moves the pointer out of the element.

You don’t have to define both of these, but you’ll want both if you don’t want the content to get “stuck” in one setting when the user mouses over it.

On Change Event

Certain <input> elements and <select> drop down menu elements can trigger JavaScript functions when they are changed. This is useful if you don’t want to force the user to click a “done” button after they make their choice.

w3schools onchange example with select element

Other Types of Changes

The functions in this example all cause the text of a paragraph to change, but JavaScript can make any other type of change happen.

Examples: your function could also hide or show content, calculate a number and display it somewhere, change the source of a picture, create a popover window, create an alert, or change the style (size / color / location / etc) of an element.