Aaron Bangerter
Aaron Bangerter

Reputation: 87

First load of my page doesn't quite work

I am somewhat new to jQuery and javascript and just implemented a new code yesterday to handle some styling around my menu. When the homepage loads, it doesn't quite work right, although it is doing something. When I navigate away to another page and come back, it works fine. It's that first load that's giving me grief. Can anyone help me figure out what's wrong with my code?

Here's my code:

$(function(){ 
  var url = window.location.pathname,  
      urlRegExp = new RegExp(url.replace(/\/$/,'') + "$");
    $('.nav ul li a').each(function(){  
        if(urlRegExp.test(this.href.replace(/\/$/,''))){        
        $(this).attr('id', 'selected'); 
        } 
  });
    $(function() {
        if (url === "/index.html" || url === "/") {
        $('.nav').attr('id','homenav');
        }
  });
});

Upvotes: 0

Views: 201

Answers (2)

DannyTheDev
DannyTheDev

Reputation: 4173

if the problem is just that when its / which is the same page as /index.html why not make / /index.html before the check.. like so:

$(function(){ 
    var url = window.location.pathname;
    if(url == '/')
    {
        url = '/index.html'; 
    }
    var urlRegExp = new RegExp(url.replace(/\/$/,'') + "$");
    $('.nav ul li a').each(function(){  
        if(urlRegExp.test(this.href.replace(/\/$/,''))){        
            $(this).attr('id', 'selected'); 
        } 
    });

    $(function() {
        if (url === "/index.html") {
            $('.nav').attr('id','homenav');
        }
    });
});

Upvotes: 1

aorlando
aorlando

Reputation: 668

You must wrap your javascript inside theready function:

$(document).ready(function(){
   $(function(){ 
  var url = window.location.pathname,  
      urlRegExp = new RegExp(url.replace(/\/$/,'') + "$");
    $('.nav ul li a').each(function(){  
        if(urlRegExp.test(this.href.replace(/\/$/,''))){        
        $(this).attr('id', 'selected'); 
        } 
  });
    $(function() {
        if (url === "/index.html" || url === "/") {
        $('.nav').attr('id','homenav');
        }
  });
});
});

I think.

that's all folks

Upvotes: 0

Related Questions