Categories
JavaScript

JavaScript Events Handlers — LoadStart and Mouse 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 onloadstart , onlostpointercapture and onmouseup event handlers.

**onloadstart**

The onloadstart property is part of an XmlHttpRequest object. It lets us assign an event handler function to it to handle the loadstart event which is fired when the data has just begun loading.

For example, we can assign an event handler to the onloadstart event as we do in the following code:

const loadButtonSuccess = document.querySelector('.load.success');  
const loadButtonError = document.querySelector('.load.error');  
const loadButtonAbort = document.querySelector('.load.abort');  
const log = document.querySelector('.event-log');

function handleLoadStart(e) {  
  console.log(e);  
  log.textContent = log.textContent + `${e.type}: ${e.loaded} bytes transferred\n`;  
}

function addListeners(xhr) {  
  xhr.onloadstart = handleLoadStart;  
}

function get(url) {  
  log.textContent = '';  
  const xhr = new XMLHttpRequest();  
  addListeners(xhr);  
  xhr.open("GET", url);  
  xhr.send();  
  return xhr;  
}  
loadButtonSuccess.addEventListener('click', () => {  
  get('https://jsonplaceholder.typicode.com/todos/1');  
});  

loadButtonError.addEventListener('click', () => {  
  get('https://somewhere.org/i-dont-exist');  
});  

loadButtonAbort.addEventListener('click', () => {  
  get('https://jsonplaceholder.typicode.com/todos/1').abort();
});

In the code above, we have 3 buttons that run the click event handler whenever each button is clicked. The ‘Load (success)’ button will run the get function when it’s clicked. We’ll pass in a valid URL in the call for the get function. The click handling for the ‘Load (success)’ button is done by the following block:

loadButtonSuccess.addEventListener('click', () => {  
    get('https://jsonplaceholder.typicode.com/todos/1');  
});

The JSONPlaceholder has a test API that can serve any URL since it hosts a fake API so we can load it and not get any errors. Likewise, we have buttons for load a URL that’ll give an error, and another button to load a valid URL but then we abort the request. Once the XmlHttpRequest is finished, then the function we assigned to the onloadstart event handler, which is the handleLoadStart function, will be run.

The handleLoadStart function has one parameter, which is an Event object with some data about the request that’s finished. In the function, we get the value of the type property, which has the event type that’s fired, which should be loadstart . Also, we get the value of the loaded property which has the number of bytes of data that’s been loaded. It should always be 0 since nothing has been loaded yet when the loadstart event is triggered.

Then in the HTML code, we add the elements listed in the querySelector calls above:

<div class="controls">  
  <input class="load success" type="button" name="xhr" value="Load Start (success)" />  
  <br>  
  <input class="load error" type="button" name="xhr" value="Load Start (error)" />  
  <br>  
  <input class="load abort" type="button" name="xhr" value="Load Start (abort)" />  
</div>  
<textarea readonly class="event-log"></textarea>

We have 3 buttons to click on to load the successful HTTP request, an HTTP request with a non-existent URL, and an aborted HTTP request respectively. Then we display the event that’s fired and the number of bytes loaded.

onlostpointercapture

The onlostpointercapture property of a DOM element lets us assign an event handler function to handle the lostpointercapture event. The lostpointercapture event is fired when a captured pointer is released. Capturing a pointer means that a particular pointer event is to be re-targeted to a particular element instead of the normal element which will respond to the pointer event. It’s used to ensure that an element continues to receive pointer events even if the pointer device moved off the element.

For example, we can use it to log the lostpointercapture event as we do in the following code:

const para = document.querySelector('p');para.onlostpointercapture = () => {  
  console.log('Pointer been released!')  
};

para.onpointerdown = (event) => {  
  para.setPointerCapture(event.pointerId);  
};

Then in the corresponding HTML code, we put:

<p>Touch and Release</p>

In the code above, when we click on the p element, the pointerdown event is fired first, so the event handler that we assigned to the onpointerdown property of the para object, which is the DOM object of the p element, runs. In the event handler function, we run the the setPointerCapture method on the para object, which targets the mouse pointer events towards the p element.

Then the captured pointer is released when the mouse button is released, so the lostpointercapture method is fired. Then event handler we assigned to the onlostpointercapture event is run, which logs the ‘Pointer been released!’ message that we added.

onmousedown

The event handler function that we assign to the onmousedown property of a DOM element is run when the mousedown event is fired. The mousedown event is fired when the pointing device button is pressed while the pointer is inside the element. This is different from the click event as the click is fired after the full click action occurs. This means that the mouse button is both pressed and then released while the pointer remains inside the same element. mousedown is fired when the mouse button is initially pressed.

For example, we can use the onmousedown event handler to create a peeping effect where when we click on parts of the screen, then the part of the image that’s been clicked on will be revealed.

First we add the HTML code for the image and a black div element to hide the image as we do 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>

Then we add the CSS code for the HTML elements to make the .view div element have a black background:

.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 in the JavaScript code, we add the onmousedown event handler to let us reveal the part of the image that the mouse pointer has clicked on:

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';  
}

const hideView = (event) => {  
  view.setAttribute('hidden', '');  
}

container.onmousedown = showView;  
container.onmousemove = moveView;  
document.onmouseup = hideView;

The onmousedown 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 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.

Then when the mouse button is released, the mouseup is event is fired, and the hideView function, which we assigned to the onmouseup property of the document object is called. We set the hidden attribute of the .view element to hide the .view element.

The onloadstart property is part of an XmlHttpRequest object. It lets us assign an event handler function to it to handle the loadstart event which is fired when the data has just begun loading.

The onlostpointercapture property of a DOM element lets us assign an event handler function to handle the lostpointercapture event. The lostpointercapture event is fired when a captured pointer is released.

The event handler function that we assign to the onmousedown property of a DOM element is run when the mousedown event is fired. The mousedown event is fired when the pointing device button is pressed while the pointer is inside the element. This is different from the click event as the click is fired after the full click action occurs. This means that the mouse button is both pressed and then released while the pointer remains inside the same element. mousedown is fired when the mouse button is initially pressed.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *