SaturnsEye
SaturnsEye

Reputation: 6499

How would I add margin-bottom using jQuery

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

Upvotes: 6

Views: 8759

Answers (3)

Abhitalks
Abhitalks

Reputation: 28387

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.

Upvotes: 3

Marcos Pérez Gude
Marcos Pérez Gude

Reputation: 22158

You can add the margin bottom in the if statement:

    $('.fixme').css({
        position: 'fixed',
        top: '0',
        left: '0',
        marginBottom: '5%' // you can write with quotes "margin-bottom" too
    });

Upvotes: 2

Tom
Tom

Reputation: 160

Just add it in your .css function when(if) the div is fixed:

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

Upvotes: 0

Related Questions