DropTheChair DropTheChair - 5 months ago 18
HTML Question

Time Based Links in HTML\JavaScript

I'm working on game right now that will have an Item Shop. I thought it would be fun that you couldn't just walk in at an untimely hour.

I made, with a bit of help, this random script (I'm not really sure if this will help) that will let you enter the shop 90% percent of the time. :

<script language="JavaScript">
var result = (Math.random()*10)
var a = document.createElement('a');

if(result >= 9)
{
var linkText = document.createTextNode("Enter The Shop");
a.id = "OpenShop";
a.appendChild(linkText);
a.title = "A place to buy weapons and stuff!";
a.href = "open.html";
document.body.appendChild(a);
}
else
{
var linkText = document.createTextNode("Don't Enter The Shop");
a.id = "ClosedShop";
a.appendChild(linkText);
a.title = "A place to buy weapons and stuff!";
a.href = "notopen.html";
}
document.body.appendChild(a);




I was wondering if it would be possible to change a few lines and make it to where the shop could be open from 9 a.m.-8 p.m. but to be closed for the rest of the day.

(Before 9 a.m. and after 8 p.m. the shop needs to be closed.)

EDIT:
I am also unsure how to center this.

Answer

Use the new Date() method. This creates a date like this: Sun Jun 26 2016 22:29:49 GMT+0200 (CEST); (Just like in the snippet below.) Then you need to create an if statement. I would suggest the substring method so you can focus on the hours only.

var currentdate = new Date();
var substringdate = currentdate.toString().substring(16,18);
document.getElementById("date").innerHTML = substringdate;

if (substringdate > 07 && substringdate < 19) {
  document.getElementById("openedshop").style.opacity = "1";
  } else {
    document.getElementById("closedshop").style.opacity = "1";
    }

//use.toString because you can't use substring on numbers.
//I just used random conditions in the if statement, you can fill it in.
a {
  opacity: 0;
  }
<p id="date"></p>
<a href="#"id="openedshop">The shop</a> 
<a href="#"id="closedshop">The shop</a>

In this case, if the hour isn't equal to 22 then the shop is open. You can change this of course. Hope this helped!

Comments