2

I have a layout in which the sidebar is resizable. I have done that using Javascript. But I want it to have a maximum and minimum value of resize. I have done that for the sidebar part by setting the max-width and min-width for the sidebar. But the problem is that main area goes decreasing(when expanding) even though the sidebar has been limited using max-width. I have been adding margin-left property to the main area according to the cursor pointer movement (using js ). But there is no property which allows us to set the maximum or minimum margin-left. How can I achieve this. Can anybody suggest any workaround to this ?

Js Fiddle - The whole code - https://jsfiddle.net/pdo4yjmg/

Please try to expand above 400px in the fiddle result , you can see the problem there ( 400px is the max-width )

Js part -

var element = document.getElementById('resizable');
  if (element) {
    var resizer = document.createElement('div');
    resizer.className = 'draghandle';
    resizer.style.width = '6px';
    resizer.style.height = '100vh';
    element.appendChild(resizer);
    resizer.addEventListener('mousedown', initResize, false);
  }

  function initResize(e) {
    window.addEventListener('mousemove', Resize, false);
    window.addEventListener('mouseup', stopResize, false);
    document.getElementById("mainArea").classList.add('marginLeft')
  }

  function Resize(e) {
    element.style.width = (e.clientX - element.offsetLeft) + 'px';
    document.getElementById("mainArea").style.marginLeft = (e.clientX - element.offsetLeft) + 'px';
  }

  function stopResize(e) {
    window.removeEventListener('mousemove', Resize, false);
    window.removeEventListener('mouseup', stopResize, false);
  }
theFrontEndDev
  • 890
  • 1
  • 17
  • 41

2 Answers2

1

Since you have successfully constrained the sidebar to a min-width of 200 and max-width of 400, I would suggest you do the same with your margin-left. But there is no such property in CSS that allows for limiting the margin, you would need to resort to JavaScript. Perhaps where you set the margin-left of mainArea, ensure your new value is between 200 and 400:

document.getElementById("mainArea").style.marginLeft = Math.min(Math.max(parseInt((e.clientX - element.offsetLeft)), 200), 400) + 'px';

Also, see How can I use JavaScript to limit a number between a min/max value?

Muhammad Talha Akbar
  • 9,952
  • 6
  • 38
  • 62
1

Complete resizable:

  function Resize(e) {
    element.style.width = (e.clientX - element.offsetLeft) + 'px';
    if(parseInt(element.style.width) <- 200)
        lement.style.width = '200px'
    document.getElementById("mainArea").style.marginLeft = (e.clientX - element.offsetLeft) + 'px';
  }