GitHub - codeadamca/javascript-mouse-events: A basic example of using JavaScript to connect mouse events to DOM changes.
A Basic Introduction to JavaScript and Mouse Events
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
Example Event
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"; });
Trying It Out
Create a new HTML document, add four div elements. Add the following four events and DOM manipulation:
- Change the
background-colourof the firstdivelements is clicked. - Change the
background-colourof the seconddivelement when the mouse enters. - Change the
background-colourof the thirddivelement when the mouse leaves. - Change the
background-colourof the fourthdivelement when double clicked.
Full tutorial URL:
https://codeadam.ca/learning/javascript-mouse-events.html
Repo Resources