0

Would it be wiser to check if a particular element exists on the page?

if ($('#cool-page').length > 0) {
    // my jQuery function
}

Or check if the window location is the correct page?

if (window.location.href.indexOf('words-here') != -1) {
    // my jQuery function
}

In this situation, I only want to run my jQuery function on pages: site.com/123/words-here

If the best way is the latter, how should I be writing up a regexp to match the location above?

3 Answers 3

1

Give the body element a class or an id:

<body class="cool-page">

Then use jQuery:

if ($('body').hasClass('cool-page')) {
  ...
}
Sign up to request clarification or add additional context in comments.

Comments

0

Because you only want it to run on a particular page, window.location.href seems like a safer bet and more indicative of your purpose for running the method. Just my opinion.

Comments

0

I would give each pages body a specific id such as

<body id="cool-page">

and using jquery/javascript I would use a switch to wrap the specific functions

var pageid = $('body').attr('id');
switch(pageid)​ {
    case 'cool-page':
        //dosomething
        break;
        default:
        //dosomething
        break;
    }​

Comments

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.