Aaron
Aaron

Reputation: 1976

Running specific JavaScript/jQuery functions on certain pages

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?

Upvotes: 0

Views: 151

Answers (3)

Michael Zaporozhets
Michael Zaporozhets

Reputation: 24526

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;
    }​

Upvotes: 0

kikuchiyo
kikuchiyo

Reputation: 3421

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.

Upvotes: 0

Blender
Blender

Reputation: 298176

Give the body element a class or an id:

<body class="cool-page">

Then use jQuery:

if ($('body').hasClass('cool-page')) {
  ...
}

Upvotes: 1

Related Questions