How to Make a <Div> Move Up and Down When I'm Scrolling the Page

How do I make a div move up and down when I'm scrolling the page?

You want to apply the fixed property to the position style of the element.

position: fixed;

What browser are you working with? Not all browsers support the fixed property. Read more about who supports it, who doesn't and some work around here

http://webreflection.blogspot.com/2009/09/css-position-fixed-solution.html

Force div element to stay in same place, when page is scrolled

Change position:absolute to position:fixed;.

Example can be found in this jsFiddle.

how to move div up & down on window scroll

You should be using 'position: absolute' and 'top' and 'left' instead of margins.
By using margins you are pushing them off each other making them make the page massive.

$(window).scroll(function() {
$(".mydiv").css({
"top": ($(window).scrollTop()) + "px",
"left": ($(window).scrollLeft()) + "px"
});
});

See this codepen - http://codepen.io/dmoojunk/pen/JXBaXm

How can I make a div stick to the top of the screen once it's been scrolled to?

You could use simply css, positioning your element as fixed:

.fixedElement {
background-color: #c0c0c0;
position:fixed;
top:0;
width:100%;
z-index:100;
}

Edit: You should have the element with position absolute, once the scroll offset has reached the element, it should be changed to fixed, and the top position should be set to zero.

You can detect the top scroll offset of the document with the scrollTop function:

$(window).scroll(function(e){ 
var $el = $('.fixedElement');
var isPositionFixed = ($el.css('position') == 'fixed');
if ($(this).scrollTop() > 200 && !isPositionFixed){
$el.css({'position': 'fixed', 'top': '0px'});
}
if ($(this).scrollTop() < 200 && isPositionFixed){
$el.css({'position': 'static', 'top': '0px'});
}
});

When the scroll offset reached 200, the element will stick to the top of the browser window, because is placed as fixed.

How to make div fixed after you scroll to that div?

This is now possible with CSS only, see https://stackoverflow.com/a/53832799/1482443


In case anyone needs jQuery approach, below is the original answer as it was posted years ago:

I know this is tagged html/css only, but you can't do that with css only. Easiest way will be using some jQuery.

var fixmeTop = $('.fixme').offset().top;       // get initial position of the element

$(window).scroll(function() { // assign scroll event listener

var currentScroll = $(window).scrollTop(); // get current position

if (currentScroll >= fixmeTop) { // apply position: fixed if you
$('.fixme').css({ // scroll to that element or below it
position: 'fixed',
top: '0',
left: '0'
});
} else { // apply position: static
$('.fixme').css({ // if you scroll above it
position: 'static'
});
}

});

http://jsfiddle.net/5n5MA/2/



Related Topics



Leave a reply



Submit