Trouble with setting greeting note with JS on HTML - javascript

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>

Related

display diffrent images depending on time

So I have a sort of homepage with some code to change the background based on the time. My problem is: it only checks the time when the page first loads, I need it to be constantly checking for it. Here is my code, please help.
var today2 = new Date();
var h2 = today2.getHours();
if (h2 > 18) {
document.body.style.backgroundImage = "url('cityatnight2.jpg')";
}
else if (h2 < 9) {
document.body.style.backgroundImage = "url('sunrise2.jpg')";
}
else {
document.body.style.backgroundImage = "url('homescreen3.jpg')";
}
I would suggest using the setInterval command. It allows you to specify that code run at a given interval. For example, to run every hour, you could do this:
function SetBackground()
{
var today2 = new Date();
var h2 = today2.getHours();
if (h2 > 18) {
document.body.style.backgroundImage = "url('cityatnight2.jpg')";
}
else if (h2 < 9) {
document.body.style.backgroundImage = "url('sunrise2.jpg')";
}
else {
document.body.style.backgroundImage = "url('homescreen3.jpg')";
}
}
// 1 Hour Interval
window.setInterval(SetBackground, 60 * 60 * 1000);
Read more about that function here: https://www.w3schools.com/jsref/met_win_setinterval.asp
Try this code.
var changeBg = function(num){
if (num > 18) {
document.body.style.backgroundColor = "red";
}
else if (num < 9) {
document.body.style.backgroundColor = "blue";
}
else {
document.body.style.backgroundColor = "black";
}
}
setInterval(function(){
var today2 = new Date();
var h2 = today2.getSeconds(); //edit here. sec -> hour.
console.log(h2)
changeBg(h2);
},1000) //and edit here. 1000 means 1sec

How can I modify a variable on another site?

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.

Can't get form to hide in JS

Having this problem with trying to get a form to hide in Javascript.
Here is my HTML:
<!DOCTYPE html>
<html>
<head>
<title>Timer</title>
<link rel="stylesheet" href="style.css">
<script src="javascript.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<link href='https://fonts.googleapis.com/css?family=Roboto:400,300' rel='stylesheet' type='text/css'>
</head>
<body>
<div id="wrapper">
<div id="time">00:00:00</div>
<form id="myform">
<input type="text" autocomplete="off" id="box" placeholder="00:00:00" onkeypress="checkBox(event)">
</form>
</div>
</body>
</html>
And here is my JS:
function timer(time) {
document.getElementById("myform").style.display = "none";
document.getElementById("time").style.display = "inline";
var interval = setInterval(function () {
if (time == 0) {
time = 299;
} else {
var newTime = timeFormat(time);
document.getElementById("time").innerHTML = newTime;
document.title = newTime;
time--;
}
}, 1000);
}
function checkBox(event) {
if (event.keyCode == 13) {
var string = document.getElementById("box").value;
var numTest = string;
if (string.length != 0) {
var numOfColons = string.split(":").length - 1;
var hr = 0;
var min = 0;
var sec = 0;
if (numOfColons == 2) {
numTest = numTest.replace(":", "");
numTest = numTest.replace(":", "");
hr = string.substring(0, string.indexOf(":"));
string = string.replace(string.substring(0, string.indexOf(":")+1), "");
min = string.substring(0, string.indexOf(":"));
string = string.replace(string.substring(0, string.indexOf(":")+1), "");
sec = string.substring(0, string.length);
} else if (numOfColons == 1) {
numTest = numTest.replace(":", "");
min = string.substring(0, string.indexOf(":"));
string = string.replace(string.substring(0, string.indexOf(":")+1), "");
sec = string.substring(0, string.length);
} else if (numOfColons == 0) {
sec = string;
}
hr = parseInt(hr);
min = parseInt(min);
sec = parseInt(sec);
if(/^\d+$/.test(numTest)) {
var totalSec = hr*3600 + min*60 + sec;
if (totalSec > 0) {
timer(totalSec);
}
}
}
}
}
function focus() {
document.getElementById("box").focus();
}
function timeFormat(time) {
var sec = time % 60;
var totalMin = time / 60;
var min = Math.floor(totalMin % 60);
var string = "";
if (min == 0 && sec < 10) {
string = "0:0" + sec;
} else if (min == 0) {
string = "0:" + sec;
} else if (sec < 10) {
string = min + ":0" + sec;
} else {
string = min + ":" + sec;
}
return string;
}
Note that I am not using a button to trigger the form submission, I am simply using a onkeypress event to detect if the user hit the enter button (I wanted a cleaner design). Whenever the timer function is called, the text box flickers like it turns off for a second, than it comes back on in an instant. I have no idea what the problem is. I also have gotten no errors in console.
Am not sure what you are trying to achieve but from looking at your code, Hitting enter results in the page being reloaded, so I can't get to see the result.
I would however suggest you use jQuery to hide show your results, since you are already calling the script
$('#myform').hide();
$('#time').show();
The problem is this line of code. It turns the form off for a split second, which causes the blinking effect to occur. Simply remove this or comment it out.
document.getElementById("myform").style.display = "none";
If you want to hide the form, use jQuery's $('#myForm').hide() function. It's similar to <form id="myform" style="display:none;">
You could also try this:
<input type="text" id="timeInputBox" autocomplete="off" id="box" placeholder="00:00:00" onkeypress="checkBox(event)">
With this:
document.getElementById('timeInputBox').style.display = "none"; // JS
Or use this:
$('#timeInputBox').hide(); // jQuery
You may also want to move the jQuery <script> tag up higher in your <head> block. It needs to go before your call to your external <script src="javascript.js"></script> tag. Then you can use the $ and all of these functions from api.jquery.com in your .js file.

