When the default action is prevented for a document in JavaScript, utilize the default event within a single element

I currently have an onMousedown and an onMouseup event handler set on the document that prevents the default action.

However, I have a single form element (a select field) where I want to allow the default action to occur. Is there a way to trigger it from JavaScript?

Perhaps something like this:

  <select ... onClick="this.browserDefaultAction">

Of course, "BrowserDefaultAction" is fictional - just to illustrate my point.

EDIT:

To clarify further -

I have a table displaying days (columns) and times (rows in units of 5 minutes). When a user hovers over the table, each cell should display the time it represents.

If the user presses the left mouse button, the times are "set" (cell turns blue), if the right mouse button is pressed, the times are "unset" (cell turns green). This should happen dynamically, without clicking on each cell individually.

Due to issues with detecting the mouse buttons directly within the event script, I added the following code to store the mouse button status in a custom variable:

var MouseButton = 0;
function MousePress(Event) {

   if (!Event)
     Event = window.event;

   if (Event.buttons) {
	   if (Event.buttons == 2) {MouseButton=2}
	   if (Event.buttons == 1) {MouseButton=1}
   }
}

function MouseRelease() {
    MouseButton = 0;
}

document.onmousedown = MousePress;
document.onmouseup = MouseRelease;

This was functioning well even without preventing the default action.

However, moving the mouse while a button was pressed still resulted in cells being marked. While this did not affect functionality, it was visually unappealing and distracting for users. To address this, I simply added a call to Event.preventDefault at the end of the function.

But the issue remained with the select field on the same page. I attempted attaching the onmouseup/down event handlers to the table or a div containing the table instead of the document, but it was unsuccessful.

If anyone wishes to view the page or the full code, here is the link.

EDIT:

I implemented the following approach

test what element triggered the event and then use preventDefault() or not as appropriate

