What is the best way to make three divs that can be adjusted in size?

Desired Layout:

  |   A   | |   B   | |   C   |
           ^         ^

Adjustment Behavior:

  | A | |   B      | |    C   |

Current Issue:

  |   A  |           C        |

I attempted to enhance the functionality by modifying the provided JavaScript code:

var isResizing = false,
    who='',
    lastDownX = 0;

$(function () {
    var container = $('#container'),
        left = $('#left'),
        right = $('#right'),
        middle = $('#middle'),
        hand2 = $('#hand2'),
        handle = $('#handle');

    handle.on('mousedown', function (e) {
        isResizing = true;
        who=e.target.id;
        lastDownX = e.clientX;
}          
       
$(document).on('mouseup', function (e) {

isResizing = false;        
}).on('mousemove', function (e) {
    
if (!isResizing) 
            return;
        
var minSize = container.width() * 0.1;
var newPosition = container.width() - (e.clientX - container.offset().left);
        
if (newPosition < minSize)
            newPosition = minSize;
             
 if (who == 'handle')
            right.css('width', newPosition);

if (who == 'hand2')
            left.css('width', newPosition);
  
});
});

Test the modified behavior here: https://jsfiddle.net/ju9zb1he/5/

Answer №1

I was searching for a solution that required minimal CSS modifications. While there was a minor bug (FIXED), I believe this example will give you a good starting point. Feel free to check out the DEMO.

In addition, my goal was to utilize DOM Traversal methods like .next() and .prev() in order to reduce reliance on specific attributes and make it easily reusable if needed multiple times on a page.

Edit - More Details

The concept here is that upon clicking a .handle, we calculate the total width (var tWidth) of the .prev() and .next() divs relative to the .handle within the DOM. We then use the initial mouse position (var sPos) to determine how many pixels our mouse has moved (e.pageX). This calculation provides us with the correct width for the .prev( ) div during the mousemove event. To obtain the width of the .next() div, we subtract the width of the .prev() div from the total width (var tWidth) stored upon clicking the .handle. I hope this clarifies things! Let me know if you have any more questions, although I may not be available until tomorrow.

HTML

<div class="container">
    <div id="left"></div>
    <div id="l-handle" class="handle"></div>
    <div id="middle"></div>
    <div id="r-handle" class="handle"></div>
    <div id="right"></div>
</div>

CSS

#left, #middle, #right {
    display: inline-block;
    background: #e5e5e5;
    min-height: 200px;
    margin: 0px;
}

#l-handle, #r-handle {
    display: inline-block;
    background: #000;
    width: 2px;
    min-height: 200px;
    cursor: col-resize;
    margin: 0px;
}

jQuery

var isDragging = false,
    cWidth = $('.container').width(),
    sPos,
    handle,
    tWidth;
$('#left, #middle, #right').width((cWidth / 3) - 7); // Set the initial width of content sections

$('.handle').on('mousedown', function(e){
    isDragging = true;
    sPos = e.pageX;
    handle = $(this);
    tWidth = handle.prev().width() + handle.next().width();
});

$(window).on('mouseup', function(e){
    isDragging = false;
});

$('.container').on('mousemove', function(e){
    if(isDragging){ 
        var cPos = sPos - e.pageX;
        handle.prev().width((tWidth / 2) - cPos); 
        handle.next().width(tWidth - handle.prev().width());
    }
});

Edit

The bug stemmed from two issues:

1) During mousemove, we were dividing the total width by two instead of using an updated mouse offset.

2) The sPos value wasn't updating on mousemove, remaining static based on the initial click location.

Resolution

Updates include adjusting sPos on mousemove to accurately reflect the mouse's movement for precise calculations. By subtracting the .next() div's width from the total width, then further subtracting the current mouse position, we ensure accurate resizing. Check the updated fiddle.

$('.container').on('mousemove', function(e){
    var cPos = sPos - e.pageX;
    if(isDragging && ((tWidth - handle.next().width()) - cPos) <= tWidth){
        handle.prev().width((tWidth - handle.next().width()) - cPos);
        handle.next().width(tWidth - handle.prev().width());
        sPos = e.pageX;
    }
});

Edit

An additional condition was added on mousemove to prevent dragging beyond the total width (var tWidth).

Answer №2

Could you clarify your objective for me?

I believe the use of position: absolute may not be necessary in this case. Absolute positioning is typically used to override the margin and padding set by a parent element.

In this scenario, default relative positioning should suffice as it allows elements to interact with one another without overlapping.

It seems like all you need is some basic CSS to achieve your goal. Here's a simple example: http://jsfiddle.net/xyz123/

<div class='first'>
    abc
</div><div class='second'>
    def
</div><div class='third'>
    ghi
</div>

body {
    margin: 0;
}

div {
    display: inline-block;
    height: 100%;
}

.first, .third {
    width: 40%;
}

.first {
    background-color: yellow;
}

.second {
    background-color: purple;
    width: 20%;
}

.third {
    background-color: orange;
}

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

The issue with updating the menu class in Internet Explorer 8 is not being resolved

