ponyboil ponyboil - 2 months ago 10
CSS Question

Javascript focusing a large div with fixed header

I'm using a tiny library called '$.scrollTo' to animate a scroll to a div element in my html. at the top of my page I have a fixed navgation bar.
at the end of the animation, I would like to have that div focused (for accessibility). if my div is to large, at the end of the animation, the fact that it gets focus - simply sends it a bit off the screen.

This does not happen with small divs.

here is my code (check jsfiddle below):

$('#buttonid').on("click", function() {

//fixed nav bar height (to compensate when scrolling)
var fixed_navbar_height = $("#navbar-id").height();

//the element to scroll to
var $go_to_selector = $("#topic2");

$.scrollTo($go_to_selector, {
duration: 1000,
offset: -fixed_navbar_height,
onAfter: function() {
//if you comment out this .focus it works as intended.
$go_to_selector.focus();
}
});
});


here is a JSFIDDLE example:
https://jsfiddle.net/dy35obpq/3/

obviously the onAfter messes it up, but i would like both the animation and the focus. Any ideas on how to implement a focus on a large div without letting it change the scroll bar ? suggestions are more than welcome.

Answer

Try this.

  onAfter: function() {
    $go_to_selector.focus();
    $(window).scrollTop($($go_to_selector).offset().top - fixed_navbar_height);
  }

I have simply added this line in your onAfter callback. $(window).scrollTop($($go_to_selector).offset().top - fixed_navbar_height);

and it seems to have fixed the problem while still retaining focus. You might want to use css to disable the focus blue highlight.