I have written a very simple countdown timer in JavaScript that I have hardcoded to tell a user the number of days left until a certain date. This is then supposed to be shown on a web page.
Here is the JavaScript:
var message, days;
if (new Date().getMonth() === 6) {
days = 34 - new Date().getDate();
message = "Coming in " + days + " days";
} else if (new Date().getMonth() === 7) {
if (new Date().getDate() > 2) {
message = "Almost there!";
} else if (new Date().getDate() === 2) {
message = "Coming in 1 day";
} else {
days = 3 - new Date().getDate();
message = "Coming in " + days + " days";
}
} else {
message = "Coming soon";
}
document.getElementById("coming_soon").innerHTML = message;
And here is the HTML:
<span id="coming_soon"></span>
The problem is that if I inline the JavaScript, it runs perfectly and the countdown is shown. If, however, I include it as a separate .js file, the countdown is not shown.
How can I include this as a separate file and still have it run and show the countdown?
I am a complete beginner to JavaScript, and somewhere between intermediate and beginner in HTML.
Thanks in advance.
Are there any messages in the browser's error console? Make sure that the script is included after the <span> element that you are trying to modify, or use the defer attribute on the <script> element. Otherwise, getElementById() will not find it.
This should do it:
Without jQuery and also for older IE's
var eventPrefix = "";
if (typeof window.addEventListener === "undefined" && window.attachEvent) {
eventPrefix = "on";
window.addEventListener = window.attachEvent;
}
if (typeof window.addEventListener !== "undefined") {
window.addEventListener(eventPrefix + 'load', function() {
var message, days;
if (new Date().getMonth() === 6) {
days = 34 - new Date().getDate();
message = "Coming in " + days + " days";
} else if (new Date().getMonth() === 7) {
if (new Date().getDate() > 2) {
message = "Almost there!";
} else if (new Date().getDate() === 2) {
message = "Coming in 1 day";
} else {
days = 3 - new Date().getDate();
message = "Coming in " + days + " days";
}
} else {
message = "Coming soon";
}
document.getElementById("coming_soon").innerHTML = message;
});
}
Preview: http://jsfiddle.net/4JPCP/1/show/
Optimized code: http://jsfiddle.net/4JPCP/3/
Edit:
IIFE are redundant in this case, since OP's code it's not self contained in a function.
However, I could leave the answer here if anyone wants to dive deeper into the argument.
You may also wants to explore what are commonly called Immediately-Invoked Function Expression (IIFE).
See Bel Alman website for more information:
http://benalman.com/news/2010/11/immediately-invoked-function-expression/
Basically, by wrapping your code with this syntax, you're telling the browser to immediately execute your function, and this do the trick:
(function(){
/* your code */
})();
See this working Plunker with your code: http://plnkr.co/edit/cPObPCqVhavvWLtQbldd?p=preview
Related
My son is doing times tables practice on this page, a timed test in which he gets 10 seconds for each sum.
https://www.timestables.com/speed-test/ - this is not my site or code, I have no direct control over the source code.
I want to give him a little more time per sum but I cannot find a way to modify the relevant code and make it work with 20 seconds instead of 10.
It looks to me like the relevant variable is maxTime (milliseconds) in this function, but nothing I do using the Chrome Developer Tools will modify this in a live running page to give 20 seconds instead of 10.
function startSom(){
vraagnr = vraagnr + 1;
if(vraagnr <= totaalSommen)
{
bezig = true;
$('#pbar_innerdiv').stop();
$('#pbar_innerdiv').css("width","100%");
$('#pbar_innerdiv').css("backgroundColor","#33BF00");
$('#pbar_innerdiv').css("borderColor","#33BF00");
if(mobiel){
$("#antwVak").html("");
}
else{
$("#antwoordI").val("");
$("#antwoordI").focus();
}
$('#pbar_innerdiv').stop();
start = new Date();
maxTime = 10000;
timeoutVal = Math.floor(maxTime/100);
var somT = sommen[vraagnr-1].split(",");
$('#somVak').html(somT[1]+"×"+somT[0]+"=");
$('#voortgangVak').html("Question "+vraagnr+" / "+totaalSommen+"<br />"+ punten + " points");
animateUpdate();
started = false;
}
else
{
showEindScherm();
}
}
Can anyone suggest what to do please?
You can copy the entire method, pase it into chrome devtools and change
function startSom() {
to
window.startSom = function() {
And obviously change your time from 10000 to 20000. This changes the amount of time it allows you to answer, but not the moving progress bar which will still only take 10 seconds.
Please paste this:
window.startSom = function(){
vraagnr = vraagnr + 1;
if(vraagnr <= totaalSommen)
{
bezig = true;
$('#pbar_innerdiv').stop();
$('#pbar_innerdiv').css("width","100%");
$('#pbar_innerdiv').css("backgroundColor","#33BF00");
$('#pbar_innerdiv').css("borderColor","#33BF00");
if(mobiel){
$("#antwVak").html("");
}
else{
$("#antwoordI").val("");
$("#antwoordI").focus();
}
$('#pbar_innerdiv').stop();
start = new Date();
maxTime = 20000;
timeoutVal = Math.floor(maxTime/100);
var somT = sommen[vraagnr-1].split(",");
$('#somVak').html(somT[1]+"×"+somT[0]+"=");
$('#voortgangVak').html("Question "+vraagnr+" / "+totaalSommen+"<br />"+ punten + " points");
animateUpdate();
started = false;
}
else
{
showEindScherm();
}
}
Here:
And if you want to make the progress bar following the new max Time, also paste this:
window.animateUpdate = function() {
if(bezig)
{
var now = new Date();
var timeDiff = now.getTime() - start.getTime();
if(!started){
$('#pbar_innerdiv').css("width", (100) + "%");
$('#pbar_innerdiv').animate({width: 0 + "%"},20000);
started = true;
}
perc = Math.round((timeDiff/maxTime)*100);
console.log(perc);
if(perc == 33)
{
$('#pbar_innerdiv').css("backgroundColor", "#FF9500");
$('#pbar_innerdiv').css("borderColor", "#FF9500");
}
if(perc== 66)
{
$('#pbar_innerdiv').css("backgroundColor", "#FF0000");
$('#pbar_innerdiv').css("borderColor", "#FF0000");
}
if (perc <= 100) {
//updateProgress(perc);
setTimeout(animateUpdate, timeoutVal);
}
else
{
bezig = false;
showTeLaat();
//alert("tijd is om");
}
}
}
There is a possibility to change files persistently in chrome devtools: Overrides.
If the script is in a seperate file you can change the maxTime directly there or if it is in a file, which needs to be reloaded you can edit any other .js and add an eventlistener there to change the startSom method on page load.
I'm having trouble running a JS code from separate stylesheet on HTML page. Basically, I want to set an adequate greeting messages depending on the current hour of the day. I've searched and there are many ways to do it, but I am trying to get it work in this way and I didn't find a solution to this problem.
window.onload = getGreeting();
function getGreeting() {
var time = new Date();
var curHours = time.getHours();
if (curHours < 10) {
document.getElementById("greeting").innerHTML = "Dobro jutro!";
} if else (curHours < 20) {
document.getElementById("greeting").innerHTML = "Dobar dan!";
} if else {
document.getElementById("greeting").innerHTML = "Dobro vece!";
}
};
<!DOCTYPE html>
<head>
<script type="text/javascript" src="LakaRukaDent.js"></script>
</head>
<body>
<p id="greeting"></p>
</body>
When I run the HTML in Chrome the greeting doesn't appear. When I press f12 in Chrome it comes up with "Uncaught SyntaxError: Unexpected token <", but I can't figure out why it doesn't work. I've checked syntax and functionality searching through the web but considering that I'm new with JS and HTML perhaps it could be some basic thing that I've skipped and I am not aware of.
Use else if instead of if else.
Example from MDN:
if (x > 5) {
} else if (x > 50) {
} else {
}
Please find the fix below. window.onload expects a function reference not returned value of a function, that is why i remove parenthesis over there. Also there was syntax error with if else statement.
window.onload = getGreeting;
function getGreeting() {
var time = new Date();
var curHours = time.getHours();
if (curHours < 10) {
document.getElementById("greeting").innerHTML = "Dobro jutro!";
} else if (curHours < 20) {
document.getElementById("greeting").innerHTML = "Dobar dan!";
} else {
document.getElementById("greeting").innerHTML = "Dobro vece!";
}
};
<h1 id="greeting"></h1>
First off, remove the parentheses from getGreeting when assigning to onload, as onload accepts a function. Also, you have syntax errors with your if statements. It should be else if not if else like so:
window.onload = getGreeting;
function getGreeting() {
var time = new Date();
var curHours = time.getHours();
if (curHours < 10) {
document.getElementById("greeting").innerHTML = "Dobro jutro!";
} else if (curHours < 20) {
document.getElementById("greeting").innerHTML = "Dobro dan!";
} else {
document.getElementById("greeting").innerHTML = "Dobro vece!";
}
}
<p id="greeting"></p>
I've found similar code elsewhere on this site but can't get it to work for my situation.
I'm trying to delay showing a div (8 second delay in this case) to NEW visitors but if cookie is set then show the div immediately to RETURNING visitors.
Currently, it seems that the first part works--showing the div to new visitors after 8 seconds--and my code sets the cookie but the second part--showing the div immediately to returning visitors--doesn't work at all and, in fact, NEVER seems to show the div content.
I've tried everything I can think to move around but no luck.
Here's the relevant code (including cookie code) all placed in the HEAD section:
<script type="text/javascript">
function createCookie(name, value, days) {
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
var expires = "; expires=" + date.toGMTString();
} else var expires = "";
document.cookie = name + "=" + value + expires + "; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
}
return null;
}
</script>
<script type="text/javascript">
function showbox() {
document.getElementById("show-this").style.visibility = "visible";
}
if (!readCookie('visitedPreviously')) { //if he/she is a new user
setTimeout("showbox()", 8000); // after 8 secs createCookie('visitedPreviously', 'visitedPreviously', 3); // 365 days persistence
}
</script>
<div id="show-this" style="visibility: hidden"><div class="center-this"><img src="mysource" alt="some text" /></div>
</div>
I've tried moving the "function showbox" to the BODY, tried if/else statements inside that function, moving code to a .js files, using css, and more but now I just need some help as I obviously don't know what I'm doing.
Thank you for your time.
if (!readCookie('visitedPreviously')) { //if he/she is a new user
setTimeout("showbox()", 8000); // after 8 secs
createCookie('visitedPreviously', 'visitedPreviously', 3); // 365 days persistence
} else {
showbox();
}
you just forgot the else :)
I have 2 buttons on the pop-up window (Ok and Cancel) using javascript message pop-up window in below code.
But i need only one button option (ok) using jquery or javascript message pop-up because i am not getting concept to disable cancel button using javascript.
Jquery message pop-up should work perfectly according to my below code.
I am working on time out session notification for a masterpage in ASP.NET and below is my javascript pop-up message code:
var active = confirm('Your session will expire in ' + (sess_expirationMinutes - sess_warningMinutes) +
' minutes (as of ' + now.toTimeString() + '), press OK to remain logged in ' +
'or press Cancel to log off. \nIf you are logged off any changes will be lost.');
Javascript code:
<script type="text/javascript">
var sess_pollInterval = 60000;
var sess_expirationMinutes = 3;
var sess_warningMinutes = 1;
var sess_intervalID;
var sess_lastActivity;
function initSession()
{
sess_lastActivity = new Date();
sessSetInterval();
$(document).bind('keypress.session', function (ed, e) {
sessKeyPressed(ed, e);
});
}
function sessSetInterval()
{
sess_intervalID = setInterval('sessInterval()', sess_pollInterval);
}
function sessClearInterval()
{
clearInterval(sess_intervalID);
}
function sessKeyPressed(ed, e)
{
sess_lastActivity = new Date();
}
function sessLogOut()
{
window.location.href = 'Logout.aspx';
}
function sessInterval()
{
var now = new Date();
//get milliseconds of differneces
var diff = now - sess_lastActivity;
//get minutes between differences
var diffMins = (diff / 1000 / 60);
if (diffMins >= sess_warningMinutes)
{
//wran before expiring
//stop the timer
sessClearInterval();
//promt for attention
var active = confirm('Your session will expire in ' + (sess_expirationMinutes - sess_warningMinutes) +
' minutes (as of ' + now.toTimeString() + '), press OK to remain logged in ' +
'or press Cancel to log off. \nIf you are logged off any changes will be lost.');
if (active == true)
{
now = new Date();
diff = now - sess_lastActivity;
diffMins = (diff / 1000 / 60);
if (diffMins > sess_expirationMinutes)
{
sessLogOut();
}
else
{
initSession();
sessSetInterval();
sess_lastActivity = new Date();
}
}
else
{
sessLogOut();
}
}
}
</script>
HTML code:
<body onload="initSession()" >
<form id="form1" runat="server">
<div>
</div>
</form>
</body>
Replace confirm with alert. The confirm has both Ok and Cancel. alert has only Ok.
You can use some JQuery from here :
http://www.freshdesignweb.com/jquery-javascript-popup-window.html
Fiddle
I am making a social network and when you post something, I want to show the time. I have the current code to display the time (this isn't only the time, it's also validating and posting the text):
$('#b').click(function () {
var v = $('#type').val();
var u = $('#input').val();
if (v !== "" && u !== ""){
var time = new Date();
var currentime = Date.now();
var x = currentime - time;
$("ul").prepend("<li>" + v + "<br />Posted by " + u + " " + x +" minutes ago </li>");
$('#type, #input').css('border','');
}
else if (v == "" && u == "") {
$('#type, #input').css('border','1px solid red');
}
else if (v == "") {
$('#type').css('border','1px solid red');
$('#input').css('border','');
}
else {
$('#input').css('border','1px solid red');
$('#type').css('border','');
}
});
When the time posts, it says 0 minutes ago (like I told it to), but after any amount of time, it still says 0.
fiddle
Basically you set up a setInterval which governs ho frequently you update your time attribute. I used a span with a class .time to so you could theoretically update anything with time.
I would go further and hash your posts so you can easily retrieve each posts original time.
EDIT: added a new fiddle.