PDA

View Full Version : A script to return the page name



wkenny
09-16-2005, 02:17 AM
I'd have thought this was eays but cannot find a current document.name property which would return say "index.htm".

I have a js generated nav bar which is included on all pages and I want to highlight and remove the anchor for the Home option when the Home page is the one being viewed.

I could parse window.location.href but is there an 'easier' property to use.

jscheuer1
09-16-2005, 02:24 AM
Not that I know of but, parsing is hardly required, a simple index query will do:

if (location.href.indexOf('index.html')!==-1){
stuff to do if it is index.html goes here
}

wkenny
09-16-2005, 02:46 AM
Thanks, John.

I would term Using 'indexof ' as parsing in that the string has to be examined.

It does seem a bit odd that js does not have a built-in function to return page name.

Billy

wkenny
09-16-2005, 02:51 AM
Just one other question on this.

If I assign var path = window.location.href in a script on the page, do I have to reassign if I have a second script which also needs to get the path? If so, do I need to use a different name for the var.

Thanks

jscheuer1
09-16-2005, 03:13 AM
To the first point, parsing means teasing out a string into its component parts. I guess we are half way there with indexOf(). All it does (in this case) is see if the substring is contained in the main string.

To your question, if the variable is set outside of a function (or declared as a global variable within a function), it becomes a global variable for the page, and thus available to all scripts that follow it logically* on the page. If there is any doubt, it is best to test it by temporarily placing an alert at the spot in your code where you want the variable to be available and see what it returns:

alert(path)
*NOTE: Just because code appears after other code on a page doesn't always mean that it executes after the preceding code.

wkenny
09-16-2005, 03:21 AM
Thanks again, John

mwinter
09-18-2005, 01:20 PM
It does seem a bit odd that js does not have a built-in function to return page name.It's not the responsibility of the scripting language to provide this sort of feature, but the object model in which it operates. However, given that it's so easy to obtain the value, there really isn't any point for browser vendors to provide it.


function getFileName() {
var url = document.URL,
i = url.lastIndexOf('/') + 1,
j = url.indexOf('#', i),
k = url.indexOf('?', i);

if(-1 == j) {j = url.length;}
if(-1 == k) {k = url.length;}

return url.substring(i, Math.min(j, k));
}Note that this will return an empty string when the document was obtained in response to a path-only URL. That is, a URL like

  http://www.example.com/

will return an empty string. The browser has no idea what file is used when returning the HTTP response - that's entirely down to the server and is dependent upon its configuration.

Mike