Overlapping img using jQuery

I’m trying to implement an effect on overlapping images so when I click and drag a bar the other image underneath should reveal modifying the width. My code works, but it’s kind of buggy. When I click on the bar I have to then release it to make it work, so it’s not really a drag, and it supposed to stop moving when I release the click.
And second, the bar goes right even outside my container. How could I fix my code?

var up = $("#up");
var bar = $("#bar");
var container = $("#container");

bar.on("mousedown", function () {
    container.on("mousemove", function (e) {
        bar.css("left", e.clientX);

$("body").on("mouseup", function () {

container.on("mouseleave", function () {
* {
    margin: 0;
    box-sizing: border-box;

img {
    height: 400px;
    width: 600px;
    object-fit: cover;

#up {
    width: 50%;

#up {
    position: absolute;
    overflow: hidden;

#container {
    position: relative;
    border: 5px solid cornflowerblue;
    height: 410px;
    width: 610px;

#bar {
    position: absolute;
    height: 400px;
    width: 10px;
    background-color: hotpink;
    left: 300px;
    cursor: e-resize;
<!DOCTYPE html>
<html lang="en">
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <link rel="stylesheet" href="style.css" />
        <div id="container">
            <div id="bottom">
                <img src="https://via.placeholder.com/600x400?text=Image1" alt="image" />
            <div id="up">
                <img src="https://via.placeholder.com/600x400?text=Image2" alt="image" />
            <div id="bar"></div>
        <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
        <script src="script.js"></script>

8 thoughts on “Overlapping img using jQuery”

Leave a Comment