Hector X Magoogliades
Hector X Magoogliades

Reputation: 41

Move divs aside when scrolling

Currently I have a page where two divs are set at the left/right sides of the page with a fixed position and I want to achieve an effect where each div will move aside as you scroll down, but move back into place if you scroll back up.

What I'm working with is currently -

html, body{
    height: 100%;
    width: 100%;
}

.left{
    position: fixed;

    left: 0;
    top: 0;

    height: 100%;
    width: 200px;

    background-color: #111111;
}

.right{
    position: fixed;

    right: 0;
    top: 0;

    height: 100%;
    width: 200px;

    background-color: #111111;
}

In the HTML, there are just two divs with the class left/right

IS there a Javascript plugin or library that I can use to easily achieve this effect?

Upvotes: 4

Views: 2310

Answers (1)

Alvaro Menéndez
Alvaro Menéndez

Reputation: 9012

If I understood your question right it's easy enough. You could use this little jquery:

$(window).scroll(function (event) {
    var scroll = $(window).scrollTop();
    $('.left').css('left', - scroll / 4);
    $('.right').css('right', - scroll / 4);
});

which basically detects the current scroll position as a variable (scroll) and you add that value to your rightand left css values. (I divided the mumber by four so it will decrease the "scroll" value added to the css making the "animation" slower)

$(window).scroll(function (event) {
    var scroll = $(window).scrollTop();
    $('.left').css('left', - scroll / 4);
    $('.right').css('right', - scroll / 4);
});
html,
body {
  height: 2000px;
  width: 100%;
  margin:0;
}

.left {
  position: fixed;
  top: 0;
  height: 100%;
  width: 200px;
  background-color: #111111;
}

.right {
  position: fixed;
  right: 0;
  top: 0;
  height: 100%;
  width: 200px;
  background-color: #111111;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<div class="left"></div>
<div class="right"></div>

JSFIDDLE

Upvotes: 1

Related Questions