DOM Event Practice Page 1

This page has practice exercises to get you familiar with and show off the power of DOM events.

Problem 1. Clicks

Click Me

Show me!

Given the following HTML for the elements above

<h3 class="ClickTarget" id="Clk1">Click Me</h3>
<p id="Click1Result" class="clickResult">mystery1</p>

and the following CSS class definitions

.happy1 {background-color: black;}

Toggle the class happy1 on the paragraph with id "Click1Result" when the h3 with id "Clk1" is clicked.

Problem 2. Double Clicks

Double Click Me

Show me too!

Given the following HTML for the elements above

<h3 class="ClickTarget" id="Clk2">Double Click Me</h3>
<p id="Click2Result" class="clickResult">mystery2</p>

and the following CSS class definitions

.happy2 {background-color: lime;}

Toggle the class happy2 on the paragraph with id "Click2Result" when the h3 with id "Clk2" is double clicked (DOM event name dblclick).

Problem 3. Mouse Down Events

Given the following HTML for the "drawing area" above

<div id="Drawing1" class="drawing"></div>

What does the following JavaScript do and what additional code do you need to make it work?

let draw1 = document.getElementById("Drawing1");

function down(event) {
  let bb = draw1.getBoundingClientRect(); // get bounds/offsets
  let myP = document.createElement("p");
  let x = (event.clientX - bb.x);
  let y = (event.clientY - bb.y);
  myP.innerHTML = `(${x.toFixed(0)}, ${y.toFixed(0)})`;
  myP.style.position = "absolute";
  myP.style.left = x +'px';
  myP.style.top = y +'px';
  myP.style.margin = "0";
  myP.style.padding = "0";
  draw1.appendChild(myP);
}

Problem 4. Mouse Down and Up Events

Given the following HTML for the "drawing area" below our goal is to move the <div> with id "Marker1" on mousedown events and move the <div> with id "Marker2" on mouseup events.

<div id="Drawing2" class="drawing">
    <div id="Marker1" class="marker"></div>
    <div id="Marker2" class="marker"></div>
</div>
                    

The following JavaScript has been given to you to achieve the above goal. What does this code do and what additional code do you need to add to get it to work?

let draw2 = document.getElementById("Drawing2");
let mark1 = document.getElementById("Marker1");
let mark2 = document.getElementById("Marker2");

function updown(event) {
    let bb = draw2.getBoundingClientRect(); // get bounds/offsets
    let mark = mark1;
    if (event.type === "mouseup") {
    mark = mark2;
    }
    mark.style.position = "absolute";
    mark.style.left = (event.clientX - bb.x)+'px';
    mark.style.top = (event.clientY - bb.y)+'px';
    mark.style.margin = "0";
    mark.style.padding = "0";
}

draw2.addEventListener("mousedown", updown);
draw2.addEventListener("mouseup", updown);