Tips for defining boundaries for position absolute elements using JavaScript

Fiddle. I am in the process of developing a chat/mail application with a resizable menu similar to the Google Hangouts desktop app. When resizing the brown content pane at a normal speed, you can observe that the boundaries are functioning as intended. My approach involves using style.left and a function that monitors cursor direction to ensure the cursor stays aligned with the drag bar.

Issue: If you hold down the mouse on the drag bar and quickly resize it out of bounds multiple times with a "fling" motion, you'll notice the behavior deviates from what was expected.

edit: The bug is less prominent when using Edge and Firefox browsers. It does not occur on the right side, but occasionally occurs on the left, never going off-screen completely.

Below is the view controller code extracted from the provided fiddle.

//handles all mousemove and boundary cases.
mouseMove(e) {
    //size of right pane relative to container (percent)
    let percentRight = Math.round(this.messageWindowContentContainer.clientWidth/this.chatContainer.clientWidth * 100);
    //normal mousemove within the bounds min:25 and max:94
    if ((percentRight) <= 94 && percentRight >= 25) {
    document.getElementById("content2").innerHTML = "Content";
    this.messageWindowContainer.setAttribute("style", "left:" + (e.clientX) + "px");

}
//Only moves if right pane is out of bounds(left), mouse if moving right, and mouse is right of pane
if (percentRight > 94 && this.getCursorXPercentage(e) >= 6 && this.cursorMovingRight(e)) {
    this.messageWindowContainer.setAttribute("style", "left:" + (e.clientX) + "px");
}
//Only moves if right pane is out of bounds (right), mouse is moving left, and mouse is left of pane
if (percentRight < 25 && this.getCursorXPercentage(e) <= 75 && this.cursorMovingLeft(e)) {
    this.messageWindowContainer.setAttribute("style", "left:" + (e.clientX) + "px");
}
}

//if e.movementX is positive, moving right
cursorMovingRight(e) {
    return (Math.sign(e.movementX) === 1)
}
//if e.movementX is negative, moving left
cursorMovingLeft(e) {
    return (Math.sign(e.movementX) === -1)
}

//returns cursor location relative to container as percent
getCursorXPercentage(e) {
    let percentage = Math.round((e.clientX / this.chatContainer.getBoundingClientRect().width) * 100)
    console.log(percentage)
    document.getElementById("content2").innerHTML = percentage;
    return percentage;
}

Answer №1

After testing the code on my computer, I discovered that the issue lies in checking the current value of percentRight instead of considering its future value. This means that even if the present value appears to be correct, it may not necessarily hold true for the future value. When your DIV is in full screen mode, as shown in the example, the new value of percentLeft will be e.clientX / widthOfTheBox. Before assigning this new value, you should perform the following calculation:

this.messageWindowContainer.style.left = Math.min(Math.max(newPercentLeft,5),75) * widthOfTheBox + 'px'

You can simplify your code by using `this.messageWindowContainer.style.left = yourvalue` instead of setAttribute.

Edit: https://jsfiddle.net/8kcc8822/16/


mouseMove(e) {
    var $0 = document.querySelector.bind(document),
        boxWidth =  $0('#mainMenuContainer').clientWidth,
        newPercentLeft = e.clientX / boxWidth,
        limitedNewPercentLeft = Math.min(Math.max(.2,newPercentLeft),.85);
    
    $0("#content2").innerHTML = limitedNewPercentLeft != newPercentLeft ? (newPercentLeft * 100 |0) : 'content';
    this.messageWindowContainer.style.left = limitedNewPercentLeft * boxWidth + 'px';

    console.log(newPercentLeft);
}

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

Ways to position Drop-down menu flush against the left edge of the webpage?

I am facing a challenge in customizing my CSS3 Mega drop-down menu. I want the mega menu to start from the left side of the main page, beginning from the home button area and extending all the way to the end. Currently, it is appearing where the parent men ...

Having trouble creating an alias system in discord.js and encountering errors

While developing an alias system for my Discord bot, I encountered a situation where I wanted to display the message: "if the user entered the wrong command name or alias then return: invalid command/alias". However, when implementing this logic, ...

Callbacks in Laika tests go untriggered

Meteor.collection.insert() allows for the use of a callback as one of its arguments. To demonstrate, you can start a new Meteor project and execute the following code in the browser's console. my_collection = new Meteor.Collection("myCollection"); my ...

Progressively increasing the time by 15 seconds during each iteration of the CSS @each loop