...
     if (!Event)
        Event = window.event;

     if (Event.target.tagName != "SELECT") {
         if (Event.buttons)

It is now working as intended.

Answer №1

Events in the DOM can propagate both upward (bubbling) and downward (capturing) from their source. When it comes to events like mousedown and mouseup, they are likely triggered by elements deeper within the DOM structure rather than the document itself. To prevent event propagation after allowing the default browser action, you can simply stop the event from bubbling further.

window.addEventListener("DOMContentLoaded", function(){

    document.addEventListener("mousedown", function(evt){
        // This code will not execute when mousing down on the list, only on the document
        alert("Something in the document or the document itself was clicked with the mouse.");
    });
  
    // ****************************************************************************************************  
  
    var list = document.getElementById("lst");
  
    list.addEventListener("mousedown", function(evt){
          alert("My default behavior for mousedown is working!");
      
          // Prevent the mousedown event from propagating to the document
          evt.stopPropagation();
    });
  
  
   
  
});
<select id="lst">
  <option>Choice 1</option>
  <option>Choice 2</option>
  <option>Choice 3</option>
  <option>Choice 4</option>
</select>


<select id="lst2">
  <option>Choice 1</option>
  <option>Choice 2</option>
  <option>Choice 3</option>
  <option>Choice 4</option>
</select>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it necessary to link event handlers to `this` when using TypeScript and React?

One issue I encountered was with a component's button handler method. If the onClick handler is not bound to this in the constructor or inline on the onClick itself, an error occurs because the context of the handleAdd method is not tied to the instan ...

When using mapStateToProps in React Redux, it may encounter difficulties in reading nested values

I feel like I must be overlooking something very obvious, possibly related to Immutable.js/React/Redux. Here is a method I have... function mapStateToProps(state){ console.log(JSON.stringify(state.test)); //prints all nested properties and object ...

How to retrieve an array using a for loop in Jquery

Hey there! I'm working on a project where I need to loop through two arrays - one for button IDs and the other for text. However, I've run into an issue where it's unable to iterate through the text array. Whenever I try to use window.alert ...

What is the proper way to incorporate scripts into my AngularJS controller?

I am encountering an issue that may be stemming from my incomplete understanding of AngularJS. My goal is to incorporate some JS scripts into my HTML. <head> <script src="https://code.highcharts.com/highcharts.js"></script> <script sr ...

How to incorporate an editable field into a mat-row within a mat-table using Angular 9

I am currently working on enhancing an Angular screen that allows users to manage data in a table with just one column. While the code I have implemented below successfully displays the data, I have been unable to find any examples of how to make this sing ...

Executing several AJAX functions using an onclick event

It seems like I have a simple issue at hand, but for some reason, I can't figure out the solution on Facebook. I have two AJAX functions that connect to PHP scripts through the onClick event. Here is how my HTML code is structured: onClick = "previou ...

Using Vue3 and Vuex4: How to efficiently render only a subset of items from an array with v-for

Hello, I'm a first-time user and beginner developer seeking some assistance. I am in the process of creating a basic web application that retrieves an HTTP JSON response from an API and displays a more visually appealing list of results. However, I&ap ...

HTML Alignment of Body and Div Elements

Setting the body and div to have the same height and width in my CSS: body { background-repeat: no-repeat; background-color: maroon; width: 1280px; height: 670px; margin: 0; } div { background-color: yellow; width: 1280px; height: 670px; } And here i ...

Creating a time-limited personal link with Django Rest Framework and React

I have a frontend application built with React Framework that I want to provide access to via a time-limited personal link, without the need for additional authentication functions. With approximately 1-2 new users per day, my proposed implementation is as ...

Steps to send an asynchronous AJAX request to the server-side within the JQuery validation plugin using the addMethod() function

Currently, I am in the process of developing my own framework using the JQuery validation plugin to validate CRUD forms both client-side and server-side. It is crucial that these forms are not static but rather created dynamically using "handlebar.js". Fo ...

Transform Text into Numeric Value/Date or Null if Text is Invalid

Consider the TypeScript interface below: export interface Model { numberValue: number; dateValue: Date; } I have initialized instances of this interface by setting the properties to empty strings: let model1: Model = { numberValue: +'', ...

Why does only the last item in JavaScript loops seem to be impacted?

Currently, I am using the gm npm module for image manipulation and have written this code: for(i=0;i < 4;i++){ gm("www/img/" + image[i]).crop(550, 406, 0, 0).write(function(err) { console.log(this.outname + " created :: " + arguments[3]) ...

The Instagram API is functioning without issues on localhost, but encountering errors when accessed on the server at the following URL: https://www.instagram.com/${name}/?__

I am having trouble retrieving profile information for a user. It works fine on my local host, but not on the server. I realized that I am not logged into my Instagram account on my local machine. It seems like the issue arises on the server when it trie ...

Looking to personalize your jVectorMap region popups? Here's how!

Currently, I am working with the jVectorMap library. While hovering over each country, the default label displays the country name. However, I would like to customize the map so that it shows regions based on database values. How can I achieve this custo ...

Error: OBJLoader is not defined in Three.js

I've been trying to learn Three.js by following various tutorials, but I keep encountering an error message that says Uncaught ReferenceError: OBJLoader is not defined when I attempt to use my own .obj file. I've tried different approaches to fix ...

An error is thrown in Three.js stating that the array index 'i' is undefined at line 180, using TransformControls

While working with loaded .STL Files in Three.js using TransformControls, I'm experiencing an issue. Whenever I mouse hover or use the transformControls, my console logs "TypeError: array[i] is undefined three.js:180:9". Is anyone familiar with this e ...

Redefining a path in JavaScript after the page has already loaded

I am currently facing an issue with my website, which is built in HTML. In the head tag, I have included a JavaScript file. The website consists of two pages, and the problem arises when the path defined in the JavaScript file works correctly on the first ...

Attempting to retrieve an element by its ID from a div that was dynamically loaded using AJAX

I am having trouble retrieving the value of an element with getElementById from a div that is loaded via ajax. Let me explain: In 'example.php' I have the following JavaScript code: <script type= "text/javascript"> var page=document.getE ...

Oops! An unexpected error occurred while parsing the JSON response

While working with my Json file, I encountered an error that has been validated on https://jsonlint.com/ @Injectable() export class LightParserService{ ITEMS_URL = "./lights.json"; constructor(private http: Http) { } getItems(): Promise<Light[ ...

Utilizing VueJs (Quasar) to access vuex store within the router

Recently, I have been diving into learning Vuex and creating an authentication module. Following a tutorial, I reached a point where I needed to use the store in the router. However, after importing my store at the top of the router index.js file, I notice ...