Creating a div resizing function using only JavaScript is a fun and useful project to tackle

Seeking help to create a div resizer using only pure JavaScript as jQuery is restricted. The current functionality works, but breaks when the position of the slider-div is not set to absolute. Any solutions to fix this issue would be greatly appreciated.

I am an aspiring student learning the ropes of JavaScript/CSS/HTML coding and navigating through some challenges along the way.

const BORDER_SIZE = 4;
const panel = document.getElementById("left_panel");
const StationaryPanel = document.getElementById("right_panel");
const parent = document.getElementById("parent");

const label1 = document.getElementById("lb1");
const label2 = document.getElementById("lb2");
const label3 = document.getElementById("lb3");

let m_pos;

function resize(e) {
  const dx = m_pos - e.x;
  m_pos = e.x;

  lb1.innerHTML = panel.offsetWidth;
  lb2.innerHTML = StationaryPanel.offsetWidth;
  lb3.innerHTML = parent.offsetWidth;

  panel.style.width = (parseInt(getComputedStyle(panel, '').width) + dx) + "px";
  StationaryPanel.style.width = (parent.offsetWidth - panel.offsetWidth) + "px";

}

panel.addEventListener("mousedown", function(e) {
  if (e.offsetX < BORDER_SIZE) {
    m_pos = e.x;
    if (panel.style.width < panel.minWidth || panel.style.width > panel.maxWidth) {
      return;
    }
    document.addEventListener("mousemove", resize, false);
  }
}, false);

document.addEventListener("mouseup", function() {
  document.removeEventListener("mousemove", resize, false);
}, false);
#left_panel {
  position: absolute;
  width: 96px;
  min-width: 50px;
  max-width: 500px;
  padding-left: 4px;
  height: 100%;
  right: 0;
  background-color: #f0f0ff;
}

#left_panel::before {
  content: " ";
  background-color: #ccc;
  position: absolute;
  left: 0;
  width: 4px;
  height: 100%;
  cursor: w-resize;
}

#right_panel {
  width: 1000px;
  height: 100%;
  background-color: #ff0000;
}

#parent {
  width: 800px;
}
<body>
  <div id="parent">
    <div id="left_panel">
      This is the left div, the one that moves
    </div>
    <div id="right_panel">
      This is the right div, the one that stays the same
    </div>
  </div>


  <p id="lb1"></p>
  <p>This is the left panel width ^</p>
  <p id="lb2"></p>
  <p>This is the right panel width ^</p>
  <p id="lb3"></p>
  <p>This is the parent width ^</p>
</body>

Answer №1

If you're looking for a simple solution without the need for Javascript, CSS can come to the rescue. Take a look at this example below to get started on customizing your layout:

#MainDiv {
  display: flex;
  flex-direction: row;
  height: 200px;
  width: 400px;
  border: 1px solid red;
  position: relative;
}

#leftDiv {
  width: 200px;
  border: 1px solid yellow;
}

#rightDiv {
  border: 2px solid;
  padding: 20px;
  width: 300px;
  /* you can make this vertical/auto to make resize both ways */
  resize: horizontal;
  overflow: auto;
}
<div id="MainDiv">
  <div id="leftDiv">
    Left Div
  </div>
  <div id="rightDiv">
    Right Div
  </div>
</div>

For those who prefer a JavaScript approach, here's an alternative method to achieve the same effect:

var h = $('#handle'),
  l = $('#left'),
  r = $('#right'),
  w = $('body').width() - 18;

var isDragging = false;

h.mousedown(function(e) {
  isDragging = true;
  e.preventDefault();
});
$(document).mouseup(function() {
  isDragging = false;
}).mousemove(function(e) {
  if (isDragging) {
    l.css('width', e.pageX);
    r.css('width', w - e.pageX);
  }
});
#left,
#right {
  border: 1px solid #aaa;
  float: left;
  height: 100px;
  width: 48%;
}

#handle {
  background: #000;
  float: left;
  height: 100px;
  margin: 1px;
  /* Slider width */
  width: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="left"> Left</div>
<div id="handle"></div>
<div id="right">Right</div>

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

A guide on integrating MongoDB, Mongoose, Express JS, and Node JS for effectively adding prices

