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

Why won't console.log function execute in this particular situation?

(function( $ ){ $.fn.openlayers = function( mapElementId, options ) { alert(console.log); console.log(options); ... } }); While attempting to enhance the capabilities of a JavaScript library, I encountered an unexpected issue. ...

Repurposing JavaScript objects after clearing their contents

Here's my issue. I'm working with a Javascript object, initialized as var stack = {}. This object is used in my project to store arrays. When the user clicks the add button, an array is added to the object with a specific key that is inputted in ...

Can anyone recommend the best method for pinpointing the exact building the user is currently in - utilizing HTML5 geolocation or creating a customized map?

In the process of developing a web application using Google App Engine and Python, I have come across information suggesting that HTML5 geolocation provides more accurate results compared to IP geolocation. However, I am curious if this level of precisio ...

Ways to extract particular items from a JSON array and store them in a JavaScript array

I am dealing with an external JSON-file structured as follows: { "type":"FeatureCollection", "totalFeatures":1, "features": [{ "type":"Feature", "id":"asdf", "geometry":null, "properties": { "PARAM1":"19 16 11", ...

Issue with using Sinon FakeServer with Mocha

I'm currently in the process of setting up a test for an API call. In my attempt to create a fake server within the before method, I have encountered issues with testing the basic implementation using $.ajax compared to my actual api call. Strangely, ...

Content displayed above a slideshow of images in a stunning gallery on Squarespace platform

Currently working on a one-page landing page using Squarespace and running into some issues with creating a slideshow. You can check out my website here (the slideshow is located at the bottom of the page): Squarespace provides default options for text p ...

Issue: Module "expose?Zone!zone.js" could not be located

Just started experimenting with Angular 2 and encountering an issue when importing zone.js as a global variable: https://i.stack.imgur.com/gUFGn.png List of my packages along with their versions: "dependencies": { "angular2": "2.0.0-beta.3", "es ...

Is there a way to drop a pin on the Google Maps app?

Is there a way to pinpoint the specific location on Google Maps? <google-map id="map-container" width="100%" height="100%" class="maps"></google-map> ...

My AJAX function is not functioning as intended

I'm currently developing a time management system for my workplace. As I was coding, I implemented a feature that allows users to configure the database details similar to the setup process in WordPress. Once the data is saved successfully, I aim to d ...

How are the plugins configured for `postcss-import` implemented?

Recently, I've transitioned to using PostCSS exclusively with Webpack. As I explore the functionalities of using postcss-import to inline external stylesheets, I'm noticing that its options offer the ability to configure plugins and transformers ...

Storing data with jQuery

Looking to store objects in jQuery for events. Each event will have a date, title, and some text that needs to be stored in an array. Wondering if using a multi-dimensional array would be the best way to go so I can easily iterate through them with a count ...

There seems to be a problem with the responsive navigation menu when activated in responsive mode and then resizing the screen

Trying to create a responsive navigation but encountering issues when following these steps: 1. Resize the navigation to less than 940px 2. Activate the menu 3. Resize the browser again to more than 940px 4. The menu is no longer inline and appears messy ...

Automatically update and reload Express.js routes without the need to manually restart the server

I experimented with using express-livereload, but I found that it only reloaded view files. Do you think I should explore other tools, or is there a way to configure express-livereload to monitor my index.js file which hosts the server? I've come ac ...

having trouble with my lambda function reading the basic json object

I recently joined Lambda and have been attempting to create a simple JSON object. However, I keep encountering an error that says "parsing error, unexpected token." Here is my code, which I have verified to be valid JSON: { "metadata": { ...

Having trouble with Angular ngRoute functionality?

I'm currently working on configuring a basic Angular app. Here is my main HTML: <html ng-app="CostumerApp"> <head> <title> Customers </title> <link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstr ...

Is there a way to link code and unit testing directly to npm test?

Is there a method to conduct unit testing in real-time on my server without having to create temporary files? I am looking for a way to supply both the code to be tested and the corresponding unit test to npm test. The information provided in the npm test ...

Transfer the data from a post request through routes following the MVC pattern

Encountering an issue when attempting to submit a post form with username and password, as an error stating Cannot POST /validateUser is displayed. The structure of my form is as follows: <!DOCTYPE html> <html> <head> <title> ...

Guide to customizing action button color on MatSnackbar?

Currently, I am encountering an issue with the snackbar in my Angular 9 project. Despite adding CSS styles to both the component.scss file and the global style.scss file, the action button on the snackbar displays the same background and text color. In an ...

Interaction issue with Material UI and React tabs: hovering fails to open and close tabs correctly

I am currently immersed in a project that involves React and Material UI. My goal is to create tabs that trigger a menu upon hovering, but I seem to be facing some challenges with this functionality. That's why I'm reaching out here for assistanc ...

Javascript datatables do not allow for setting a default column sort

I am encountering an issue where I need to sort the results by a specific column on page load. In this case, I want the initial results to be displayed in descending order based on "RecordDate". However, it seems that the server side is blocking any sort ...