Javascript concat() not working as it should be

<!DOCTYPE html>
<html>
<script>
function myFunction() {
var objDate = new Date();
var hours = objDate.getHours();
var mins = objDate.getMinutes();
var time = hours.concat(mins);
window.alert(time);
if (time>=1600&&time<=0900) {
document.body.style.background ="url('closed.png') no-repeat";
} else if (time>=1230&&time<=1315) {
document.body.style.background ="url('lunch.png') no-repeat";
} else {
document.body.style.background ="url('open.png') no-repeat";
}
}
setInterval(myFunction, 3000);
</script>
</html>
At line 8
"var time = hours.concat(mins);"
I get "Uncaught TypeError: undefined is not a function" and it refuses to continue. All I want to do is specify if its between a certain time then we are open, closed or at lunch. Schedule never really changes so it doesn't need to be more advanced than that.
concat() is for joining two arrays. You just want to join two strings. Try
var time = hours.toString() + mins.toString();
getHours() returns a number so it doesn't have a concat method, so your script should throw an error saying Uncaught TypeError: undefined is not a function
function myFunction() {
var objDate = new Date();
var hours = objDate.getHours()+'';
var mins = objDate.getMinutes();
var time = hours.concat(mins); //or hours + ':' + mins
window.alert(time);
}
setInterval(myFunction, 3000);
But for your calculation related to background style, it will be better to use time in minutes
function myFunction() {
var objDate = new Date();
var hours = objDate.getHours();
var mins = objDate.getMinutes();
var time = hours * 60 + mins;
if (time >= 960 || time <= 540) {
document.body.style.background = "url('closed.png') no-repeat";
} else if (time >= 750 && time <= 795) {
document.body.style.background = "url('lunch.png') no-repeat";
} else {
document.body.style.background = "url('open.png') no-repeat";
}
}
setInterval(myFunction, 3000);

JavaScript functions not loading

I'm trying to run a function at pageload:
<script type="text/javascript" src="functions.js"></script>
<body onload="startUp();">
The problem is startUp() isn't running, nor is anything else that I try to refer to in my JS file. I am certain that the link to the JS file is correct; and even if it weren't, I even tried pasting all of functions.js right into the page header--still nothing. This is the content of functions.js:
function startUp() {
document.write("running"); //for debugging
alert("running"); //for debugging
stretchAbdomen();
if (defaultStyle()) {
setStyleCookie(1, false);
}
else { //if mobilestyle
setStyleCookie(0, false);
if (!window.location.hash) {
window.location.hash = "#mobilearea";
}
}
}
function stretchAbdomen() {
var bodyheight = getbodyheight();
var abdomen = document.getElementById('abdomen');
if (window.innerHeight > bodyheight) {
var currentpaddingstring = window.getComputedStyle(abdomen, null).getPropertyValue('padding-bottom');
var currentpadding = Number(currentpaddingstring.substring(0, currentpaddingstring.length - 2)); //-2 removes "px" from string
abdomen.style.paddingBottom = (((window.innerHeight - bodyheight) + currentpadding) + "px";
}
}
function getbodyheight() {
var body = document.body,
html = document.documentElement;
return Math.min( body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight);
}
/*** BELOW HERE SHOULD NOT BE RELEVANT FOR THE QUESTION ***/
window.onresize = resetStyleCookie;
function defaultStyle() {
if (window.getComputedStyle(document.getElementById('mobilearea')).getPropertyValue('width') == "1px")
return true;
else return false;
}
function resetStyleCookie() {
document.cookie = "stylecookie=" + "; expires=Thu, 01 Jan 1970 00:00:01 GMT;";
setStyleCookie(defaultStyle() ? 1 : 0, true); //forcereset because otherwise it wasn't working on subpages
}
function setStyleCookie(number, forcereset) {
if (document.cookie.indexOf("stylecookie") == -1 || forcereset) {
var now = new Date();
var time = now.getTime();
time += 3600 * 150000;
now.setTime(time);
document.cookie = "stylecookie=" + number + "; expires=" + now.toGMTString() + "; path=/";
}
}
I have to assume that there's some compile-time problem in functions.js, but my debugging tools show no errors, nor can I find anything myself. The call to startUp() simply does nothing, even when I don't rely on the onload event to call it. Thanks for any insight!
You have an error in your JS code. Try using JSLint.com to validate your code.
if (window.innerHeight > bodyheight) {
var currentpaddingstring = window.getComputedStyle(abdomen, null).getPropertyValue('padding-bottom');
var currentpadding = Number(currentpaddingstring.substring(0, currentpaddingstring.length - 2)); //-2 removes "px" from string
abdomen.style.paddingBottom = (((window.innerHeight - bodyheight) + currentpadding) + "px";
}
You are missing the last ) on abdomen.style.padding.bottom.
Error: Expected ')' to match '(' from line 22 and instead saw ';'.
<html>
<head>
<script type="text/javascript">
function startUp() {
document.write("running"); //for debugging
alert("running"); //for debugging
//stretchAbdomen();
if (defaultStyle()) {
setStyleCookie(1, false);
}
else { //if mobilestyle
setStyleCookie(0, false);
if (!window.location.hash) {
window.location.hash = "#mobilearea";
}
}
}
</script>
</head>
<body onload="startUp();">
</body>
</html>
The above code works for me. As you can see, I've taken only the function you are trying to reference and have put it in script tags -- but it works. It seems to me that the problem occurs when you try to reference the stretchAbdomen function.
You need to reference the function, f.e.
<body onload="startUp">
Make sure to reference it after it was defined (as you did in your example with the external JavaScript).

Categories