Currently adding various documents to the database: await TestMOdel.insertMany([ { Model: "Samsung", price: 45000, OS: "MS DOS", }, { Model: "Wipro", pr ...

Exploring Data within Data Structures

I am currently making two JSON requests in my code: d3.json("path/to/file1.json", function(error, json) { d3.json("path/to/file2.json", function(error, json2) { }); }); The structure of json 2 looks like this: [ { "city" : "LA", "locati ...

Styling animations in React with inline styles

Exploring the world of React inline animation styling, I set out to create a toggle button. The goal was simple: when the user presses the button for the first time, I wanted a pop-up animated card to slide from left to right. On the second press, the card ...

I have a dynamic blog site that is generated on the fly using Ajax, making the content unsearchable

I have a blog website that is created dynamically using Ajax (XMLHttpRequest) and the HTML History API. One issue I am facing is that my content is not searchable by search engines like Googlebot. I know that Google is now able to analyze such sites, but w ...

What could be causing the AngularUI bootstrap datepicker to not appear?

Exploring the popup datepicker demo from angularUI bootstrap, which is embedded in their page and works perfectly. However, when I tried to create a minimal plunker here, the button click does not open the calendar. Any thoughts on what might be causing th ...

Is there a way to adjust the height pixel value in my code so it can be dynamic?

I have created a simple script that allows selected objects to fade in as the user scrolls down. However, my issue is that this script is quite rigid. If I were to apply it to 20 different objects, for example, I would need to manually adjust the height ea ...

When using res.render to send results, redundant lines are displayed

I feel like I must be missing something really obvious, but for the life of me I cannot figure out what it is. All I want to do is list the documents in a MongoDB collection in a straightforward manner. I am working with nodejs, mongoose, and Jade (althoug ...

The rendering of graphs in FusionCharts is experiencing delays particularly in Internet Explorer, with Chrome performing more efficiently in comparison

I am currently utilizing FusionCharts to generate and display graphs. My requirement is to load over 60 graphs on a single page. Upon testing the page loading in Internet Explorer 11, it is taking approximately 5 minutes. However, when using Google Chrom ...

Unable to Call ZF2 Controller Function

I have been attempting to send a post value to the OrderController using ZF2. I have included JavaScript code in the view folder. Below are the codes: function submitHandler(form) { var urls = '<?php echo $this->baseurl; ?>/order/save ...

Unable to load module/controller file from Angular 1 into view/html

var app = angular.module("appModule",[]); app.controller("viewController",function($scope){ $scope.greeting = "Welcome to the future"; }); <html> <head> <script src="Scripts/script.js"></script> <script ...

Identify the class within a child division and include the class in a separate division

How can I detect a special class within a child div and then add a class to another div when that specific class is found? For example: <ul class="m-a-ul"> <li class="menu"> </ul> Now, if the class collapsed is dynamically added: ...

Nodemon is failing to automatically re-run the changes I've made in my local codebase

Recently, I developed a basic node function that simply outputs "hello world." When I ran the script using the command line node myfirst.js, it successfully displayed the message in the browser. Then, I decided to install nodemon so that it would re-exec ...

Can you help me figure out how to configure my page so that pressing the Enter key does not trigger a postback action?

I'm encountering an issue on one of my asp web pages with a textbox. I am using jQuery to display content in the textbox above it when the user hits the Enter key. However, it always triggers a postback, causing the displayed content to disappear imme ...

Refresh an iframe smoothly and without any visual distraction (using JavaScript)

Does anyone have a clever solution to dynamically refresh an iframe without the annoying flickering or flashing that usually occurs when the page reloads? Is it possible to incorporate a smooth blur-out and blur-in animation instead of the unappealing flic ...

Which is better for handling events - jQuery delegation or function method?

Which approach is quicker and has broader browser support? 1. Utilizing a JavaScript function such as: function updateText(newtext) { $('div#id').text(newtext); } and incorporating it into an element's onclick event: <button onc ...

Struggling to locate the element for clicking or sending keys in Selenium using Java?

Hi everyone, I'm a new member of this forum and I'm just starting out with coding for the first time. I have encountered an issue with a specific part of my code: md-input-container class="md-default-theme md-input-invalid">> label for="i ...

Using Reactjs: How do you insert HTML code into the primaryText of a list item?

Is it possible to include a span element inside a ListItem like so: <ListItem primaryText={"<span class='inner'>Some important info</span>" + item.title} /> When I view the rendered content, the output is not an HTML span ...

Is it possible to search for a value within an array of objects in MongoDB, where the value may be found in any object within that array?

Here is the schema: {"_id":"_vz1jtdsip", "participants":{ "blue":["finettix"] "red":["EQm"] }, "win":"red"," __v":0} I have multiple documents l ...

Difficulties accessing MongoDb database using Node.js

Having issues when trying to read this data collection using mongoose and Node.js: I have a single JSON object within my Collection and I'm attempting to access it with the following code: materias.find().exec(function(err1,materias){ if(err ...

Tips on extracting data from an API using jQuery

Struggling with parsing data and feeling a bit stuck. That's why I'm reaching out for assistance. This is where I need help: How do I specifically retrieve market_cap values? Each value needs to be accessed individually for a specific string I ...