Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would I add margin-bottom using jQuery

Tags:

jquery

margin

Here's the code I am using that fixes a div to the top of the page while scrolling but I want to give the div a margin after it gets fixed to the top.

var fixmeTop = $('.fixme').offset().top;
$(window).scroll(function() {
    var currentScroll = $(window).scrollTop();
    if (currentScroll >= fixmeTop) {
        $('.fixme').css({
            position: 'fixed',
            top: '0',
            left: '0'
        });
    } else {
        $('.fixme').css({
            position: 'static'
        });
    }
});

I've seen examples such as this to add margin using jQuery, but I can't get it to apply to my code:

$('.fixme').css('margin-bottom',90);

You'll see that when the div gets fixed to the top of the page the space between the two elements closes up. I want to add margin to the div after so that it has the same distance as soon as it sticks.

FIDDLE

like image 270
SaturnsEye Avatar asked Nov 03 '15 09:11

SaturnsEye


1 Answers

You'll see that when the div gets fixed to the top of the page the space between the two elements closes up. I want to add margin to the div after so that it has the same distance as soon as it sticks.

You can't do that. That's because, once an element is fixed, it is removed from the flow and is in a different layer altogether from the rest of your content. Putting margin on fixed element will not work because that is in a different layer. Content scrolls past from behind this div and there is no way you can control the spacing. Content is going to get covered up by this div anyway. Check this fiddle to see what I mean (added shadow to help you visualize the layers):

Demo Fiddle 1: http://jsfiddle.net/abhitalks/3Lv6fL7r

If you just want to avoid the abrupt jumping of that div, just add margin-top to that div. Alternatively (and a better way), keep those styles in CSS and apply / remove those classes.

Demo Fiddle 2: http://jsfiddle.net/abhitalks/zu75wpqm/5

Note: You need marginTop instead of margin-top when you are using that as a property via Javascript.

like image 129
Abhitalks Avatar answered Nov 03 '22 13:11

Abhitalks