Reputation: 383
I have this code in my JS file. If i remove the the if else loops then i can get the hello as alert otherwise not.
Neither i am getting any error in firebug console
Basically in those loops i am just checking if the url contains few keywords so that ican chnage the css to selected
$(document).ready(function(){
var userPage = /child\/(.+)/.exec(location.href)[1];
if( userPage.indexOf('show') != -1 )
{$('.profile').addClass('selected');}
if( userPage.indexOf('workbook') != -1 )
{
$('.selected').removeClass('selected');
$('.workbook').addClass('selected');
}
if( userPage.indexOf('gallery') != -1 )
{
$('.selected').removeClass('selected');
$('.gallery').addClass('selected');
}
if( userPage.indexOf('mylist') != -1 )
{
$('.selected').removeClass('selected');
$('.mylist').addClass('selected');
}
if( userPage.indexOf('Photos') != -1 )
{
$('.selected').removeClass('selected');
$('.photos').addClass('selected');
}
if( userPage.indexOf('profile/list') != -1 )
{
$('.selected').removeClass('selected');
$('.list').addClass('selected');
}
alert("hillo");
Upvotes: 0
Views: 112
Reputation: 309
It returns null in the first line of your code.
var userPage = /child/(.+)/.exec(location.href)[1];
and you must get this error ": Cannot read property 'indexOf' of null"
its better to check first whether the url has child or not then proceed.
Upvotes: 0
Reputation: 318342
The way you've set it up the alert is not inside any if statement, so it should alert no matter what. If there is no alert you're script has errors, and I spot at least two :
You're assuming the url contains the string child/
, if it does not your script will halt and not work, next you're assuming the output of that exec()
is an array with at least two values, selecting the second value of that array, and if for some reason your url does not contain child/
there will be no second value in that array, and the script halts, but then again it already halted in the exec()
.
The second error is that the document.ready
function is'nt closed, thats probably just a typo.
On the other hand you should figure out a way to do this more dynamically. You're using the same class as the url string you are checking for, so for most of the cases you could just use it directly in the selector, cutting your function down to just a few lines, something like:
$(document).ready(function() {
var url = 'http://somesite.com/child/gallery'; //just a test url
var userPage = url.indexOf('child/') != -1 ? /child\/(.+)/.exec(url)[1] : null;
if (userPage) {
console.log('has child in url');
$('.selected').removeClass('selected');
$('.'+userPage).addClass('selected');
}else{
console.log('not ok');
}
});
Upvotes: 2