0

I have created a resources site that has multiple pages of content. Each page has 20-30 Bootstrap accordions. When clicked the accordions expand to display additional information about the given resource.

My goal is for the homepage to have "Featured Resources" that when clicked will navigate to the page and open the requested accordion. I'd like to use a # to navigate (site.com/page.html#featured-resource)

The following script allows me to navigate to the page using a hashtag and open the requested accordion, but does not actually scroll to that part of the page.

 $(document).ready(function () {
 location.hash && $(location.hash + '.collapse').collapse('show');
 });

I would like for this to not only open the accordion, but to scroll to that part of the page as well. How would I make this happen?

Thanks!

bill
  • 3
  • 2

2 Answers2

0

Bill-

Try using this snippet of jQuery-->

//$( document ).ready(function() {

//location.hash && $(location.hash + '.collapse').collapse('show');

//Move the window's scrollTop to the offset position of the div named #now
$(window).scrollTop($('#now').offset().top);

//});

Let me know if this works for you. Cheers!

Mussser
  • 507
  • 7
  • 18
  • This will work, but is it possible to have the element to scroll to be defined by what the hash equals? For instance, if the hash is #scroll-element have $(window).scrollTop($('#scroll-element').offset().top);? – bill Jan 21 '14 at 21:08
  • Yeah that will absolutely work, you just need to pass the unique #ID to the next page so that the function can scroll the user to the correct place on the page. – Mussser Jan 21 '14 at 23:16
  • I would need to see more code in order to help you further. Do you have some example code of the home page accordions and the accordions on the page the user would land on after click? – Mussser Jan 21 '14 at 23:17
0

Try the following

$(document).ready(function(){
  var posTop = $(location.hash + '.collapse').offset().top;
  $('html,body').animate({
      scrollTop: posTop - 20; //where 20 is allowance from top of the page
   });
});
tlogbon
  • 1,052
  • 10
  • 12
  • This should only scroll down 20px from the top of the page, no? This doesn't seem to be specific to any div... – Mussser Jan 21 '14 at 20:42
  • This will scroll to the div identified by the selector `location.hash + '.collapse'`, that's the essence of the `posTop` variable, the 20 is only a random allowance value. – tlogbon Jan 22 '14 at 00:14
  • tlogbon - Ahh I see, thank you. bill - I didn't try this but it may work for you. Let us know if it achieves what you're looking for. – Mussser Jan 22 '14 at 01:02