Jump to content

How to add condition for specific URL


airesofwar

Recommended Posts

I am trying to learn javascript and having a bit of a issue with this script I been practicing with. No matter what I do this will not display only on the homepage. Even if I add it into a <div class then add conditional tags followed with CSS to display none on all other pages it still ends up displaying on every page. So I figure I need to use some type of condition in the script to only show on selected URL. However as I said I am a noob with JavaScript.

<script type="text/javascript">function morning(){alert("Good Morning!");}function afternoon(){alert("Good Afternoon!");}function night(){alert("Good Night!");}</script><script type="text/javascript">var d = new Date();var time = d.getHours();if (time < 12){morning();}else if (time > 19){night();}else{afternoon();}</script>

Link to comment
Share on other sites

Why don't you only put the script on the home page? Or you can write everything into a function and just call that function on the home page.

Link to comment
Share on other sites

Why don't you only put the script on the home page? Or you can write everything into a function and just call that function on the home page.
That would be the easy route to take but the point of this for me is to learn more in how to use JavaScript. And I am sure at a later date it would come in handy to be able to have a script active on selected page even if the script it readable from all pages. Basically the script has no value to me and im not going to be using it other then something to train off of. So sure I could add it into a post or homepage and be done with it. But that would not give me anything to learn off and build onto. I know that might sound pointless but to me that is how I learn.
Link to comment
Share on other sites

You still include the script in all pages - you just only call the function that alerts the greeting on the page you want. E.g.script.js

function morning(){alert("Good Morning!");}function afternoon(){alert("Good Afternoon!");}function night(){alert("Good Night!");}function greet() {var d = new Date();var time = d.getHours();if (time < 12){morning();}else if (time > 19){night();}else{afternoon();}}

index.html

<html>	<head><title>Test</title><script type="text/javascript" src="script.js"></script>		<script type="text/javascript">			greet();		</script>	</head>	<body>	</body></html>

All other pages:

<html>	<head><title>Test</title><script type="text/javascript" src="script.js"></script></head>	<body>	</body></html>

Anyway, you can get the URL the client used to access the page using the window.location. Trying to detect the page this way is bad practice though - what if the page name changes, for example?

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...