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

Tips for displaying HTML elements using JSON data in React?

My goal is to dynamically render HTML elements based on JSON data using a React class that takes objects and generates a list of divs. The values inside the divs correspond to the first value in each object within the JSON. Here's an example of the J ...

Modify the font style of numbers based on the keyboard language selected by the user

Is it possible to change the font family of numbers in input fields based on the user's keyboard language? For example, if the user is typing in Persian, the numbers should be displayed in a Persian font, and when they switch to an English keyboard, t ...

Creating a static footer in AngularJS with material design: A step-by-step guide

This is how I've set up my webpage design. <div layout="column" layout-fill ng-controller="MainCtrl as mc"> <header> <md-toolbar md-scroll-shrink> <div layout="row" layout-align="center center" flex> ...

Reveal and conceal using CSS animations

I am working on adding animation effects to show and hide HTML elements triggered by a button click. The button toggles a "hide" class to display or hide the element. Check out my code snippet: const toggleButton = document.querySelector('button ...

Clicking on a table will toggle the checkboxes

I am facing an issue with this function that needs to work only after the page has finished loading. The problem arises due to a missing semicolon on the true line. Another requirement is that when the checkbox toggle-all is clicked as "checked", I want ...

Issue arises when applying both overflow-x:scroll and justify-content:center

Encountering a problem with using overflow-x: scroll and justify-content: center on a flex parent container. Here is my code snippet: The issue: the first flex child item is not visible as it is cropped on the left side. Please refer to the screenshot and ...

Transferring Data to Model

I am attempting to send a variable to the 'GetFiles' function in a model within web2py using this code snippet where the output is saved as 'a': <script> VARIABLE = 'teststring' a = {{=XML(response.json(GetFiles(VARIABL ...

A status code of 200 indicates a successful login, which then leads to a 401 status code upon making a

Just recently, I successfully deployed a rails backend and a vue frontend to Heroku. Everything was working fine until today when I encountered a problem while trying to log in to the web app. Immediately after logging in, I started receiving 401 responses ...

Steps for enabling a feature flag via API in specific environments

Within my project, I am working with three separate environments and I am looking to activate a feature flag only for a specific environment. Is it feasible to toggle an unleash feature flag using the API for just the development environment? The code snip ...

challenges with template inheritance: when one template takes precedence over another

I have encountered an issue with my two HTML templates, login.html and signup.html. Both of these files inherit from the base.html file, but there seems to be a problem where one file is overriding the title and content of the other. So when I visit /login ...

Is it possible to dynamically add the URL to an iframe based on a condition being true, and then iterate through a list of URLs before

I'm trying to figure out how to change the URL in an iframe based on the presence of a class="show". The first time the element has the class "show," it should load about.html. The second time the same element has the class "show," it should open wor ...

What design pattern serves as the foundation for Angularjs? Is mastering just one design pattern sufficient?

Although I have been teaching myself Angular and can understand how to code in it, I realize that simply learning the concepts of AngularJS and coding or tweaking things to solve problems is not enough. Moving forward, my goal is to write effective and sta ...

Tips for removing special characters from HTML?

I'm currently grappling with the concept of the filter My situation is as follows: $htmlData includes a user-entered html string formatted like this $htmlData = array('<em>test</em>', 'text here','\n') ...

The Express application remains silent unless a port is specified for it to

Having recently started working with Node, I encountered an issue with Express. My application is only listening to localhost:PORT and I want it to also listen to just localhost. Here is the code snippet: ** var app = require('../app'); var debu ...

Vue.js Issue: Image not properly redirected to backend server

Having an issue with my Vue app connecting to the backend using express. When I attempt to include an image in the request, it doesn't reach the backend properly. Strangely though, if I bypass express and connect directly from the Vue app, everything ...

Is there a way for me to access the information within these curly brackets [[]}?

I'm facing a challenge where I need to extract the ID from an API response that is formatted in a way unfamiliar to me. As a result, I'm unsure of how to retrieve the ID data from this response. (This is my initial query, so if it's unclear ...

Exploring JSON data in React applications

Below is the code I am currently working with: export class Highlights extends React.Component { render() { return ( <div> {JSON.stringify(this.props.highlights_data.data)} </div> ) ...

Affix Object to Bottom of Stationary Element

I have a header element that I want to remain fixed while scrolling. The scrollable area should be positioned directly after the fixed header, without using position: absolute and removing it from the document flow. To better illustrate the issue, I' ...

The absence of parameters in the Express.js middleware object

const application = express(); let routerInstance = require('express').Router({mergeParams: true}); const payloadMiddlewareFunction = (request, response, next) => { console.log('A:', request.params); const {params, query} = reque ...

Next JS Dynamic Routing displays successful message on invalid routes

I have been using the App Router feature in Next JS along with Strapi as my CMS. When I make a query to the API endpoint in Postman, I receive the expected results. Requests for routes without corresponding slugs return a 404 error, while only routes with ...