Javascript concat() not working as it should be - javascript

<!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);

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

Timer doesn't start running

I tried to make a normal Timer in Javascript and started coding something with help of some Tutorials.
I did it the same way as in the tutorial but my timer actually doesn't start running, and i don't know why.
Here is my Code:
var time = 0;
var running = 0;
function startPause() {
if(running == 0){
running = 1;
increment();
}
else{
running = 0;
}
}
function reset(){
running = 0;
time = 0;
document.getElementById("startPause").innerHTML = "Start";
}
function increment() {
if(running == 1){
setTimeout(function(){
time++;
var mins = Math.floor(time / 10 / 60);
var secs = Math.floor(time / 10);
var tenths = time % 10;
document.getElementById("output").innerHTML = mins + ":" + secs + ":" + tenths;
}, 100);
}
}
</script>
i also made a fiddle you can check out here: https://jsfiddle.net/adamswebspace/5p1qgsz9/
what is wrong with my code?
I cleared a bit your code, and used setInterval instead of setTimeOut;
note that you have to use clearInterval in order to stop the timer
var time = 0;
var running = 0;
var timer = null;
function increment() {
time++;
var mins = Math.floor(time / 10 / 60);
var secs = Math.floor(time / 10);
var tenths = time % 10;
document.getElementById("output").innerHTML = mins + ":" + secs + ":" + tenths;
}
function startPause() {
if (running === 0) {
running = 1;
timer = setInterval(increment, 1000);
} else {
running = 0;
clearInterval(timer);
}
}
function reset() {
running = 0;
time = 0;
document.getElementById("startPause").innerHTML = "Start";
}
you have to bind the function like the following
var vm = this;
vm.startPause = function startPause() {
if (running == 0) {
running = 1;
vm.increment();
} else {
running = 0;
}
}
https://jsfiddle.net/f7hmbox7/
In order for onclick to find the function in your code. It must be supplied in a <script> tag for JSFiddle.
You can just add
<script>
/** JS Here */
</script>
and it will work.
Keep in mind that all the errors coming from JS are showed in the console of your browser inspector.
https://jsfiddle.net/dzskncpw/

JavaScript function working in IE not in chrome

I am facing problem while enabling & disabling the div block in web page. I need to display dvMessage block in non-working hours and dvChat in working hours.
For this I have written a code CheckTime as follows:
function CheckTime() {
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()
var time = hours + ":" + minutes
var isweekend = currentTime.getDay();
if ((time >= "20:00" && time <= "8:00")) {
document.getElementById("dvMessage").style.display = "block";
document.getElementById("dvChat").style.display = "none";
}
else {
document.getElementById("dvMessage").style.display = "none";
document.getElementById("dvChat").style.display = "block";
//End
}
}
Calling this function at body onload="CheckTime(); div id="dvChat" and div id="dvMessage" style="display: none;" class="message"
But this function works in IE but not in chrome. Is there anything else I need to do for Crome?
Thanks in advance.
Thanks, It works after currentTime is defined and adding missing Semicolons.
function CheckTime() {
var currentTime = new Date();
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();
var time = hours + ":" + minutes;
var isweekend = currentTime.getDay();
if ((time >= "20:00" && time <= "9:00")) {
document.getElementById("dvMessage").style.display = "block";
document.getElementById("dvChat").style.display = "none";
}
else {
document.getElementById("dvMessage").style.display = "none";
document.getElementById("dvChat").style.display = "block";
//End
}
}

Countdown timer javascript mins into hours

I'm a beginner in JavaScript, I wrote a countdown timer, but I don't know how to convert the mins into hours. I think its not to hard, but I can't do it, whenever I wrote new rows its not working. Here is my code:
var minutesRemaining;
var secondsRemaining;
var intervalHandle;
function resetPage() {
document.getElementById('inputArea').style.display = 'block';
//hide pause button by default
document.getElementById("pauseArea").style.display = "none";
//hide resume button
document.getElementById("resumeArea").style.display = "none";
}
function resumeCountdown() {
tick();
intervalHandle = setInterval(tick, 1000);
//hide resume button when resuming
document.getElementById("resumeArea").style.display = "none";
//show resume button;
document.getElementById("pauseArea").style.display = "block";
return;
}
function pauseCountdown() {
clearInterval(intervalHandle);
document.getElementById("pauseArea").style.display = "none";
document.getElementById("resumeArea").style.display = "block";
return;
}
function tick() {
//grab h1
var timeDisplay = document.getElementById('time');
//turn seconds into mm:55
var min = Math.floor(secondsRemaining / 60);
var sec = secondsRemaining - (min * 60);
//add leading 0 if seconds less than 10
if (sec < 10) {
sec = '0' + sec;
}
//concatenate with colon
var message = min.toString() + ':' + sec;
// now change the display
timeDisplay.innerHTML = message;
//stop if down to zero
if (secondsRemaining === 0) {
alert('Done!');
clearInterval(intervalHandle);
resetPage();
}
// subtract from seconds remaining
secondsRemaining--;
}
function startCountdown() {
//get contents
var minutes = document.getElementById('minutes').value;
//check if not a number
if (isNaN(minutes)) {
alert("Please enter a number!");
return;
}
//how many seconds?
secondsRemaining = minutes * 60;
//call tick
intervalHandle = setInterval(tick, 1000);
//hide form
document.getElementById('inputArea').style.display = 'none';
//show pause when running
document.getElementById("pauseArea").style.display = "block";
}
window.onload = function () {
// create text input
var inputMinutes = document.createElement('input');
inputMinutes.setAttribute('id', 'minutes');
inputMinutes.setAttribute('type', 'text');
inputMinutes.setAttribute('placeholder', 'Idő megadása');
//pause button
var pauseButton = document.getElementById("pauseBtn");
pauseButton.onclick = function() {
pauseCountdown();
};
//resume button
var resumeButton = document.getElementById("resumeBtn");
resumeButton.onclick = function() {
resumeCountdown();
};
//create button
var startButton = document.createElement('input');
startButton.setAttribute('type', 'button');
startButton.setAttribute('value', 'Indítás');
startButton.onclick = function () {
startCountdown();
};
// add to DOM
document.getElementById('inputArea').appendChild(inputMinutes);
document.getElementById('inputArea').appendChild(startButton);
document.getElementById("pauseArea").appendChild(pauseButton);
document.getElementById("resumeArea").appendChild(resumeButton);
//hide pause button by default
document.getElementById("pauseArea").style.display = "none";
//hide pause button by default
document.getElementById("resumeArea").style.display = "none";
};
Here is what i just wrote really quick. It may help you. But you can just do some basic math to get your conversions and handle the remainder. Like so:
function countDown(future_date_in_millis) {
var date = new Date();
var current_time = date.getTime();
//get the future date and time
var future_date = future_date_in_millis.getTime(); //1438077258047; //date.getTime();
// get the duration in milliseconds
// 1 day = 86400000 millis
var duration = future_date - current_time;
var dd = Math.floor(duration / 86400000);
var remainder = duration % 86400000;
var hh = Math.floor(remainder / 3600000);
remainder = remainder % 3600000;
var mm = Math.floor(remainder / 60000);
remainder = remainder % 60000;
var ss = Math.floor(remainder / 1000);
var days = document.getElementById("dd");
var hours = document.getElementById("hh");
var minutes = document.getElementById("mm");
var seconds = document.getElementById("ss");
days.innerHTML = dd.toString();
hours.innerHTML = hh.toString();
minutes.innerHTML = mm.toString();
seconds.innerHTML = ss.toString();
}
window.setInterval(function () {
/// call your function here
var d = new Date("July 15, 2015 4:52:00 PM");
countDown(d);
}, 1000);

