0

I am having a hard time getting any jquery code to work. I've tried some examples and none work for me. Here is an example that sort of works in chrome from the C drive, but not from dropbox on the web, nor does it work at all in ie9.

When it is 'sort of' working on chrome from my C drive, it starts out displaying all the tabs instead of just Tab A as it is supposed to. Then after clicking one of the links it only shows the corresponding tab.

My end goal is to modify my website so that the whole page doesn't flash while reloading every time I click on a menu item.

<!--  found at: http://jsfiddle.net/uFgtS/ -->

<script type='text/javascript' src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type='text/javascript'>

$(window).on('hashchange', function() {
    $('div.tab').hide();
    $(location.hash).show();
});

$('a.hash').on('click', function(e){
    e.preventDefault();
    location.hash = $(this).data('hash');
});
</script>

<a href="#A" data-hash="A" class="hash">A Link</a>
<a href="#B" data-hash="B" class="hash">B Link</a>
<a href="#C" data-hash="C" class="hash">C Link</a>

<div id="A" class="tab">Tab A</div>
<div id="B" class="tab hidden">Tab B</div>
<div id="C" class="tab hidden">Tab C</div>
John
  • 336
  • 1
  • 4
  • 15
  • Seems working for me http://jsfiddle.net/GM6Qk/ – palaѕн May 09 '13 at 18:21
  • I think you need to use: `if ("onhashchange" in window) { //... }` See here: http://stackoverflow.com/questions/3090478/jquery-hash-change-event – Carol Skelly May 09 '13 at 18:25
  • I added the suggested doc ready line. I guess I don't understand exactly what I should do next. I really do not understand how the code is working, I am just trying to see what I can do with this example I did not write. The goal is that when the page is initially loaded, it should not show Tab A Tab B Tab C, it should only show Tab A. Then if you click on a link it changes which one is displayed. – John May 09 '13 at 18:40

2 Answers2

2

You forgot :

$(document).ready(function() {

    // your code goes here

});

so when attaching the click handler to a.hash, there's no such element in the DOM.

adeneo
  • 312,895
  • 29
  • 395
  • 388
1

If you place your jQuery before the elements that it affects you need to wrap it in

$(document).ready(function() {
    // Code to be run once the document is ready
}

Alternatively, place your scripts at the very end of the document body to make $(document).ready() redundant.

David Barker
  • 14,484
  • 3
  • 48
  • 77