views:

51

answers:

4

Hello All,

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...?

A: 
var pathOfIndexPage = "index.aspx";

if (window.location.pathname == "/"+pathOfIndexPage || window.location.pathname == "/")
{
  //do stuff
}
SinistraD
Won't work if the user visits `/` instead of explicitly visiting `/index.aspx`, pointless (and inefficient) use of string concatenation, use of assignment (`=`) instead of equality (which should, generally, be strict) (`===`).
David Dorward
at the time I beautified my code, someone posted the same answer xD
SinistraD
This looked like something I could use... except 'every' root aspx page in every unique directory is called index.aspx... ugh.
chrisb
don't worry, window.location.pathname contains the whole path, so using "/myDir/index.aspx" and "/myDir/" will do the trick. Everything except the domain name is there.
SinistraD
A: 

You shouldn't, but you could probably do something like this:

if(window.location.pathname == "{home page}")
{
  //run home page jquery.
}

BUT... my advise would be to create a content section on the home page that gets placed into the HEAD and put the jQuery into there instead of the masterpage. No reason to include it in the masterpage if it's not used everywhere...

Abe Miessler
+5  A: 
Marko
+1, yes this would be the least krufty way to do this.
Abe Miessler
+1 Most any other way of doing this would smell of the equivalent of requiring a parent class to know about its sub classes.
Jim Leonardo
I am in dialog with the backend devs on implementing this solution.
chrisb
A: 

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
}
Marko
I'm going to try this.
chrisb
@chrisb I feel bad now for providing this (ugly) alternative - why can't you do use the code above? It's a much better solution.
Marko
lol. I can't say I've ever posted 2 answers, one of which got 5 upvotes and the other got accepted.
Marko
I'm just the frontend java guy... and don't have access to the Master Pages... I just need a 'dirt' fix until those guys get back in tomorrow... ;-)
chrisb