tags:

views:

48

answers:

2

I have this in the head of my document:

<script type="text/javascript">

            var myString= location.href;
            var mySplit = myString.split("#");
            var x = mySplit[1];

            if (x == 'page1_div1') {
                document.getElementById('div1').className = 'theNewClass';
            }
</script>

What is my error? Thanks, Linda

+3  A: 

If you have that code in the head of your document as you say, the problem is that document.getElementById is not able to find your "div1" element, because when it is executed, the body of your document hasn't been evaluated, try to use the window.onload event:

window.onload = function () {
  var x = location.hash.substring(1);

  if (x == 'page1_div1') {
    document.getElementById('div1').className = 'theNewClass';
  }
};

Note that I also simplified your code a little bit, you wanted to extract the hash part of the current url.

CMS
Perfect. Thank you very much especially for the explanation for why it was not finding div1.
Linda
A: 

You can get the hash more easily through location.hash and since you will likely have several divs, it's easier to switch on them. Example:

<script type="text/javascript">
  var myHash = location.hash || 'NO-HASH';

  switch (myHash) {
    case 'NO-HASH':
      // Original page - no hash.
      document.getElementById('div1').className = 'theOldClass';
      document.getElementById('div2').className = 'theOldClass';
      break;
    case '#page1_div1':
      document.getElementById('div1').className = 'theNewClass';
      document.getElementById('div2').className = 'theOldClass';
      break;
    case '#page1_div2':
      document.getElementById('div1').className = 'theOldClass';
      document.getElementById('div2').className = 'theNewClass';
      break;
  }
</script>

However, if this is related to your history tracking question, you'll want to run this code in a polling timer.

Max Shawabkeh
>if this is related to your history tracking question, you'll want to run this code in a polling timer.It is a similar problem but not the same. The first question was between div's on the same page. This question was about navigation between different pages. On the link to the first page, I am putting a hash that does not resolve on the linked page just to have some tracking between pages. Max, how to I go about hiring you to solve my javascript problems :-)
Linda