Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the name of the HTML document that called a JS function

I'm a beginner with JS. I am working with some JavaScript on a site, and I just want to use only 1 file of JS for determine the actions off the pages. Something like this:

function registerEvents(){
     NameOfHTMLDocument = //?? Get the name of the document that called registerEvents function.
  switch(NameOfHTMLDocument)
  {
    case:"homepage":
          hmp_btn = document.getElementById("hmp_btn");
          hmp_btn.onclick=otherFunction;
          break;
    case:"otherPage":
          elem = document.getElementById("elemID");
          elem.onclick=fooFunction;
          break;
     //etc...
 }
}

This function is called with a <body onload="registerEvents()"> that is "inherited" by all the pages.

The question is, How can I get the "NameOfHTMLDocument"?. Because I don't want that JS begin doing weird things when trying to get elements that don't exist.

I found that I can get the URL of the DOM and then play a little with it to get the string that i want, but i'm not sure if this is the better way of doing it.

It Would be nice if you have a better suggestion.

like image 496
ElHacker Avatar asked Dec 18 '25 13:12

ElHacker


1 Answers

Firstly I would really suggest that you create separate script tags in html documents for functionality that is used only on that page and common functionality in separate file for several reasons:

  • No code pollution
  • Ease of change
  • Smaller download

Secondly, you can use switch on window.location.pathname DOM variable which is everything after domain instead of homepage, etc..

i.e.

url = vader.samplesite.com/light/saber/

window.location.pathname = /light/saber/

(look at http://www.developertutorials.com/questions/question/q-242.php )

like image 169
zveljkovic Avatar answered Dec 21 '25 03:12

zveljkovic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!