Skip to content

7.7 Events Part 1

In this lesson; we will be using the following HTML document:

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Our Website</title>
    <style>
       section{
         margin: 2rem 0;
         padding: 2rem 0;
         border-bottom: 0.3rem solid CadetBlue;
       }
       #container{
         display: flex;
         justify-content: center;
       }
       .box{
         width: 10rem;
         height: 10rem;
         margin: 1rem;
       }
       #box-1{
         background: lightblue;
       }
       #box-2{
         background: Olive;
       }
       #box-3{
         background: tomato;
       }
       #form{

       }
       #form input, #colorSelect{
         display: block;
         margin: 1rem 0;
         width: 20rem;
         height: 2rem;
         border: none;
         outline: none;
         border-bottom: 0.1rem solid tomato;
         font-size: 1.5rem;
       }
       input[type="submit"]{
         background: tomato;
         color: #fff;
       }
       input[type="submit"]:hover{
         opacity: 0.8;
         cursor: pointer;
       }
    </style>
  </head>
  <body>
    <header>
      <h1>Welcome to our website</h1>
    </header>
    <section id="container">
      <div class="box" id="box-1"></div>
      <div class="box" id="box-2"></div>
      <div class="box" id="box-3"></div>
    </section>
    <section id="formSection">
      <form id="form">
        <input type="text" id="yourName" placeholder="Your Name">
        <input type="number" id="age" placeholder="35">
        <select name="selectMenu" id="colorSelect">
          <option value="DarkSlateGray">DarkSlateGray</option>
          <option value="SaddleBrown">SaddleBrown</option>
          <option value="Yellow">Yellow</option>
          <option value="CadetBlue">CadetBlue</option>
          <option value="Chocolate">Chocolate</option>
          <option value="CornflowerBlue">CornflowerBlue</option>
          <option value="Gainsboro">Gainsboro</option>
          <option value="LemonChiffon">LemonChiffon</option>
          <option value="SteelBlue">SteelBlue</option>
          <option value="Snow">Snow</option>
          <option value="SpringGreen">SpringGreen</option>
        </select>
        <input type="submit" value="Send">
      </form>
    </section>
    <section id="answers">
      <h2>Your answers will be shown here:</h2>
      <p id="yourName"></p>
      <p id="yourAge"></p>
      <p id="yourColor"></p>
    </section>
    <script src="script.js"></script>
  </body>
</html>

The onmouseover & onmouseout events

Task 1: Select the first box.

let el = document.getElementById("box-1");

console.log(el);

The result is: <div class="box" id="box-1"></div>

Task 2: Change the color of the first box to Chocolate.

let el = document.getElementById("box-1");
el.style.backgroundColor = "Chocolate";

Task 3: Create a function that changes the background of an element to Chocolate.

function changeBackground(el){
  el.style.backgroundColor = "Chocolate";
}

Task 4: The background color of the first box is changed to Chocolate when the mouse pointer is moved onto the box. Check the following code.

let el = document.getElementById("box-1");
el.onmouseover = function(){
  el.style.backgroundColor = "Chocolate";
}

onmouseover

The mouseover event happens when the mouse pointer is moved onto an element.

Task 5: The background color of the first box is changed to DarkSlateGray when the mouse pointer is moved away from the box the box. Check the following code.

let el = document.getElementById("box-1");
el.onmouseover = function(){
  el.style.backgroundColor = "Chocolate";
}
el.onmouseout = function(){
  el.style.backgroundColor = "DarkSlateGray";
}

onmouseout

The mouseout event happens when the mouse pointer is moved out of an element.

Task 6: When the pointer is moved onto the second box, change its border to black 2rem, and when the pointer is away from the box, change the border to black 0.5rem.

let el = document.getElementById("box-2");
el.onmouseover = function(){
  el.style.border = "2rem solid black";
}
el.onmouseout = function(){
  el.style.border = "0.5rem solid black";
}

Task 7: When the pointer is moved onto the third box, change its border to 0.5rem Gainsboro, and when the pointer is away from the box, change the border to 1rem Gainsboro, and change the background color to SpringGreen.

let el = document.getElementById("box-3");
el.onmouseover = function(){
  el.style.border = "0.5rem Gainsboro solid";
}
el.onmouseout = function(){
  el.style.border = "1rem Gainsboro solid";
  el.style.backgroundColor = "SpringGreen";
}

Task 8: Refer to task 7; keep the background color to tomato when the mouse pointer is moved to onto the box.

let el = document.getElementById("box-3");
el.onmouseover = function(){
  el.style.border = "0.5rem Gainsboro solid";
  el.style.backgroundColor = "tomato";
}
el.onmouseout = function(){
  el.style.border = "1rem Gainsboro solid";
  el.style.backgroundColor = "SpringGreen";
}

