Categories
JavaScript

JavaScript Events Handlers — Mouse Over and Mouse Up Events

Spread the love

In JavaScript, events are actions that happen in an app. They’re triggered by various things like inputs being entered, forms being submitted, and changes in an element like resizing, or errors that happen when an app is running, etc. We can assign an event handler to handle these events. Events that happen to DOM elements can be handled by assigning an event handler to properties of the DOM object for the corresponding events. In this article, we’ll look at how to use the onmouseover and onmouseup properties of DOM elements.

onmouseover

The onmouseover property of a DOM element lets us assign an event handler function to it to handle the mouseover event. It’s fired at an element when a pointing device like a mouse or trackpad is used to move the cursor onto the element or one of its child elements.

This means that the mouseenter event is fired whether the mouse moves to another element no matter where it is in the hierarchy. Therefore, the mouseenter event may be fired many times, which can cause significant performance problems. If we need to listen to events in the whole element tree when the mouse is over a big element with lots of descendants, then it’s better to use the mouseover event.

When combined with the mouseout event, which is fired when the mouse leaves an element, the mouseover event acts in a way that’s very similar to the CSS :hover pseudo-class.

For example, we can use it to create a peeping effect on an image where we show a part of an image when the mouse pointer hovers over a part of an image.

First, we add the HTML code for the image and a black box for hiding the image. Also, we add a circle div element to show part of the image that we hover over. To do this, we put in the following code:

<div class='container'>  
  <div class="view" hidden></div>  
  <img src='https://images.unsplash.com/photo-1503066211613-c17ebc9daef0?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1500&q=80'></div>

The .container div is added for showing the black box for covering up the image. The .view div is the circle for us to have the peeping effect to reveal part of the image as we hover over it, and the img element has the image itself.

Next, we add the CSS code to style div elements like we just described by adding the following CSS code:

.container {  
  background: black;  
  width: 500px;  
}

.view {  
  position: absolute;  
  width: 200px;  
  height: 200px;  
  background: white;  
  border-radius: 50%;  
}

img {  
  mix-blend-mode: darken;  
  width: 500px;  
}

Then finally, we add the JavaScript code to do what we just described:

const img = document.querySelector('img');  
const view = document.querySelector('.view');  
const container = document.querySelector('.container');

const showView = (event) => {  
  view.removeAttribute('hidden');  
  view.style.left = event.clientX - 50 + 'px';  
  view.style.top = event.clientY - 50 + 'px';  
  event.preventDefault();  
}

const moveView = (event) => {  
  view.style.left = event.clientX - 50 + 'px';  
  view.style.top = event.clientY - 50 + 'px';  
}

container.onmousemove = moveView;  
container.onmouseover = showView;

In the code above, we get the .container element by using the querySelector method. We do the same with the img and .view elements. Once we did that, we write the event handler functions.

The onmouseover property of the .container div element is set to the showView function, which is runs when the mouse button is down. Inside the function, we remove the hidden attribute from the .view div element to reveal the image underneath the div . From the event parameter, which has the Event object, we get the clientX and clientY properties, which has the mouse coordinates of the click location. We set that to the position of the view DOM object which represents the .view element. Then we called event.preventDefault() to stop the default action since we already did the revealing with the code before it.

The onmousemove event handler of the .container div element is set to the moveView function, which handles the mousemove event. The event is fired when the mouse moves. In the function, we set the .view element to the position of where the mouse pointer is currently located, again with the clientX and clientY properties of the event parameter, which is the MouseEvent object.

Once we did all that, when we hover our mouse over the black box, then we reveal that part of the image underneath.

onmouseup

The onmouseup property of a DOM element lets us assign an event handler function to it to handle the mouseup event. It’s fired when the user releases the mouse button. mouseup events are the counterpoint to the mousedown event.

For example, we can use it along with the mousedown and mousemove event handlers to make a simple whiteboard. First, we create a canvas element in our HTML code:

<canvas width="300" height="300"></canvas>

Then we create our CSS code which adds a border to the canvas element:

canvas {  
  border: 1px solid black;  
}

Finally, we add our JavaScript code to do the drawing on the canvas element:

let isDrawing = false;  
let x = 0;  
let y = 0;
const canvas = document.querySelector('canvas');  
const context = canvas.getContext('2d');  
const rect = canvas.getBoundingClientRect();  
const drawLine = (context, x1, y1, x2, y2) => {  
  context.beginPath();  
  context.strokeStyle = 'red';  
  context.lineWidth = 1;  
  context.moveTo(x1, y1);  
  context.lineTo(x2, y2);  
  context.stroke();  
  context.closePath();  
}

canvas.onmousedown = e => {  
  x = e.clientX - rect.left;  
  y = e.clientY - rect.top;  
  isDrawing = true;  
};

canvas.onmousemove = e => {  
  if (isDrawing === true) {  
    drawLine(context, x, y, e.clientX - rect.left, e.clientY - rect.top);  
    x = e.clientX - rect.left;  
    y = e.clientY - rect.top;  
  }  
};

document.onmouseup = e => {  
  if (isDrawing === true) {  
    drawLine(context, x, y, e.clientX - rect.left, e.clientY - rect.top);  
    x = 0;  
    y = 0;  
    isDrawing = false;  
  }  
};

The code above works by getting the canvas element and the get the context object from it which allows us to draw on the canvas.

We defined the drawLine function, which takes the canvas context, the x and y coordinates of the originating coordinate of the line, which are x1 and y1 , and the x and y coordinates of the end of the line, which is x2 and y2 .

In the function, we call beginPath on the canvas context object. Then we set the strokeStyle to red , which makes the line red. Then we set the lineWidth to 1 pixel. Next we call the moveTo with x1 and y1 to start drawing in those coordinates, then we call the lineTo method with the arguments x2 and y2 to define the line segment from (x1, y1) to (x2, y2). Then we call the stroke method on the context object to actually do the drawing. Finally, we call the closePath method to draw the line back to the starting point (x1 , y1 ).

Then we attach our event handlers. We assign the onmousedown event handler function to set the x and y coordinates and set isDrawing to true to indicate that we’re going to start drawing.

Next, we set the onmousemove property of the canvas element by assigning it an event handler function that runs code when isDrawing is true . If it’s true , then we call the drawLine method that we defined above, with (x, y) as the start of the line segment and (e.clientX — rect.left, e.clientY — rect.top ) as the end point of the line line segment. e.clientX is the x coordinate of the mouse pointer’s location, and clientY is the y coordinate of the mouse pointer’s location. rect is returned from the getBoundingClientRect method of the context, which returns the size of an element and its position relative to the viewport. We subtract rect dimensions so that the endpoint of the line segment we drew and the starting point will be the same as the mouse pointer’s location after the line is drawn.

Finally, the we set an event handler function for the onmouseup event to draw the remaining line if isDrawing is true , and then set isDrawing to false to stop drawing since we released the mouse button.

The onmouseover property of a DOM element lets us assign an event handler function to it to handle the mouseover event. It’s fired at an element when a pointing device like a mouse or trackpad is used to move the cursor onto the element or one of its child elements.

The onmouseup property of a DOM element lets us assign an event handler function to it to handle the mouseup event. It’s fired when the user releases the mouse button. mouseup events are the counterpoint to the mousedown event.

We can use it with other mouse event handlers to create useful things that like a whiteboard or changing content when hovering a mouse over something.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.