Strategies for avoiding text selection interference with onMouseMove event

I am in the process of adding a "resize handle" to adjust the width of my left navigation panel. This handle, represented by a div, triggers an onMouseDown() event that calculates the necessary widths and applies them to the relevant elements during subsequent calls to onMouseMove(). However, I am experiencing some issues.

1) The article element, located to the right of the navigation panel and handle, fails to trigger the onMouseUp() event when I release the mouse there. Could this be due to the initial activation of onMouseDown() in another element?

2) If I move the mouse rapidly to the right, I am unable to prevent text within the article from being selected, despite attempts to use methods like preventDefault() and stopPropagation().

3) Even if there is no text present in the article, the resizing functionality only works effectively when the mouse is moved very slowly. Moving the mouse swiftly over the article results in the resizing stopping abruptly unless the mouse button is released – in such cases, the resizing proceeds smoothly (implying that text selection was hindering the process even when no text was present). However, upon releasing the mouse button, the resizing should ideally cease (refer to point 1).

I have come across suggestions involving CSS properties like user-select: none, but implementing these would indiscriminately prevent text selection within the article, which seems excessive.

Hence, how can I achieve seamless resizing without inadvertent text selection while moving the mouse across any element within my document? (Following the initial click within the right div, of course.)

The following snippets showcase my HTML, CSS, and JavaScript code for reference:

To view the complete code and a functional example, please visit:
<a href="https://jsfiddle.net/45h7vq7u/" rel="nofollow noreferrer">Resize Handle Example</a>
<a href="https://jsfiddle.net/v1cmk2f6/1/" rel="nofollow noreferrer">Additional Implementation Example</a>

Answer №1

Observe the start moving and finish moving events using your preferred method (such as onMouseDown and onMouseUp). Apply a CSS class to indicate the moving state when the action begins, and remove it when the action concludes.

If you're facing this scenario, you can experiment with the following:

Create a new CSS class:

.moving {
    user-select: none;
    -moz-user-select: none;
    -webkit-user-select: none;
    -ms-user-select: none;
}

Update your handMd() and handMu() functions:

function handMd(e) {
    mx = e.pageX;
    px = document.getElementById('nav').clientWidth;
    moving = true;
    document.getElementById('article').classList.toggle('moving', true);  // Include this line. 'article' refers to the element ID where text selection is not desired.
}
function handMu(e) {
    moving = false;
    document.getElementById('article').classList.toggle('moving', false);  // Include this line. 'article' refers to the element ID where text selection is not desired.
}

Answer №2

Upon examining a solution found elsewhere, I have made some alterations.

In the HTML, only one event handler is now necessary:

...
<main>
    <nav id='nav'>
        <div class='navcont'>
            <p>nav 1</p>
            <p>nav 2</p>
        </div>
        <div class='handle' onmousedown='handMd(event)'>
        </div>
    </nav>
    <article id='article'>
    </article>
</main>
...

In the Javascript code, it is now more efficient to attach and detach the onmousemove event handler instead of calling onmousemove every time the mouse moves (to then check if the mouse button has been pressed). Additionally, the event is now attached to the document rather than each div on the screen:

var mx,px,minW = 200;
function handMd(e) {
    mx = e.pageX;
    px = document.getElementById('nav').clientWidth;
    document.addEventListener('mousemove',handMm);
    document.addEventListener('mouseup',handMu);
    document.getElementById('article').classList.toggle('moving',true);
    document.getElementById('nav').classList.toggle('moving',true);
}
function handMm(e) {
    var diff = e.pageX - mx;
    if (px+diff >= minW && window.innerWidth-px-diff >= minW) {
        document.getElementById('nav').style.width = (px+diff)+'px';
        document.getElementById('article').style.width = (window.innerWidth-px-diff)+'px';
    }
}
function handMu(e) {
    document.removeEventListener('mousemove',handMm);
    document.removeEventListener('mouseup',handMu);
    document.getElementById('article').classList.toggle('moving',false);
    document.getElementById('nav').classList.toggle('moving',false);
}

In the CSS section, following Ryan Tsui's advice, I removed unwanted text selection while resizing:

.moving {
    user-select:none;
    -moz-user-select:none;
    -webkit-user-select:none;
    -ms-user-select:none;
}

Answer №3

Stopping the selection process may be a bit tricky, but one way to handle it is by using the event called onselect which is triggered when something is selected.

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

How can I retrieve all the data for the chosen item in a mat-select within a mat-dialog, while still preserving the code for setting the default selected value

In my modal dialog, I have a dropdown menu populated with various languages. The ID of the selected language is bound to the (value) property for preselection purposes when data is passed into the dialog. However, I am looking for a way to also display the ...

Create a PHP form that includes a dropdown menu for selecting the quantity, allowing users to insert multiple rows of data inputted into the form

My first time posting something here. The issue I'm facing is: I have an HTML form with various variables. A dropdown for Quantity that should insert the data into a MySQL table multiple times based on the chosen quantity. For example, if the dropd ...

