tags:

views:

152

answers:

5

I want to display a certain message on a certain page.

Suppose the name of the page I want to display something on is called "foo_page.html",

How can I do this using javascript?

+1  A: 

The following will show an alert box if the url is something like http://example.com/foo_page.html :

if(location.pathname=="/foo_page.html") alert('hey!');
zaf
+1  A: 
var index = document.location.lastIndexOf("/");
var filename = document.location.substr(index);

if(filename.indexOf("foo_page.html")>-1){
   alert("OK");
}
Gregoire
+1  A: 

You can do it like this:

if(document.URL.indexOf("foo_page.html") >= 0){ 
...show your message
}
fat_tony
Probably want `>= 0` there.
Syntactic
Good spot, thanks. Edited.
fat_tony
A: 

You can use document.location to figure out what URL the visitor is at.

Try this:

<script type="text/javascript">
var currentPage = document.location.href.substring(document.location.href.lastIndexOf("/")+1, document.location.href.length);
</script>

Your "currentPage" variable should now contain the name of the page you're on. You can use that to select an action.

EAMann
A: 
var loc = window.location.pathname.split("/"),
    size = loc.length

    alert(loc[size])

gives you the last part splitted by "/" most of the time the html, php or whatever file. But i would use classes on your body to recognize where you are. Or just check if the element you want to do something with exists on the page. Before you execute your function like this

  function example(element) {
      if(getElementById(element).length) {
          // now you are sure that a element exists on the page
      }else{
         return false; //if not just do nothing
      }
  }
  example("myId")
meo
`loc[size-1]`, or just: `var filename= location.pathname.split('/').pop();`. (And why `.length` on the element node?)
bobince
what is pop() doing exactly? length to get the last piece of the array. Thx for the tipp
meo