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

Using a React component to trigger an action when the Enter key

I have a react component that needs to respond to the "Enter" key press event. class MyComponent extends Component { componentDidMount() { console.log('componentDidMount'); document.removeEventListener('keypress', t ...

What's the best way to ensure that your item list automatically updates the rendered list when an item is deleted

I've developed a web cart using Redux. The cart functions as expected, except for one issue - when I delete an item from the cart, the changes are only displayed after refreshing or navigating to another page. How can I update the view dynamically as ...

The issue with Three.Js Raycasting arises when attempting to change camera transformations within an Object3D parent element

In my latest project, I decided to create a "camera controller" that handles the movement and rotation of the camera by utilizing an Object3D as its parent. The Y-axis rotations are applied to the Object3D, while the X-axis rotation is directly applied to ...

Using Javascript's .replace() method to preserve HTML elements

This is a JavaScript function I wrote function replaceCharacters(text_input){ return text_input .replace(/O/g, 0) .replace(/I/g, 1) .replace(/o/g, 0) .replace(/i/g, 1) .replace(/t/g, 4) .replace(/d/g, 9) ...

Passing information using AJAX, utilize the data as a paragraph in PHP

As someone with limited experience in PHP, I've been attempting to create a basic "adminpage" on my own. However, I've run into an issue when passing a value via AJAX from the adminpage to the index page - the value does not appear in the paragra ...

Firefox experiencing trouble handling flexbox overflow

Having some trouble with a test project that involves using flexbox. The task at hand is to create a dashboard with multiple lists of cards arranged side-by-side with infinite overflow. I was able to achieve this layout, however, the issue arises when eac ...

Using the debug module, we're able to set up debugging for our Express application with the specific tag "express-locallibrary-tutorial:server". I am curious to understand the purpose and significance of this setup

I've been diving into backend development with Express lately. I decided to work on the express-locallibrary-tutorial project from GitHub. However, I'm having trouble grasping something. var debug = require('debug')('express-locall ...

Implementing the display of bootstrap modal with error message upon page reload in CodeIgniter

Currently, I have a popup model that allows users to add a course name. In my Codeigniter controller, I have implemented form validation. If the validation fails, I reload the view with an error message displayed above the form input in the modal. However, ...

Finding out the RAM restriction of Docker for Mac through NodeJS

Understanding the Docker Limitation In our development setup, we utilize Docker for Mac to overcome the compatibility issues between Docker/Linux Containers and MacOS/Darwin/Unix. Docker for Mac employs a Linux virtual machine internally to run all contai ...

The Web Browser is organizing CSS elements in an alphabetized sequence

map.css({ 'zoom': zoom, 'left': map.width()/(2*zoom) - (point[0]/100)*map.width(), 'top': map.height()/(2*zoom) - (point[1]/100)*map.height() Upon observation, it appears that Chrome adjusts the map zoom first be ...

Fixed: Transmitting user's verified email from website to chrome extension

I am currently in the process of developing a website named websiteA using Laravel 8 and Vuejs, along with a Chrome extension that utilizes JavaScript for web scraping. This extension is designed to extract content from another websiteB, and my goal is to ...

Expansion issue with Bootstrap panel

I am currently using Bootstrap 3 for the development of a social networking site. The issue I'm encountering involves displaying comments within a panel footer on toggle. However, the comments are extending beyond the footer area. Can anyone provide g ...

Switching the checkbox state by clicking a button in a React component

Is there a way to update checkbox values not just by clicking on the checkbox itself, but also when clicking on the entire button that contains both the input and span elements? const options = ["Option A", "Option B", "Option C"]; const [check ...

Utilize JavaScript to submit the FORM and initiate the 'submit' Event

Hey there! Here's the code I've been working on: HTML : <html> <body> <form enctype="multipart/form-data" method="post" name="image"> <input onchange="test();" ...

How can I create interactive markers on Google Maps?

I'm looking to incorporate Google Maps into a website. I will be receiving data on the client side in JSON format and I want to dynamically add markers based on that data. Additionally, I would like the markers to display iteratively, similar to the a ...

Steps to create an automatic submission feature using a combobox in HTML5 and then sending the retrieved data back to the HTML file

Here is the code snippet I've been working on: <strong>Station Name</strong> <!--This portion includes a combobox using HTML5 --> <input type=text list=Stations> <datalist id=Stations> <option>Station1</opt ...

Error in Typescript: Draggable function is undefined

I'm currently working with typescript alongside vue and jquery ui. Encountering the error "TypeError: item.$element.draggable is not a function". What am I doing wrong in my code? I have already included jquery-ui, as shown in the following files. M ...

Learn about Angular8's prototype inheritance when working with the Date object

In my search for a way to extend the Date prototype in Angular (Typescript), I stumbled upon a solution on GitHub that has proven to be effective. date.extensions.ts // DATE EXTENSIONS // ================ declare global { interface Date { addDa ...

Looking through a Json file and retrieving data with the help of Javascript

I am currently working on developing a dictionary application for FirefoxOS using JavaScript. The structure of my JSON file is as follows: [ {"id":"3784","word":"Ajar","type":"adv.","descr":" Slightly turned or opened; as, the door was standing ajar.","tr ...

Understanding the most recent tweet using the most up-to-date Twitter API

My goal is to retrieve the latest tweet using the most recent version of Twitter's API and add it to a specific div on my website. Despite attempting the code below, I have not been successful. If anyone could provide guidance on how I can accomplish ...