How to run jquery script if html page is the home page...?

chrisb picture chrisb · Sep 15, 2010 · Viewed 23.6k times · Source

I'm working with an external team with our website and they recently added one of my scripts to the .NET MasterPage of the site... well it did finally get my script running but now... it loads Banners on 'every' page on the site.

How can I write an 'if' statement that basically says... if this is the home page... run this script... if not don't...?

Answer

Marko picture Marko · Sep 15, 2010

I'm posting another answer in case you can't implement the Master Page solution.

You could use a flag element to tell jQuery it's the homepage, because the URL solutions posted earlier can easily break.

Somewhere in your Homepage content, simply place this.

<span id="homepage-flag" style="display: none" />

And then using jQuery, check if the element exists and run your code. It's a pretty poor solution but it will work if you can't get my other answer to work.

if($("#homepage-flag").length > 0) {
    // run code for homepage
}