Shift_Ctrl
Shift_Ctrl

Reputation: 25

Dynamically Center Div Content by Screen Position

I am trying to center the contents of a Div when the user has scrolled down passed the header which is always at the top and is always 120px high. I am wanting to use vanilla javascript and have not found a way to do this?

I need to also be able to decide what is centered and what is not.

Thanks in advance.

Upvotes: 1

Views: 37

Answers (1)

JT Nolan
JT Nolan

Reputation: 1210

You could use something like this.

var sections = $('.section');
$(window).scroll(function() {
    var currentPosition = $(this).scrollTop();
    sections.removeClass('selected').each(function() {
        var top = $(this).offset().top,
            bottom = top + $(this).height();
        if (currentPosition >= top && currentPosition <= bottom) {
            $(this).addClass('selected');
        }
    });
});

Select could do text align center or something.

Upvotes: 1

Related Questions