Reputation: 93
I'm rather new to Javascript and I can't seem to get a script to run/not run on certain pages.
I have this script on my main page to hide and unhide content:
$(document).ready(function() {
$(".hidden").hide();
$(".show").html("[+]");
$(".show").click(function() {
if (this.className.indexOf('clicked') != -1 ) {
$(this).prev().slideUp(0);
$(this).removeClass('clicked')
$(this).html("[+]");
}
else {
$(this).addClass('clicked')
$(this).prev().slideDown(0);
$(this).html("[–]");
}
});
});
I need some coding like this:
if url contains "/post/" then ignore script else run script
It should be a simple fix. I just can't get it to work. Any suggestions?
Upvotes: 1
Views: 3950
Reputation: 38
According to this answer,
window.location
is an object, not a string, and so it doesn't have anindexOf
function.
... So window.location.indexOf()
will never work.
However, as guided by the same answer, you could convert the URL to a string with window.location.href
to then perform searches. Or you could access parts of the URL, like this:
if (window.location.pathname === '/about/faculty/'){
... }
for an exact match
or
window.location.pathname.split( '/' )
to get parts of the url, as mentioned in this answer.
Upvotes: 1
Reputation: 253396
The if
you're looking for is:
if (window.location.indexOf('/post/') == -1){
// don't run, the '/post/' string wasn't found
}
else {
// run
}
indexOf()
returns -1
if the string wasn't found, else it returns the index in the string where the first character of the string is found.
The above rewritten with added common sense provided by Jason (in comments, below):
if (window.location.indexOf('/post/') > -1){
// run, the '/post/' string was found
}
Upvotes: 2