Reputation: 1582
I'm looking to try and check if the hash in the url contains a certain value before proceeding, I have a function that works like so:
$(window).load(function () {
var hash = window.location.hash,
number = $(hash).index(),
width = 403,
final = width * number;
setTimeout(function () {
$('.news-inner-wrap').animate({
'marginLeft': "-=" + final + "px"
});
}, 1000);
});
So if the hash is www.website.com/#news-item-03
it will slide the user horizontally along to the 3rd news story, this works great!. I only want this function to fire though if the hash contains news-item
obviously the number after each will change, but if the hash begins with news-item
then I want the function above to be fired, I'm not even sure it this is at all possible, any suggestions would be greatly appreciated!
Upvotes: 1
Views: 16860
Reputation: 11786
Use a regular expression:
var matches = hash.match(/^#news-item-([0-9]+)$/);
if (matches) {
var number = matches[1];
// Rest of your code
}
Upvotes: 3
Reputation: 3580
No need for jQuery, this should work nicely
if (window.location.hash) {
if (window.location.hash.indexOf('news-item') == 1) { // not 0 because # is first character of window.location.hash
// it's at the start
}
else if (window.location.hash.indexOf('news-item') != -1) {
// it's there, but not at the start
}
else {
// not there
}
}
Upvotes: 10