Task 9: When the mouse pointer goes onto the submit button, change the button background color to gray. When the mouse pointer goes away from the button, change the button background color to tomato.

let el = document.querySelector('#form input[type="submit"]');
el.onmouseover = function(){
  el.style.backgroundColor = "gray";
}
el.onmouseout = function(){
  el.style.backgroundColor = "tomato";
}

Task 10: When the mouse pointer moves onto the #answers section, change the font size of the h2 to 2rem, and when the mouse pointer moves away, change the font size of the h2 to 1rem.

let el = document.querySelector('#answers h2');
el.onmouseover = function(){
  el.style.fontSize = "2rem";
}
el.onmouseout = function(){
  el.style.fontSize = "1rem";
}

The onchange Event

Task 11: When the user adds his/her name, the input background color changes to gray. Check the following code.

let el = document.querySelector(`#form #yourName`);

el.onchange = function(){
  el.style.backgroundColor = "gray";
}

Task 12: When the user adds his/her age, the input background color changes to LemonChiffon.

let el = document.querySelector(`#form #yourAge`);

el.onchange = function(){
  el.style.backgroundColor = "LemonChiffon";
}

Task 13: When the user selects her/his favorite color, the select background color changes to whatever color s/he selects. Hint: use el.value to get the value of the selection.

let el = document.querySelector(`#form #colorSelect`);

el.onchange = function(){
  let colorValue = el.value;
  el.style.backgroundColor = colorValue;
}

onchange event

The onchange event happens when the value of the field changes.

el.value

The el.value property returns the value of an element.


The Event Object

Task 14: Study the following example.

let el = document.querySelector(`#form #colorSelect`);

el.onchange = function(eventObject){
  eventObject.preventDefault();
  console.log(eventObject)
}

