I am trying to link anchors inside jquery tabbed content. I have gotten it to work, however, now when I click on tabs the page jumps to the top of the tab-content div, and cuts off tabs. I would like it to stay in the same spot without scrolling when tabs are clicked. I also need to access each tab and inside anchor from a URL, just need the tab URL to not jump to top of tab-content div, cutting off tabs on top. example: http://mysite.com/test#tab1
Here is what I have so far:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
$('a.refresh').live("click", function() {
location.reload();
});
});
</script>
<section class="wrap">
<div class="tablist">
<ul class="tabs">
<li><a href="#tab1">Tab 1</a></li>
<li><a href="#tab2">Tab 2</a></li>
<li><a href="#tab3">Tab 3</a></li>
</ul>
</div>
<div class="panes">
<div id="tab1" class="tab-content">
Tab 1 content
<br />
<a name="anchor1" id="anchor1">Anchor 1</a>
</div>
<div id="tab2" class="tab-content">
Tab 2 content
</div>
<div id="tab3" class="tab-content">
Tab 3 content
<br />
<a name="anchor2" id="anchor2">Anchor 2</a>
</div>
</div>
</section>
<script type="text/javascript">
$(document).ready(function() {
var $tabContent = $(".tab-content"),
$tabs = $("ul.tabs li"),
tabId;
$tabContent.hide();
$("ul.tabs li:first").addClass("current").show();
$tabContent.first().show();
$tabs.click(function() {
var $this = $(this);
$tabs.removeClass("current");
$this.addClass("current");
$tabContent.hide();
var activeTab = $this.find("a").attr("href");
$(activeTab).fadeIn();
});
// Grab the ID of the .tab-content that the hash is referring to
tabId = $(window.location.hash).closest('.tab-content').attr('id');
// Find the anchor element to "click", and click it
$tabs.find('a[href=#' + tabId + ']').click();
})
$('a').not('.tabs li a').on('click', function(evt) {
evt.preventDefault();
var whereTo = $(this).attr('goto');
$tabs = $("ul.tabs li");
$tabs.find('a[href=#' + whereTo + ']').trigger('click');
$('html, body').animate({
scrollTop: $('#'+whereTo+' a').offset().top });
});
</script>
Any thoughts, ideas, or help would be much appreciated!!
Thanks!
You need to add this to the event to stop its default behavior
preventDefault();
So for any anchor tag that you need to stop its behavior
$('#yourselector').click(function(e){
e.preventDefault();
});