I recently made changes to a CSS script that involves the repetition of an animation task. Rather than repeating a segment of code 30 times, I decided to streamline it using a loop. Now, there are 30 <div></div> segments and each one undergoes ...

Supporting server-side routing with NodeJS and Express for AngularJS applications

My current setup includes NodeJS + expressJS on the server and AngularJS on the client side. The routes defined in my AngularJS controller are as follows: app.config(function($routeProvider,$locationProvider) { $routeProvider .when('/field1/:id&apo ...

Dynamic change in the mutation observer is not causing the callback to trigger

I have created a nested structure with two <div> elements. I am monitoring changes in the width of the inner <div>, which is set to width:auto;. Despite adjusting the width of the parent <div>, the mutation observer callback doesn't ...

Obtaining Values from Identical jQuery Buttons with the Same Class名称

I am facing an issue with my PHP script that generates buttons for each content schedule. The script outputs multiple HTML buttons with the same name, class, and ID, but their values are dynamically set based on a variable. In my jQuery code, I have selec ...

Setting background colors for classes based on an array

I have a total of six div elements on a single page, all sharing the same class. My goal is to give each one a unique color from an array I have prepared. I want to avoid any repetition of colors among these divs. Currently, I have managed to assign backg ...

What are the different methods to display information in Angular?

list.component.ts import { Component, OnInit } from '@angular/core'; import { StudentAPIService } from 'src/app/services/student-api.service'; import { StudentModel } from 'src/app/model/student'; @Component({ selector: &ap ...

Error: The configuration property is not defined, causing a TypeError at Class.run ~/node_modules/angular-cli/tasks/serve.js on line 22

I'm encountering a persistent error on my production server that indicates a missing angular.json file, even though the file is present in the root of my project! Every time I run npm start, npm build, or npm test, I receive the same error message. ...

Entering text into a field / Inserting data into a MySQL database / Presenting

I am facing a challenge that I'm uncertain how to resolve. The issue lies with a textarea on my form that permits the user to input data in the following format: Windows XP Home and Professional<br />(32 and 64 bit) Windows 7 Home and Professi ...

Analyzing all the <option> elements within a <select> tag with jQuery

I have a WordPress plugin in development and I am currently facing an issue with comparing user-input from an <input> element to a set of <option> elements within a <select> element. Here is my current approach: $('button#test_bu ...

The DataGrids effortlessly expanded to accommodate their parents without the need for a horizontal scrollbar, showcasing their full capacity

After conducting numerous tests on simpler models, I have come to realize that the display of DataGrids Pro has been altered in MUI v6, rather than being a result of something I had broken initially. My workplace utilizes multiple DataGrids with columns h ...

Ways to navigate a div within an iframe that has been loaded

As I load a page(A) inside an iframe, the HTML structure of the embedded content is as follows: <html><body> <div id="div1"></div> <div id="div2"><button>Hello</button></div> </body></html> The ...

Problem with displaying images and videos in a lightbox gallery

Currently, I am encountering an issue with the lightbox feature on my website. When trying to play a video, there seems to be a layer (div tag) blocking it, preventing me from playing or stopping the video. This problem occurs when clicking on an image fir ...

JavaScript code to copy a specified column through the last column, and then paste it down to the last row

I have limited experience with JavaScript and I've been putting together the code I need by searching online resources and watching videos. My goal is to set multiple columns in row 4, starting from column 18 to the last column, as the active cells fo ...

What is the process for transforming the search bar into an icon located at the top of a WordPress site?

For the past few weeks, I've been attempting to convert the search bar on my website (which is currently a plugin) into an icon positioned near the header. I've experimented with modifying the child theme's functions.php, the parent theme&a ...

Out of the box, Next.js is equipped with a standard error message stating: "TypeError: Cannot read properties of null (reading 'useContext')"

After just setting up next.js for my upcoming website, I ran into some unexpected errors while trying to host it with "next". The specific error message I encountered was: TypeError: Cannot read properties of null (reading 'useContext') This iss ...

Access User Information from Facebook using Nativescript {N} oAuth Plugin

Developing an Android App with NativeScript I am in the process of creating an Android app using JavaScript and NativeScript. The initial page asks users to connect with Facebook, and my goal is to verify if an account exists with their email address. To ...

Are you looking for straightforward dynamic directives that come with dynamic controllers and a scope?

Feeling like I have a simple problem to solve here. Working within the confines of a TypeScript + Angular application. Within a controller, I've got an array of similar directives that I want to utilize. These are essentially the panels strewn throug ...