bugl
bugl
HomeLearnPatternsSearch
HomeLearnPatternsSearch

Loading lesson path

Learn/JavaScript/DOM and Browser APIs
JavaScript•DOM and Browser APIs

JavaScript Events

Concept visual

JavaScript Events

Pointer walk
two pointers
leftright102132436485116
left=0
right=6
1
3

Start at both ends

HTML Events

HTML events are things that happen to HTML elements.

Examples of events:

An HTML button is clicked

A web page has finished loading

The mouse moves over an element

A keyboard key is pressed

An HTML input field is changed

HTML DOM allows JavaScript to react to HTML events:

Mouse Over Me

Click Me

JavaScript Events

Often, when events happen, you may want to do something. When JavaScript is used in HTML pages, JavaScript can react on events. JavaScript lets you execute code when events are detected. HTML allows event handler attributes, with JavaScript code, to be added to HTML elements.

Syntax

With single quotes:

< element event = ' some JavaScript ' >

With double quotes:

< element event = " some JavaScript " > In the following example, an onclick attribute (with code), is added to a <button> element:

Example

Formula

< button onclick ="document.getElementById('demo').innerHTML = Date()"> The time is?</button >

In the example above, the JavaScript code changes the content of the element with id="demo". In the next example, the code changes the content of its own element using this.innerHTML

Example

Formula

< button onclick ="this.innerHTML = Date()"> The time is?</button >

Calling a JavaScript Function

JavaScript code can often be several lines long. It is more common to use the event attribute to call a function:

Example

<button onclick="displayDate()">The time is?</button> <script>

function displayDate() {
document.getElementById("demo").innerHTML = Date();
}

</script>

Common HTML Events

Here is a list of some common HTML events:

Event

Description onchange

An HTML element has been changed onclick

The user clicks an HTML element onmouseover

The user moves the mouse over an HTML element onmouseout The user moves the mouse away from an HTML element onkeydown

The user pushes a keyboard key onload

The browser has finished loading the page

Previous

HTML DOM Reference

Next

JavaScript Mouse Events