Forcing page refresh at a specific time with timezone

I'm trying to force a page to refresh with js at a specific time, after digging around I found the script below. However, it doesn't appear to take into consideration timezones. How would I implement that?
<html>
<head>
<title></title>
<script type="text/javascript">
function refreshAt(hours, minutes, seconds) {
var now = new Date();
var then = new Date();
if(now.getHours() > hours ||
(now.getHours() == hours && now.getMinutes() > minutes) ||
now.getHours() == hours && now.getMinutes() == minutes && now.getSeconds() >= seconds) {
then.setDate(now.getDate() + 1);
}
then.setHours(hours);
then.setMinutes(minutes);
then.setSeconds(seconds);
var timeout = (then.getTime() - now.getTime());
setTimeout(function() { window.location.reload(true); }, timeout);
}
refreshAt(15,06,0); //Will refresh the page at 3:06pm
</script>
</head>
<body onLoad="setInterval('getCurrentTime()', 1000);">
<div id="time"></div>
content
</body>
</html>
Here you go, reload will occur for every user exactly as you define in global vars in script:
EDIT!!! I had bug in code so I have updated the script...
EDIT working example:
http://simplestudio.rs/yard/tinediffredir/content.html
<html>
<head>
<title>Chk diff and reload if match</title>
<script>
var reload_time = "15060"; // this is 15:06:00 - change to desired reload time
var reload_hour_diff = 15; // for cheking diff - change to desired hours
var reload_minute_diff = 6; // for cheking diff - change to desired minutes
var time_zone_offset = "-5"; // globally looking from GMT time, change this according to DST
var reload_time_checker = setInterval(function(){reload_page()},300);
var diff = null;
function chk_reload_moment(offset) {
dat = new Date();
utc = dat.getTime() + (dat.getTimezoneOffset() * 60000);
default_date = new Date(utc + (3600000*offset));
var default_year = default_date.getFullYear();
var default_month = default_date.getMonth();
var default_day = default_date.getDate();
var default_hour = default_date.getHours();
var default_minutes = default_date.getMinutes();
var default_seconds = default_date.getSeconds();
user_date = new Date();
var user_year = user_date.getFullYear();
var user_month = user_date.getMonth();
var user_day = user_date.getDate();
var user_hour = user_date.getHours();
var user_minutes = user_date.getMinutes();
var user_seconds = user_date.getSeconds();
user_current = user_hour+""+user_minutes+""+user_seconds;
default_current_f = default_day+"/"+default_month+"/"+default_year+" "+default_hour+":"+default_minutes+":"+default_seconds;
user_current_f = user_day+"/"+user_month+"/"+user_year+" "+user_hour+":"+user_minutes+":"+user_seconds;
var timeEnd = new Date(user_current_f);
var timeEndH = timeEnd.getHours();
var timeEndM = timeEnd.getMinutes();
var new_reload_minute_diff = 60+reload_minute_diff;
diff = (timeEndH - reload_hour_diff + 12) + " hours " + (new_reload_minute_diff - timeEndM) + " minutes";
if (user_current == reload_time) {
return true;
}
else {
return false;
}
}
function reload_page() {
var chktime = chk_reload_moment(time_zone_offset);
if (chktime) {
window.location.reload();
}
else {
var timer_div = document.getElementById('timer');
timer_div.innerHTML = "remaining: " + diff + " until new content";
}
}
</script>
</head>
<body>
<div id="timer">
</div>
</body>
</html>
I think it is clear how to configure it but if you have some problems feel free to ask...

Categories