1

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.

Ozan Kurt
  • 2,305
  • 3
  • 14
  • 29
giorgio79
  • 3,025
  • 7
  • 42
  • 70

1 Answers1

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

You forgot to use your conditional offset value.

gnCupo
  • 97
  • 2
  • 7
  • 1
    Yes, @gnCupo beat me to it. Here's the [updated fiddle](https://jsfiddle.net/maneeshchiba/13jex6p5/1/) – Maneesh Jun 30 '16 at 07:32