JavaScript function working in IE not in chrome - javascript

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
}
}

Related

onclick fires with no issues but addEventListener requires multiple clicks to work

I've tried this a few different ways. I'm attempting to create an event for a button that toggles an elements visibility on and off. for some reason when I use .onclick it works fine. Each time I click the button it toggles the element visibility as expected. However when I attempt to swap .onClick for addEventListener the button has to be clicked multiple times for it to work. It seems intermittent. It may work on the 1st click one time and then the next time it may require 2 or 3.
function showTime() {
options = {weekday: 'short', year: 'numeric', month: 'short', day: '2-digit'}
var date = new Date();
var hr = date.getHours();
var min = date.getMinutes();
var sec = date.getSeconds();
var period = "am";
if(hr == 0){
hr = 12;
}
if(hr > 12){
hr = hr - 12;
period = "pm";
}
min = (min < 10) ? "0" + min : min;
sec = (sec < 10) ? "0" + sec : sec;
var time = hr + ":" + min + ":" + sec + " " + period;
document.getElementById("displayTime").innerHTML = time;
document.getElementById("displayDate").innerHTML = date.toLocaleDateString("en-US", options);
var startTime = setTimeout(showTime, 1000);
//Set Alarm
var set = document.getElementById("setButton");
set.onclick = function(){
var timeVis = document.getElementById("displayTime");
if (timeVis.style.display !== 'none') {
timeVis.style.display = 'none';
} else {
timeVis.style.display = 'block';
}
}
}
showTime();
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset="utf-8"/>
<title> Clock </title>
</head>
<body>
<div id="displayTime" onLoad="showTime()" ></div>
<input type="text" id="setInput">
<button id="setButton">set</button>
<div id="displayDate"></div>
<script src="DigitalClock.js"></script>
</body>
</html>
Below are the two alternate ways I attempted to use add an event listener
var set = document.getElementById("setButton");
set.addEventListener('click', function(){
var timeVis = document.getElementById("displayTime");
if (timeVis.style.display !== 'none') {
timeVis.style.display = 'none';
} else {
timeVis.style.display = 'block';
}
});
var set = document.getElementById("setButton");
var timeVis = document.getElementById("displayTime");
function vis(){
if (timeVis.style.display !== 'none') {
timeVis.style.display = 'none';
} else {
timeVis.style.display = 'block';
}
};
timeVis.addEventListener('click', vis);
The problem is that you use addEventListener inside the showTime() function, so each time showTime() is executed, you bind a new listener.
Now because of this:
var startTime = setTimeout(showTime, 1000);
The function is executed each second. As a result, after a couple of seconds, when you click one time on the button, the toggle part is executed multiple times.
On the other hand, with set.onclick, you only redefine the onclick property of the element, this is why it's working as expected.

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

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

Javascript Function activates before button is clicked

If requirements are met when you click the button it will display a count down timer. Problem is it displays the countdown timer BEFORE you even click the button. I'm not sure what I'm overlooking.
<input id="upgrade" type="button" value="Upgrade" onclick="timer();" />
<br><br><br><br>
<p id="countdown_timer"></p>
<script>
function display_timer(){
document.getElementById("countdown_timer").innerHTML = "<span id='countdown' class='timer'></span>";
}
</script>
<script>
var currently_upgrading = 0;
var current_ore = 398;
var current_crystal = 398;
var upgradeTime = 172801;
var seconds = upgradeTime;
function timer() {
if(currently_upgrading == 1){alert('You are already upgrading a module.');return;}
if(current_ore <= 299){alert('You need more ore.');return;}
if(current_crystal <= 299){alert('You need more crystal.');return;}
display_timer();
var days = Math.floor(seconds/24/60/60);
var hoursLeft = Math.floor((seconds) - (days*86400));
var hours = Math.floor(hoursLeft/3600);
var minutesLeft = Math.floor((hoursLeft) - (hours*3600));
var minutes = Math.floor(minutesLeft/60);
var remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('countdown').innerHTML = days + ":" + hours + ":" + minutes + ":" + remainingSeconds;
if (seconds == 0) {
clearInterval(countdownTimer);
document.getElementById('countdown').innerHTML = "Completed";
} else {
seconds--;
}
}
var countdownTimer = setInterval('timer()', 1000);
</script>
You need to move countdownTimer variable into your timer() function.
Try changing the last lines of timer() to be like this:
if (seconds == 0) {
document.getElementById('countdown').innerHTML = "Completed";
} else {
seconds--;
setTimeout(timer, 1000);
}
and remove the setInterval line.
Speaking generally, setTimeout is much preferred to setInterval, because it doesn't require a managed state (countdownTimer in your example) and is far more flexible.
Also note that passing a string as in setTimeout('timer()', 1000) is obsolete, just pass a function: setTimeout(timer, ...).
This line
var countdownTimer = setInterval('timer()', 1000);
will execute 1 second after the page loads as well as on the button click and this calls the display_timer function.
you have called it in setInterval function, so it will starts immediately , because setInterval function runs after page loads and not on click and setInterval uses your function

Javascript Onclick event only works once

This javascript calls up a timer that countdowns if certain variables are met. While the countdown is happening it hides the original button and replaces it with another button so that the event can't be called again during the countdown. However, after the countdown ends nothing happens when you click the button again.
<div id="set_upgrade">
<input id="upgrade" type="button" value="Upgrade" />
</div>
<div id="set_upgrading" style="display:none">
<input id="upgrading" type="button" value="Upgrade" />
</div>
<br><br><br><br>
<p id="countdown_timer"></p>
<script>
document.getElementById("countdown_timer").innerHTML = ("<span id='countdown' class='timer' style='display:block'></span>");
document.getElementById('upgrade').onclick=timer;
document.getElementById('upgrading').onclick=alert_box;
function display_timer(){
};
function alert_box(){
alert("You are currently upgrading this module.");
};
var currently_upgrading = 0;
var current_ore = 398;
var current_crystal = 398;
var upgradeTime = 3;
var seconds = upgradeTime;
var su = document.getElementById('set_upgrade');
var su2 = document.getElementById('set_upgrading');
var su3 = document.getElementById('countdown');
function timer() {
if(currently_upgrading == 1){alert('You are already upgrading a module.');return;}
if(current_ore <= 299){alert('You need more ore.');return;}
if(current_crystal <= 299){alert('You need more crystal.');return;}
su.style.display = "none";
su2.style.display = "block";
su3.style.display = "block";
var days = Math.floor(seconds/24/60/60);
var hoursLeft = Math.floor((seconds) - (days*86400));
var hours = Math.floor(hoursLeft/3600);
var minutesLeft = Math.floor((hoursLeft) - (hours*3600));
var minutes = Math.floor(minutesLeft/60);
var remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('countdown').innerHTML = days + ":" + hours + ":" + minutes + ":" + remainingSeconds;
if (seconds == 0) {
su.style.display = "block";
su2.style.display = "none";
su3.style.display = "none";
} else {
seconds--;
setTimeout(timer, 1000);
}
}
</script>
First of all you don't need to open and close the <script> tag every time you need to do something, then instead of doing onclick="alert_box();", try it this way.
function alert_box(){
alert("You are currently upgrading this module.");
};
document.getElementById('upgrading').onclick=alert_box;

Categories