Here is a code snippet using JavaScript: var x = jQuery(window).innerHeight(); jQuery(document).scroll(function() { if (jQuery(this).scrollTop() >= x) { jQuery('#nav').removeClass('nav').addClass('topfix_nav'); ...

What is the method for opening the image gallery in a Progressive Web App (PWA)?

I am struggling to figure out how to access the image gallery from a Progressive Web App (PWA). The PWA allows me to take pictures and upload them on a desktop, but when it comes to a mobile device, I can only access the camera to take photos. I have tried ...

How can you retrieve the ID of the container at the top layer using jQuery?

My webpage is filled with HTML controls that look like this: <span id="pic1" class="container"> <span class="inner"> <span class="img"></span> <span class="strip"></span> <span class="remove_ ...

Filtering URLs using Firefox extension

As the page loads, multiple HTTP requests are made for the document and its dependencies. I am looking to intercept these requests, extract the target URL, and stop the request from being sent if a specific condition is met. Additionally, plugins may als ...

Issue with scrollTop functionality on Android smartphones

Currently working on implementing chat functionality for an Android mobile app using jQuery and jQuery mobile theme for the frontend. The issue I am encountering is related to the scrollTop() function not functioning as expected in Android browsers. Does ...

What steps should I take to make sure that the types of React props are accurately assigned?

Dealing with large datasets in a component can be challenging, but I have found a solution by creating a Proxy wrapper around arrays for repeated operations such as sorting. I am looking to ensure that when the data prop is passed into my component as an ...

CRUD operations are essential in web development, but I am encountering difficulty when trying to insert data using Express

I am currently attempting to add a new category into the database by following the guidelines provided in a course I'm taking. However, I am encountering difficulties as the create method does not seem to work as expected. When I try it out in Postman ...

Select the first item that is visible and chosen

Currently, I am working with a select list: <option ng-repeat="hour in Hours" value="{{hour.Value}}" ng-show="filterEvent($index)" ng-selected="hour.Value == EventDate || $first"> {{hour.Text}} </opti ...

Unable to reach 'this' within a nested function

Struggling with a coding issue for hours now and in need of some assistance. The challenge at hand involves creating an object named Rank. Rank is expected to make DB calls in mongodb to retrieve data needed to populate a matrix, followed by executing nes ...

Incorporating external script into React website's functional component

I have invested countless hours on this particular issue, which appears to be quite trivial, yet I am unable to pinpoint where my mistake lies. I recently purchased terms and conditions from Termly.com and now wish to showcase these terms and conditions o ...

Customizing Styles in Material UI with React

I am facing an issue with customizing the styles in my Material UI theme in React. Specifically, I am trying to modify the border of the columnsContainer but it doesn't seem to work, only the root style is having an effect. Take a look at this Codesa ...

What is the method to provide function parameters without executing the function?

I'm searching for a solution to obtain a function that requires a parameter without actually invoking the function. Example of current malfunctioning code: const _validations = { userID: (req) => check('userID').isString().isUUID(&apo ...

Personalized Firefox Scrollbar - Rounded Corners

I have successfully customized the default CSS of browser scrollbars for Chrome and Edge, but I am facing issues with Firefox. Is there a way to sync the scrollbar styling in Firefox with Chrome and Edge? Currently, I am unable to apply border radius to th ...

How to calculate the difference in months between two dates using JavaScript

Is there a way to calculate the number of months between two dates taking into account specific conditions, such as when the dates are not exact and may have different day counts? Here is an example using the moment library: var date1 = moment('202 ...

Functions perfectly on Chrome, however, encountering issues on Internet Explorer

Why does the Navigation Bar work in Chrome but not in Internet Explorer? Any insights on this issue? The code functions properly in both Internet Explorer and Chrome when tested locally, but fails to load when inserted into my online website editor. Here ...

Utilizing CSS to position an image at both the top and bottom of a webpage

I have been struggling to find a solution to this particular issue. My goal is to position an image at both the top and bottom of the page using a background property. I understand that by making the positioning relative, the image will be placed at the bo ...

What is the jQuery alternative for the classList property in vanilla JavaScript?

Currently, I am working on a collaborative project with two acquaintances. One of the requirements is to stick to either vanilla JavaScript selectors like document.getElementById("thisDiv"); or jQuery selectors such as $("#thisDiv"); to maintain consis ...

Is there a way to manage the state of a dictionary nested within a list using React JS?

Below is a snippet of my code. I am attempting to update the state of data (which is contained within datasets) to a value defined by the user. constructor(props) { super(props); this.state={ value:'', set:[], coun ...

Repositioning a jQuery function from inside a plugin

I need assistance with customizing the functionality of a jQuery plugin called AjaxFileUpload. You can find the plugin here: https://github.com/davgothic/AjaxFileUpload The current behavior of the plugin is that it uploads the file as soon as it is select ...

Managing headers for localhost with Access-Control-Allow-Origin

I've run into a challenge with my React app. I'm making endpoint calls to different servers and have withCredentials set to true to include a token/cookie in the requests. The issue arises when trying to make this work seamlessly on localhost. S ...