Once you are comfortable with referencing different elements in the HTML document using the DOM (Document Object Model), the next step is to connect the manipulation of the elements in teh DOM to events. JavaScript has many events that can be connected to blocks of code:
- onclick
- ondblclick
- onmousedown
- onmousemove
- onmouseout
- onmouseover
If we had the following HTML document:
<!doctype html>
<html>
<head>
<title>The JavaScript DOM</title>
</head>
<body>
<h1 id="heading">The JavaScript DOM</h1>
<p id="paragraph">Mauris convallis dictum odio. Quisque euismod finibus.</p>
<a id="link" href="https://codeadam.ca">codeadam.ca</a>
<button id="button">Click Me!</button>
</body>
</html>
If we wanted to change the colour of the h1
element when the button
element is clicked, we would first create a reference to the button element:
var button = document.getElementById('button');
And then add an event listener:
button.addEventListener("click",function(){
document.getElementById("heading").styles.color = "red";
});
Create a new HTML document, add four div
elements. Add the following four events and DOM manipulation:
- Change the
background-colour
of the firstdiv
elements is clicked. - Change the
background-colour
of the seconddiv
element when the mouse enters. - Change the
background-colour
of the thirddiv
element when the mouse leaves. - Change the
background-colour
of the fourthdiv
element when double clicked.
Full tutorial URL:
https://codeadam.ca/learning/javascript-mouse-events.html