javascripthtmljquerycssdrag

Drag two textbox and adjust the width of the textbox using JavaScript


I have two textboxes in a row. I want to drag and adjust the width of the text boxes. Something like: "https://www.tutorialspoint.com/online_markdown_editor.php" (Only dragging system). I have already tried something, but the drag is not smooth, and can't drag full width.

// index.html

<!DOCTYPE html>
<html>
<head>
  <title>Log Converter</title>
  <script src="https://cdn.tailwindcss.com"></script>
  <style>
    #input,
    #output {
      height: 80vh;
    }

    * {
    box-sizing: border-box;
    }
    
    .bar {
        height: 90%;
        width: 2px;
        background-color: #ddd;
        cursor: w-resize;
    }
  </style>
</head>
<body class="bg-gray-100">
  <div class="container mx-auto mt-10 p-4">
    <div class="flex gap-2">
        <div class="w-full left">
          <div class="editor">
            <textarea id="input" class="w-full h-48 p-4 bg-white rounded" placeholder="Enter logs here..."></textarea>
          </div>
          <button class="btn bg-green-500 text-white px-4 py-2 mt-4" onclick="convertLogs()">Convert</button>
        </div>
        <div><div class="bar w-1" title="Click & Drug"></div></div>
        <div class="w-full right">
            <textarea id="output" class="w-full h-48 p-4 bg-white rounded" readonly></textarea>
        </div>
    </div>
  </div>
      
  <script>
    const left = document.querySelector(".left"),
          bar = document.querySelector(".bar");

    const drag = (e) => {
        left.style.width = (e.pageX + (bar.offsetWidth * 148)) + "px";
    }

    bar.addEventListener("mousedown", () => {
        document.addEventListener("mousemove", drag);
    })

    window.addEventListener("click", () => {
        document.removeEventListener("mousemove", drag);
    })
  </script>
</body>
</html>

I am not good at frontend design, someone please help me. Thanks in advance.


Solution

  • Finally, I got the solution.

    Update HTML

    <textarea id="input" class="w-full h-48 p-4 bg-white rounded leftbox" 
    placeholder="Enter logs here..."></textarea>
    <textarea id="output" class="w-full h-48 p-4 bg-white rounded rightbox" 
    readonly></textarea>
    

    Just added the 'leftbox' and 'rightbox' classes.

    Add CSS

    #input {
      resize: horizontal;
      min-width: 90px;
      max-width: 1450px;
    }
    #output {
      resize: none;
    }
    

    Add Script

    const left = document.querySelector(".leftbox"),
          right = document.querySelector(".rightbox");
    
    left.addEventListener("mousedown", () => {
        document.addEventListener("mousemove", function(){
          if (left.offsetWidth < 748) {
            right.style.width = (748 + (748 - left.offsetWidth)) + "px";
            
          } else {
            right.style.width = (748 - (left.offsetWidth - 748)) + "px";
          }
        });
    })