unable to retrieve the value of the table row with a particular class designation

I'm currently working with a table code and I need to retrieve the value of the table row with the class "highlight". However, when trying to do so with the code below, I'm getting a null result. Can someone please assist me? Table name: itemtab ...

Exploring the world of unit testing in a store - any tips on getting it to work

I am currently working on a store.js file import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) export const mutations = { increment: state => state.count++, Changeloading(state, status) { state.loading = status }, Cha ...

When applying the `display:block` and `width:100%` attributes to an HTML table cell, it may

My issue lies in the usage of DISPLAY:BLOCK for the td cells with a class of column. Despite applying it appropriately, the logo and CALL US td cells do not stack vertically when resized to mobile size. While they are supposed to take up 100% width, they ...

Preventing Form Submission from Redirecting to the Top in an HTML Document with PHP

Recently, I integrated a php form into my html code and changed the file from index.html to index.php. The contact form is functioning perfectly and sending all information as expected. However, after submitting the form, users are receiving the message "T ...

Using Javascript to automatically replace content when the page is loaded

Having trouble with my fullCalendar jquery calendar and the 'eventClick' method. When I click on an event, the URL is getting encoded incorrectly. For example, I'm trying to pass a Wordpress URL like this: http://sitedomain.com/?post_type= ...

Using the _id String in a GraphQL query to retrieve information based on the Object ID stored in a

Encountering an issue with my graphql query not returning anything when sending the _id as a string. Interestingly, querying the DB using any other stored key (like name: "Account 1") works perfectly and returns the object. I've defined my Account sch ...

Developing a pop-up feature that triggers upon clicking for a miniature rich text editing

Looking to integrate the Tiny rich text editor into my code. Check out the TextEditor.js component below: import React from 'react'; import { Editor } from '@tinymce/tinymce-react'; class App extends React.Component { handleEditorCha ...

The 'export '__platform_browser_private__' could not be located within the '@angular/platform-browser' module

I have encountered an issue while developing an angular application. Upon running ng serve, I am receiving the following error in ERROR in ./node_modules/@angular/http/src/backends/xhr_backend.js 204:40-68: "export 'platform_browser_private' w ...

Comparing Objects in an Array to Eliminate Duplicates and Make Updates in Javascript

I am working with an array of objects that is structured like this: 0: Object ConsolidatedItem_catalogId: "080808" ConsolidatedItem_catalogItem: "undefined" ConsolidatedItem_cost: "0" ConsolidatedItem_description: "Test Catalog Item" ConsolidatedItem_ima ...

The CSS selector within the website's URL

When a URL like www.example.com/#signup is entered, the browser focuses its view on the HTML element with the ID signup. Is this correct? Can the CSS style of the element be changed if it is focused in this way? For example, if there is a div element wit ...

How can I design unique navigation menus using HTML, CSS, JavaScript, and jQuery?

Is there a way to create menus where clicking on a holiday/seasonal category opens up all related lists automatically? For example: https://i.sstatic.net/Nctd1.png I've been searching online for submenu options but haven't found the right metho ...

Incorporating a setup file into my JavaScript project

In my JavaScript project, I have both frontend and backend codes (NodeJS). Here is the folder structure for my production environment: /prod /server sourceCode1.js sourceCode2.js ... sourceCodeN.js index.js ...

Enhancing Bootstrap Carousel with various effects

My exploration of the web revealed two distinct effects that can be applied to Bootstrap Carousel: Slide and Fade. I'm curious if there are any other unique effects, such as splitting the picture into small 3D boxes that rotate to change the image? ...

What is the best way to display an icon and text side by side in the header of a Phonegap app

____________________________________________________________ | logo_image page_Title | ------------------------------------------------------------ I am looking to create a header for my PhoneGap app similar to the one sh ...

Restricting the frequency at which a specific key value is allowed to appear in JSON documents

Within my JSON file, there is an array structured like this: { "commands": [ { "user": "Rusty", "user_id": "83738373", "command_name": "TestCommand", "command_reply": "TestReply" } ] } I have a requirement to restrict the num ...

When an iteration occurs within a for loop and a value changes, remember to incorporate a line break or equivalent element using jQuery

I am currently working on implementing a hierarchy system for users stored in a database table. At the moment, only top-level users with a hierarchy of 1 are displayed. When clicked, I use AJAX to retrieve and display all related users below them. These ...

Including an embedded iframe in an asp.net web form

I need to integrate an iframe into a web form by retrieving the URL from an API call to a third-party payment service. I am working with ASP.NET 4.5 and C# 6.0. The code for my web form includes implementing an iframe similar to that in an ASP.NET MVC cod ...

Methods for anchoring an element at the bottom of a square container div

* { box-sizing: border-box; } .publication { display: flex; width: 100%; margin-top: 6%; } .bottom1, .bottom2 { display: flex; flex-direction: column; ...