user3356048 user3356048 - 7 months ago 20
Javascript Question

How to fix an element to viewport center regarding the container element?

Consider two container elements side by side, both of them are longer than the width of the viewport and the viewport is scrollable horizontally. Both of them contain an element inside that I want to keep in the center of visible portion of the containing div. Here is the markup:

<body>
<div class="wrapper">
<div class="container" id="container1">
<div class="element" id="element1"></div>
</div>
<div class="container" id="container2">
<div class="element" id="element2"></div>
</div>
</div>
</body>


and here is the css:

body {
overflow-x: auto;
}
.wrapper {
width: 400%;
}
.container {
width: 50%;
border: 1px solid #ccc;
height: 50px;
float: left;
}


I am very sorry I find it very difficult to describe what I need since English is not my native language but I would like to describe it with an image and an animation:

[The effect I want to achieve in steps2
[The effect I want to achieve in animated gif form]1

Answer

Here is what you want.

Gift: check out the prettier meoww version.

$(".parallax").on("scroll", function() {
    var scrollValue = $(this).scrollLeft();
    var parallaxWidth = $(this).width();

    $(".box").each(function() {
        var container = $(this).parent();
        var containerWidth = $(container).width();
        var isLeftBox = $(container).is("#left");
        var ratioParallax = parallaxWidth/containerWidth;
        var ratioScroll = scrollValue/containerWidth;

        var move = 50*ratioParallax;

        if (isLeftBox) {
            move += ratioScroll*100;

            if (ratioScroll > 1/3)
                move -= (ratioScroll-1/3)*50;
        } else {
            move += (ratioScroll-1)*100;

            if (ratioScroll < 1)
                move -= (ratioScroll-1)*50;
        }

        $(this).css("left", move+"%");
    });
});

$(".parallax").trigger("scroll");
div.parallax {
    height:200px;
    width:400px;
    overflow-x:scroll;
    overflow-y:visible;
}
div.parent-container {
    height:100%;
    width:300%;
}
div.container {
    width:50%;
    height:100%;
    float:left;
    overflow:hidden;
}
body div.container#left {
    background-color:red;
}
body div.container#right {
    background-color:blue;
}
div.box {
    height:50px;
    width:50px;
    margin-top:-25px;
    margin-left:-25px;
    background-color:yellow;
    position:relative;
    top:50%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parallax">
    <div class="parent-container">
        <div id="left" class="container">
            <div class="box"></div>
        </div>
        <div id="right" class="container">
            <div class="box"></div>
        </div>
    </div>
</div>