Home › Forums › JavaScript › Linking to Specific tab with hash and class="current"
- This topic is empty.
-
AuthorPosts
-
April 1, 2015 at 1:51 am #199393tbeParticipant
Hello, i have an address like: http://mysite.com/page.htm#tab-supplier.
it links to specific tab in page.htm with hash. tab should take class=”current” for hash and if nothing hash found, first tab is activated. my code: http://codepen.io/anon/pen/KwYgZg
April 1, 2015 at 2:23 am #199394Ilan FirsovParticipantI have used something like that on a website I’m working on:
function showHashTargetTab() { //// tab switch function. this is Bootstrap $('#myTab a[href="'+window.location.hash+'"]').tab('show'); $('.package .sub-menu li').removeClass('active open'); $('.package .sub-menu a[href*="'+window.location.hash+'"]').parent('li').addClass('active open'); } $(document).on('click', '#myTab a[data-toggle="tab"]', function (e) { e.preventDefault(); window.location.hash = $(this)[0].hash; //// tab switch function. this is Bootstrap again $(this).tab('show'); }); // this happens on load, we check if the hash exists and if it is show the specific tab, otherwise show default tab if(window.location.hash) { showHashTargetTab(); } else { //// tab switch function. this is Bootstrap again $('#myTab a[data-toggle="tab"]:first').tab('show'); } // we need to know when we change the hash to show the specific tab $(window).on('hashchange', function(e) { e.preventDefault(); showHashTargetTab(); });
I’m sure it can be cleaned up a bit, but it works fine as it is.
I use Bootstrap here, but it should be easily changed to another tab switching logicEdit cleaned up a bit and added comments.
April 1, 2015 at 3:20 am #199395Ilan FirsovParticipantNow that I think about it, it is more complicated than you need since I’m updating the active link on the sidebar as well. Here the code a bit simplified without the bit that updates the sidebar
$(document).on('click', '#myTab a[data-toggle="tab"]', function (e) { e.preventDefault(); window.location.hash = $(this)[0].hash; //// tab switch function. this is Bootstrap again $(this).tab('show'); }); // this happens on load, we check if the hash exists and if it is show the specific tab, otherwise show default tab if(window.location.hash) { //// tab switch function. this is Bootstrap $('#myTab a[href="'+window.location.hash+'"]').tab('show'); } else { //// tab switch function. this is Bootstrap again $('#myTab a[data-toggle="tab"]:first').tab('show'); } // we need to know when we change the hash to show the specific tab $(window).on('hashchange', function(e) { e.preventDefault(); showHashTargetTab(); });
April 3, 2015 at 10:55 pm #199723tbeParticipantHi Ilan Firsov,thanks for reply but it has no sense with code ?!
April 6, 2015 at 3:56 am #199820tbeParticipantHi,is there any conflict with my code vs yours?
-
AuthorPosts
- The forum ‘JavaScript’ is closed to new topics and replies.