giorgio79 giorgio79 - 5 months ago 6
CSS Question

Scrolling to and vertically centering an element inside a div with javascript

I am trying to scroll to an element inside a div, and center it vertically in the div.

I have tried so far this code but no luck.

jQuery(document).on('click', '#scroll_button', function(e) {
var el = $( "#scroll_test" );
var elOffset = el.offset().top;
var elHeight = el.height();
var windowHeight = $("#editor").height();
var offset;

if (elHeight < windowHeight) {
offset = elOffset - ((windowHeight / 2) - (elHeight / 2));
}
else {
offset = elOffset;
}

jQuery('#editor').animate({
scrollTop: $("#scroll_test").offset().top
}, 1000);
});


I am using this example, but it is not working as per the fiddle. The scroll gets where the element is at the top of the holding element. I would like to have it in the vertical center.

I also learned that using jQuery to get an element's height maybe inaccurate, and pure js should be used, but I did not have luck with that also.

I started from this question originally.

Answer
jQuery('#editor').animate({
    scrollTop: offset
  }, 1000);
});

You forgot to use your conditional offset value.

Comments