The result is: Event {isTrusted: true, type: "change", target: select#colorSelect, currentTarget: select#colorSelect, eventPhase: 2, …}

The Event Object

When an event occurs, the event object is created. The event objects holds information about the occurred event. It is generally expressed by e.

e.preventDefault()

The e.preventDefault() prevents the default behavior when the event occurs. For example, it prevents the page from reloading on change/click events.

Task 15: Refer to task 14; What is the type of the event occurred? Hint: use eventObject.type.

let el = document.querySelector(`#form #colorSelect`);

el.onchange = function(eventObject){
  eventObject.preventDefault();
  console.log(eventObject.type);
}

The result is: change

Task 16: Refer to task 14; What is the type of the event occurred? Hint: use eventObject.target.

let el = document.querySelector(`#form #colorSelect`);

el.onchange = function(eventObject){
  eventObject.preventDefault();
  console.log(eventObject.target);
}

The result is: <select name="selectMenu" id="colorSelect"></select>


The onclick Event

Task 17: The user clicks on the send button. Once the click event occurs, the background of the form turns to gray. Study the following example.

let button = document.querySelector('#form input[type="submit"]');
let form = document.querySelector('#form');

button.onclick = function(e){
  e.preventDefault();
  form.style.backgroundColor = "gray";  
}

The onclick Event

The onclick event occurs when the user clicks on a given element.

Task 18: The user adds her/his name, and s/he clicks on the send button. Once the click event occurs, the user name is added to #answers #yourName paragraph.

let button = document.querySelector('#form input[type="submit"]');
let userName = document.querySelector('#form > #yourName');
let nameParagraph = document.querySelector('#answers #yourName');

button.onclick = function(e){
  e.preventDefault();
  let name = userName.value;
  nameParagraph.appendChild(document.createTextNode(name));
}

Task 19: Refer to task 18; the user also enters her/his age, and s/he clicks on the send button. Once the click event occurs, the user age is added to #answers #yourAge paragraph.

let button = document.querySelector('#form input[type="submit"]');

let userName = document.querySelector('#form > #yourName');
let nameParagraph = document.querySelector('#answers #yourName');

let userAge = document.querySelector('#form > #age');
let ageParagraph = document.querySelector('#answers #yourAge');

button.onclick = function(e){
  e.preventDefault();
  let name = userName.value;
  nameParagraph.appendChild(document.createTextNode(name));
  let age = userAge.value;
  ageParagraph.appendChild(document.createTextNode(age));
}

Task 20: Refer to task 19; the user also selects a color and s/he clicks on the send button. Once the click event occurs, the user color is added to #answers #yourColor paragraph.

let button = document.querySelector('#form input[type="submit"]');

let userName = document.querySelector('#form > #yourName');
let nameParagraph = document.querySelector('#answers #yourName');

let userAge = document.querySelector('#form > #age');
let ageParagraph = document.querySelector('#answers #yourAge');

let userColor = document.querySelector('#form > #colorSelect');
let colorParagraph = document.querySelector('#answers #yourColor');

button.onclick = function(e){
  e.preventDefault();
  let name = userName.value;
  nameParagraph.appendChild(document.createTextNode(name));
  let age = userAge.value;
  ageParagraph.appendChild(document.createTextNode(age));
  let color = userColor.value;
  colorParagraph.appendChild(document.createTextNode(color));
}

Task 21: Refer to task 20; when the user clicks on the send button more than once. His/her new inputs are added to the old inputs. Clear the old input before appending the new input to the respective paragraph.

let button = document.querySelector('#form input[type="submit"]');

let userName = document.querySelector('#form > #yourName');
let nameParagraph = document.querySelector('#answers #yourName');

let userAge = document.querySelector('#form > #age');
let ageParagraph = document.querySelector('#answers #yourAge');

let userColor = document.querySelector('#form > #colorSelect');
let colorParagraph = document.querySelector('#answers #yourColor');

button.onclick = function(e){
  e.preventDefault();
  let name = userName.value;
  nameParagraph.textContent = "";
  nameParagraph.appendChild(document.createTextNode(name));
  let age = userAge.value;
  ageParagraph.textContent = "";
  ageParagraph.appendChild(document.createTextNode(age));
  let color = userColor.value;
  colorParagraph.textContent = "";
  colorParagraph.appendChild(document.createTextNode(color));
}

Task 22: Refer to task 21; if the user did not provide any input, add "no input for this field".

let button = document.querySelector('#form input[type="submit"]');

let userName = document.querySelector('#form > #yourName');
let nameParagraph = document.querySelector('#answers #yourName');

let userAge = document.querySelector('#form > #age');
let ageParagraph = document.querySelector('#answers #yourAge');

let userColor = document.querySelector('#form > #colorSelect');
let colorParagraph = document.querySelector('#answers #yourColor');

let inputNotProvidedSentence = "No input for this field";

button.onclick = function(e){
  e.preventDefault();
  let name = userName.value || inputNotProvidedSentence;
  nameParagraph.textContent = "";
  nameParagraph.appendChild(document.createTextNode(name));
  let age = userAge.value || inputNotProvidedSentence;
  ageParagraph.textContent = "";
  ageParagraph.appendChild(document.createTextNode(age));
  let color = userColor.value || inputNotProvidedSentence;
  colorParagraph.textContent = "";
  colorParagraph.appendChild(document.createTextNode(color));
}

The Event Object Again

Task 23: Log the event object of the button click event.

let button = document.querySelector('#form input[type="submit"]');

button.onclick = function(e){
  e.preventDefault();
  console.log(e);
}

The result is: MouseEvent {isTrusted: true, screenX: 1372, screenY: 245, clientX: 168, clientY: 165, …}

Task 24: Refer to task 23; what is the event target?

let button = document.querySelector('#form input[type="submit"]');

button.onclick = function(e){
  e.preventDefault();
  console.log(e.target);
}

The result is: <input type="submit" value="Send">

Task 25: Refer to task 23; Is the altKey pressed when the event occurs? Hint: use e.altKey

let button = document.querySelector('#form input[type="submit"]');

button.onclick = function(e){
  e.preventDefault();
  console.log(e.altKey);
}

The result is: false

Task 26: Refer to task 23; What is the path of the clicked element. Hint: use e.path

let button = document.querySelector('#form input[type="submit"]');

button.onclick = function(e){
  e.preventDefault();
  console.log(e.path);
}

The result is: (7) [input, form#form, section#formSection, body, html, document, Window]

Task 27: Refer to task 23; where does the click event occur on the page. Hint: use e.clientX and e.clientY

let button = document.querySelector('#form input[type="submit"]');

button.onclick = function(e){
  e.preventDefault();
  console.log(e.clientX, e.clientY);
}

The result is: 217 568

Task 28: Refer to task 23; where does the click event occur in respect to the button element. Hint: use e.offsetX and e.offsetY

let button = document.querySelector('#form input[type="submit"]');

button.onclick = function(e){
  e.preventDefault();
  console.log(e.offsetX, e.offsetY);
}

The result is: 179 19

Where does the event occur?

The event.clientX property returns the horizontal position of the mouse pointer in respect to the current window.

The event.clientY property returns the vertical position of the mouse pointer in respect to the current window.

The event.offsetX property returns the horizontal position of the mouse pointer in respect to the target element.

The event.offsetY property returns the vertical position of the mouse pointer in respect to the target element.