Skip to content

JavaScript Before & After Comparison

CODEPEN

JavaScript Before & After Comparison

Github: https://github.com/furkangulsen98/HTML-CSS-JAVASCRIPT/tree/master/JavaScript%20Before%20%26%20After%20Comparison


HTML

 <div class="container">
        <div class="image"></div>
        <div class="image"></div>
    </div>

CSS

body{
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
}
.container {
    position: relative;
    overflow: hidden;
    --width: 800px;
    --height: 400px;
    width: var(--width);
    height: var(--height);
}
.image {
    position: absolute;
    height: 100%;
    background: url("https://cn.opendesktop.org/img/c/7/4/1/c5a5f92b530de2cf2c18e917c8a51ac60cb6.jpg");
    background-size: var(--width) var(--height);
}
.image:first-child{
    right: 0;
    width: 100%;
    background-position: center left;
}
.image:last-child{
    right: 0;
    width: calc( 100% - var(--x,50%));
    background-position: center right;
    filter: grayscale(100%);
    box-shadow: inset 2px 0 0 #111, -2px 0 0 #111;
}

JS


        document.querySelectorAll('.container').forEach((elem) => {
            let x, width
            elem.onmouseenter = () => {
                const size = elem.getBoundingClientRect()
                x = size.x
                width = size.width
            }

            elem.onmousemove = (e) => {
                const horizontal = ((e.clientX - x) / width) * 100
                elem.style.setProperty('--x', horizontal + '%')
            }
        })

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: