JS/JQuery - If Date is (future date), run this HTML/JS
New here? Learn about Bountify and follow @bountify to get notified of new bounties! x

I need a few pieces of code to run on a page during a specific day in the future, but won't have access to the web on that day to upload the changes myself. So, how can I do this programmatically in JS/JQuery?

Eg. Only if the date is January 31st, 2014, print out this piece of HTML code <li></li> or <div></div>, and this section of <script></script> in the head section.

Crowdsource coding tasks.

2 Solutions


This should do it:

var now = new Date()
var then = new Date('2014 Jan 31')
var script_to_include = "https://your-script333"
var id_to_replace_content_of = "answers-main"

if(now < then){
  // include javascript
  // from http://stackoverflow.com/questions/21294/dynamically-load-a-javascript-file-think-of-include-in-c
  var s = document.createElement("script");
  s.setAttribute("type", "text/javascript");
  s.setAttribute("src", script_to_include);
  var head = document.getElementsByTagName("head")[0];
  head.appendChild(s);

  // replace content by element ID
  document.getElementById(id_to_replace_content_of).innerHTML="<ul><li>Hello world 1</li><li>Hello world 2</li></ul>";
}
Whoops - I misread and thought you wanted something to happen only before/after January 31. Could be changed to do block of code only on Jan 31 too, of course
skram over 5 years ago

<head>
<script type="text/javascript">
var today = new Date();
var checkDate = new Date();
var dateOk = false;
checkDate.setFullYear(2014,0,31); //January 31st, 2014
if (today.getFullYear() == checkDate.getFullYear() && today.getMonth() == checkDate.getMonth() && today.getDate() == checkDate.getDate()){
//Do Something
alert('today is January 31st, 2014');
dateOk = true;
}
</script>
</head>
<body>
<script type="text/javascript">
if(dateOk){
document.write('<li></li> <div></div>');
}
</script>
</body>


This solution use document.write to write html in page, a better solution is to build html with dom, but it depends on what you need to do.

View Timeline