14

Is there any way to detect what page you are on in JavaScript?

Why I want to know is so that i can detect what page i am on, and then set the style of an element accordingly.

Stephen Docy
  • 4,738
  • 7
  • 18
  • 31
Callum
  • 932
  • 2
  • 8
  • 12
  • var fullPath = window.location.pathname; var whatPage = fullPath.split("/").pop(); – Musa Oct 20 '16 at 20:52
  • 1
    If your on your own site, then location.pathname is probably easiest. if it only returns "/" then your at your home page. – riegersn Jan 13 '17 at 18:43

2 Answers2

12

document.URL will get you the URL of the current page.

To check for a specific page you would use:

if ( document.URL.includes("homepage.aspx") ) {
    //Code here
}
m.edmondson
  • 30,382
  • 27
  • 123
  • 206
  • Ah thankyou, one mroe question. How would i do it so that if it contains the name of the page, it will perform some action – Callum Apr 21 '13 at 16:40
  • Not sure what you mean, where is the name of the page? – m.edmondson Apr 21 '13 at 16:41
  • Oh sorry, say for example i have a page called homepage.aspx. How would i do it so that if the url contains homepage.aspx; it will then perform some action – Callum Apr 21 '13 at 16:43
  • 1
    if ( document.URL.contains("homepage.aspx") ) { – krs Apr 21 '13 at 16:44
  • So you would supply 'homepage.aspx' as the matching criteria? Can you modify your question above to ask for this additional requirement? – m.edmondson Apr 21 '13 at 16:44
  • No problem - if you wouldn't mind marking the question as the answer that would be great. – m.edmondson Apr 21 '13 at 16:49
  • And what if you hosting and you want to detect the home page but the page doesn't have a URL, e.g. the URL would be www.mywebsite.com, about would be www.mywebsite.com/about. So the homepage doesn't have a /. So how would you detect the home page then? – Franco Feb 22 '22 at 13:15
2

Get url of page are you on

location.href

Or

document.URL

Set style to element by id:

document.getElementById('mydiv').style.border = '1px solid black';
Roman Nazarkin
  • 2,209
  • 5
  • 23
  • 44