Magnetic div: fixed div inside absolute position of div

I have the following page:

[LINK]

The page is designed to scroll horizontally, so a series of divs (black border) appear in the line.

Now, I have less divs inside (red) to behave so that they never go beyond the parent div, but at the same time, while scrolling the page, I want them to move inside the parent div, as if they were fixed -positioned.

I will explain the diagram to myself. I want my divs to behave like this:

[LINK]

Can anybody help? Thank you for your time!

+7
source share
1 answer

UPDATE


created some minimal / experimental jQuery plugin: https://gist.github.com/3177804

you can use it like this: http://jsfiddle.net/7q3Zu/2/

download and enable the plugin https://raw.github.com/gist/3177804/556074672de8f200327d83f0146d98533c437ac3/jquery.magnetic.js then call it like this:

$(function() { $('.container').magnetic({ //call it on some scrollable container selector: '.object', //what to fix left: 180, //when to fix (px) right: 500 //when to unfix (px) }); });​ 

atm is just an experiment without a guarantee of operation in any browser

(so feel free to grasp the essence and improve it :)


As mentioned in the comments, you can do this using Javascript.

Here is an example using jQuery :

http://jsfiddle.net/7q3Zu/

HTML

 ​<div class="container"> <div class="object"></div> </div>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​ 

Js

 $(function() { var obj = $('.object'); $(document).on('scroll', function() { var offset = $(this).scrollLeft() //fix the position a some point if (offset >= 200) { obj.css('position', 'fixed').css('left', '20px'); } //..and unfix it later if (offset >= 500) { obj.css('position', 'absolute').css('left', '500px'); } }); });​ 

CSS

 .container{ width: 4000px; padding: 20px; margin: 20px; border: 1px solid #ccc; height: 400px; position: relative; } .object{ position: absolute; height: 400px; width :100px; background: red; left: 200px; } 
+3
source

All Articles