← Back to list

Creating a Movable Window in HTML and JavaScript: A Simple Guide

Learn to create a draggable window using HTML, CSS, and JavaScript. Enhance user experience with this simple, flexible guide!

Fabian Mejia · 2024-10-29 19:46 · 52 claps · 3.4 min read
#javascript #javascript-tips #javascript-development #ui-interaction #software-development
Open on Medium ↗
Wiki topics: RAG · RAG & Retrieval UX · UI/UX Design 🌐 · Web Development

Creating a Movable Window in HTML and JavaScript: A Simple Guide

If you’ve ever used a design tool or a web-based editor, you’ve probably encountered one common interaction: movable windows. These draggable panels make it easier to customize the workspace by allowing users to rearrange their screen. It’s a feature that’s surprisingly simple to implement using just HTML, CSS, and a touch of JavaScript.

In this post, we’ll walk through the fundamentals of creating a movable window that can be seamlessly integrated into any web application. The example is framework-agnostic, meaning it can be adapted to fit any development stack. For styling, we’ll leverage Tailwind CSS to maintain efficiency and flexibility.

We’ll also attach a click event listener to the body element, which will dynamically create and display the movable window. The window will consist of a header (to enable dragging), some body content, and a close button. To interact with these elements in our JavaScript, we’ll assign unique id attributes for straightforward identification.

To achieve smooth movement, we’ll modify the position of the container using CSS custom properties (--), allowing us to easily update its placement as the user drags it around.

<body class="w-screen h-screen">
    <div 
        id="movable-container" 
        class="w-40 h-auto rounded-md bg-blue-100 p-2 select-none fixed hidden"
        style="top: var(--top); left: var(--left)"
    >
        <div class="text-lg w-full text-center font-bold">Herramientas</div>
        <div class="italic w-full justify">Visualización de información rándom</div>
        <div class="w-full flex justify-end">
            <button id="movable-close-button" class="bg-red-400 px-2 rounded text-white">close</button>
        </div>
    </div>
</body>

Inside our JavaScript file, we’ll start by selecting the necessary HTML elements right at the beginning. By selecting these elements up front, we ensure that our code remains clean and organized as we implement the interactive behavior.

const container = document.querySelector('#movable-container');
const movableCloseButton = document.querySelector('#movable-close-button');
const body = document.querySelector('body');

Next, we’ll add a click listener to the body element to handle opening the movable window, making it easy to trigger the window as needed.

body.addEventListener('click', (e) => {
    container.classList.remove('hidden');

    const x = e.clientX;
    const y = e.clientY;

    container.style.setProperty('--left', `${x}px`);
    container.style.setProperty('--top', `${y}px`);
});

At this point, we have the window opening wherever the user clicks.

Clicking on any random position…

Clicking on any random position…

Next, we need to set up an event listener for the mousedown event. When the user clicks the mouse, we’ll compute the difference (delta) between the top-left position of the movable window and the current cursor position. We'll also set a status variable to track when the mouse button is held down.

Using this delta, we can translate the container’s position as the mouse moves. To avoid potential bugs, we’ll add the mousemove event listener to the window rather than the container itself (I’ll demonstrate these bugs in a GIF). Finally, when the user releases the mouse button (mouseup), we’ll set the status variable to false.

I’ve structured the code this way for simplicity, but you could easily implement separate events if needed.

container.addEventListener('mousedown', (e) => {
    isMouseDown = true;
    const x = e.clientX - container.offsetLeft;
    const y = e.clientY - container.offsetTop;

    window.addEventListener('mousemove', (e) => {
        if (isMouseDown) {
            container.style.setProperty('--left', `${e.clientX - x}px`);
            container.style.setProperty('--top', `${e.clientY - y}px`);
        }
    });

    container.addEventListener('mouseup', () => {
        isMouseDown = false;
    });
});

Expected behavior…

Expected behavior…

Adding the mousemove event to the container can lead to bugs, particularly if the mouse moves quickly. This could cause the movable window to stop responding, as it may not continuously detect the mouse's position. By attaching the event listener to the window instead, we ensure smoother movement even at faster speeds.

Mouse move event on container bug

Mouse move event on container bug

If we don’t compute the delta during the mousedown event, we may encounter the following bug.

Failing to compute the delta during the mousedown event will make ending the dragging process a nightmare.

Failing to compute the delta during the mousedown event will make ending the dragging process a nightmare.

In this guide, we covered how to create a movable window using HTML, CSS, and JavaScript. This feature enhances user experience by allowing for a customizable workspace and illustrates how simple interactions can improve usability in web applications.

By using Tailwind CSS for styling and JavaScript for event handling, we implemented a functional component with minimal effort. Key points include the importance of computing deltas for smooth dragging and correctly applying event listeners to prevent bugs.

You can further enhance this implementation by adding features like resizing or persistence of window positions. This foundational knowledge can serve as a basis for more advanced user interface components.


메타데이터
post_id
8ccda0d88eff
slug
creating-a-movable-window-in-html-and-javascript-a-simple-guide-8ccda0d88eff
url
https://medium.com/@fibianmejia/creating-a-movable-window-in-html-and-javascript-a-simple-guide-8ccda0d88eff
canonical_url
https://medium.com/@fibianmejia/creating-a-movable-window-in-html-and-javascript-a-simple-guide-8ccda0d88eff
author_url
https://medium.com/@fibianmejia
status
ok
fetched_at
2026-06-15 20:49:13