0

I have the following code which enables me to link to a specific tab from another page. The only problem is that when the link is clicked the page is loaded and then scrolled down to where the DIV is located. I want it to just load the page at the top.

Any help would be appreciated.

<script type="text/javascript">
$(function() {
  // Javascript to enable link to tab
  var url = document.location.toString();
  if (url.match('#')) {
    $('.nav-tabs a[href=#'+url.split('#')[1]+']').tab('show') ;
  }

  // Change hash for page-reload
  $('a[data-toggle="tab"]').on('show.bs.tab', function (e) {
    window.location.hash = e.target.hash;
  });
});
</script>

The hyperlink back to the page with the tabs is as follows.

<a href="../view_mail/#two" class="btn btn-theme">Close</a>

Many thanks,

John

John Higgins
  • 857
  • 12
  • 25

3 Answers3

0

There is probably a better way to do this but try just scroll to the top after a click.

$( "body" ).scrollTop(0);
johnny 5
  • 19,893
  • 50
  • 121
  • 195
0

The following unfortunately will likely not work:

e.preventDefault();

(How to prevent jump on an anchor click?)

The above will not solve the problem because, I believe, preventDefault does not apply to updating location.hash (How can I update window.location.hash without jumping the document?).

Alternatively you can use the scrollTop method, but you may see a scroll jump temporarily with this method:

$("body").scrollTop(0);

In modern browsers, you can use the History Api (How can I update window.location.hash without jumping the document?).

Community
  • 1
  • 1
Trent
  • 335
  • 2
  • 8
0

If you prevent the default event the hash wont be attached to the url. If you use the scrollTop "hack" the user might experience a glitch. Try using the history API:

history.pushState(null, null, '#myhash');

if(history.pushState) {
    history.pushState(null, null, '#myhash');
}
else {
    location.hash = '#myhash';
}

I got this from: http://lea.verou.me/2011/05/change-url-hash-without-page-jump/

L.H
  • 325
  • 1
  • 7