0

I don't know how to phrase my question, so here's more of an explanation... Problem I need to solve: Only display this script on pages A, B and C. They are wordpress pages so I can't just paste the script into each page. I wrote this script:

if(window.location.href.indexOf("url-string-a") > -1){
    jQuery( "form" ).addClass( "active" );
}

but I don't know how to apply it to more than one URL without copy and pasting this 3 times. (In my actual scenario, this script needs to run on 10 pages, so I don't want to copy and paste this 10 times. I'm sure there's a cleaner way of doing this.)

Thanks!

1 Answer 1

2

When you think about copy-paste, instead think about functions that should wrap the code you were going to repeat again and again. One possible approach:

function containsAny(haystack, needles) {
  return needles.some(function(str) {
    return haystack.indexOf(str) > -1;
  });
}

Here you created a function that takes two arguments: haystack (a string) and needles (an array of strings), the former will be checked for any of the latter.

Then just use this function inside if check:

if (containsAny(location.href, ['url-string-a', 'url-string-b', ...])) {
  $('form').addClass('pnt');
}
Sign up to request clarification or add additional context in comments.

5 Comments

I'm getting an error "Uncaught ReferenceError: containsAny is not defined"
I think the use of some is a key part of this solution that many would not already be familiar with.
@nthChild - Have you defined the function in that script?
@nthChild Where's the function declaration placed? It should be in scope of the code using it.
Ok I got it mostly working except it says "Uncaught TypeError: $ is not a function" for the line where the .addClass occurs

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.