I'm not able to make the right logic for a simple vanilla javascript alarm clock, that shows a message/plays a sound at the time which user had set... help me make the logic right.
Here's my javascript code:
<script>
function setAlarm(){
//taking value of time
var a=document.getElementById("H").value;
var b=a*3600000;//converted to millisecound
var c=document.getElementById("M").value;
var d=c*60000;//converted to millisecound
var e=d+b;//addition of millisecound
//live values of time
var f=h*3600000;//converted to millisecound
var g=m*60000;//converted to millisecound
var i=g+h;//addition of millisecound
var j=0;
if(i>=e){
j=i-e;
}else{
j=e-i;
}//else
document.getElementById("demo2").innerHTML=j;
setInterval(test,j);
if (d==g){
console.log("if called");
test();
}//if
}
function test(){
console.log("test called")
document.getElementById("demo2").innerHTML="its work";
}
var d=new Date();
var h=d.getHours();
document.getElementById("hours").innerHTML=h;
var m=d.getMinutes();
document.getElementById("minutes").innerHTML=m;
var s=d.getSeconds();
document.getElementById("secound").innerHTML=s;
setInterval(repeat,1000);
function repeat(){
var d=new Date();
var h=d.getHours();
document.getElementById("hours").innerHTML=h;
var m=d.getMinutes();
document.getElementById("minutes").innerHTML=m;
var s=d.getSeconds();
document.getElementById("secound").innerHTML=s;
}
var i=0;
function ChangeTheam(){
i++;
if(i%2){
document.body.style.backgroundColor= "black";
document.getElementById("hours").innerHTML.style.color = "blue";
}else{
document.body.style.backgroundColor= "white";
}//else
}//change theam function
</script>
I can provide HTML code if someone wants but don't think that'll be necessary since I'm not able to make the logic right at the first point.
Thanks :)
In your code
//live values of time
var f=h*3600000;//converted to millisecound
var g=m*60000;//converted to millisecound
var i=g+h;//addition of millisecound`
You added g+h instead of g+f as a result the time that your alarm takes to trigger may be significantly shorter.
var s=d.getSeconds();
document.getElementById("secound").innerHTML=s;
I am not sure if this is just what you id'd the element by I assume you meant 'second' not 'secound'
Otherwise, I see no problems with your code and should work fine.
Related
I have an application (HTML5, JavaScript, Jquery, jquery Mobile) with a slider.
The handle can be moved via touch and you can navigate through the years 1861 to 2000. There are symbols on my map which are visible/non visible depending on the year. See my example image.
I also want the handle to move, when the user clicks a specific button ("forward"). the handle should go through each year until the user clicks a different button.
I managed that with one click the handle goes + 1 year, and the handle, the year and the map update the changed year.
function moveLeft(){
var slider1 = $("#slider").val();
var $slider = $("#slider");
slider1++;
$slider.val(slider1).slider("refresh");
var wert1 = slider1;
var start = new Date().getTime(); //start =
hideLayer2(wert1, start);
$('#jahr').text(wert1);
var $ausgabe = $("#ausgabe");
$ausgabe.text(wert1);
gewaehltesJahr = wert1;
I built a for loop (for (i =slider1; i< 2000; i++)) for this function but the handle and everything will only update, if the function reached the year 2000. I want to see the update of every single year.
Even if I go through the code with a debugger, it will only update year, handle and map when it finished the loop und exited the function.
Following code for example:
If i start in 1861 und initialise the function the handle and map will jump directly into 1870 after the alert "alert("vor") in the last line.
function vor(){
var slider1 = $("#slider").val();
var $slider = $("#slider");
for( var s = slider1; s < 1870; s++){
//$slider.val(s).slider("refresh");
$("#slider").slider('value',s);
alert(s);
var wert1 = s;
var start = new Date().getTime(); //start = aktuelles Datum
hideLayer2(wert1, start);
$('#jahr').text(wert1);
var $ausgabe = $("#ausgabe");
$ausgabe.text(wert1);
gewaehltesJahr = wert1;
}
alert("vor");
}
The handle, when in focus can also be moved by pressing the arrowkeys.
$('.ui-slider-track .ui-btn.ui-slider-handle').focus();
I tried du imitate the pressing of one key to go a year forward but it isn't working either.I tried to set a trigger but it didn't work. Can anybody help?
var kEvent = document.createEvent('Event');
kEvent.initKeyEvent("keypress", true, true, null, false, false, false, false, 38, 0);
document.activeElement.dispatchEvent(kEvent);
For loop gets executed instantly, so you have to use javascript timers!
//Global flag to decide animation
//Make this false to clear the animation loop from anywhere
var animate_slider = false;
//Global timer for animation
var animation_timer;
//Call animation function
function vor(){
animate_slider = true;
animation_timer = setInterval(function(){
if(!animate_slider){
clearInterval(animation_timer);
}
else{
var slider1 = $("#slider").val();
var $slider = $("#slider");
$("#slider").slider('value',s);
var wert1 = s;
var start = new Date().getTime(); //start = aktuelles Datum
hideLayer2(wert1, start);
$('#jahr').text(wert1);
var $ausgabe = $("#ausgabe");
$ausgabe.text(wert1);
gewaehltesJahr = wert1;
if(slider1 == maxValue){
clearInterval(animation_timer);
}
}
},1000);
}
Note:
Triggering arrow keys is not necessary & pointless, cause it'll also result in instance execution of all clicks. So even there you have to use timers, thus you can bypass that & change you main method with timers.
Thanks so much, I edited it a little bit and now it works!
var animation_timer;
function vor(){
animate_slider = true;
animation_timer = setInterval(function(){
if(!animate_slider){
clearInterval(animation_timer);
}
else{
var slider1 = $("#slider").val();
var $slider = $("#slider");
// $("#slider").slider('value',slider1);
slider1++;
var wert1 = slider1;
$slider.val(slider1).slider("refresh");
var start = new Date().getTime(); //start = aktuelles Datum
hideLayer2(wert1, start);
$('#jahr').text(wert1);
var $ausgabe = $("#ausgabe");
$ausgabe.text(wert1);
gewaehltesJahr = wert1;
if(slider1 == 2000){
clearInterval(animation_timer);
}
}
},1000);
}
I'm having this div element that shows the time past since it got created. However it doesn't get updated and always remains on few seconds ago. It looks like this
var newMsg= "<div id="chat-time">'+ moment().fromNow()+'</div>";
$("#chat-list").html( newMsg);
How can I update this text. I know I can do it with sentInterval but I can't figure out how to do it properly.It just prints out seconds! I'm using this for a chatroom. So each message will have a timestamp in the formatof momentjs.fromNow().
Does setting timer for all these message create a problem? I'd appreciate a hint.
EDIT:I'm using this code as mentioned in below but it's not showing anything:
<div id="chat-time"></div>
var messageTimeStamp = new Date();
setInterval(function(){
var time = moment(messageTimeStamp).fromNow();
$("#chat-time").html(time);
}, 1000);
To make this work you need the element in the dom and the setInterval running without being included in any string concatenation
HTML
<div id="chat-time"></div>
JS
var $chatTime = $('#chat-time').text(moment().fromNow());
setInterval(function(){
var time = moment().fromNow();
$chatTime.txt( time );
}, 1000);
UPDATE 2
Given that you're using socket.io, you'd do something like this (demo: http://plnkr.co/edit/QuaMV6x1vNB0kYPaU6i1?p=preview):
// The messages the user can currently see.
var messages = [];
// You have something like this in your code, presumably.
socket.on('new message', function(data) {
addChatMessage(data);
});
function addChatMessage(data) {
// First add the message to the dome, with a unique id for the timestamp text.
var messageElementId = 'chat-message-' + data.messageId;
$("#chat-list").prepend($("<div>" + data.message + "<i> (sent: <span id='" + messageElementId + "'>just now</span>)</i></div>"));
// When you no longer display that message in the DOM it from clear this array. I'd render the DOM based on this list if I were you.
messages.push({
messageElementId: messageElementId,
timestamp: data.timestamp
});
}
// By updating all the messages at once you don't have memory leaks.
setInterval(function() {
messages.forEach(function(message) {
var time = moment(message.timestamp).fromNow();
$("#" + message.messageElementId).text(time);
});
}, 1000);
UPDATE 1
Given this is your code:
var newMsg= "<div id="chat-time">'+ moment().fromNow()+'</div>";
$("#chat-list").html(newMsg);
You would do this, instead:
var messageTimeStamp = new Date(); // You need to grab this from somewhere.
setInterval(function(){
var time = moment(messageTimeStamp).fromNow();
$("#chat-list").html(time);
}, 1000);
You need to use moment(TIMESTAMP_OF_MESSAGE) not moment() and do something like this:
$(function(){
$("body").append($('<div id="chat-time"></div>'));
var messageTimeStamp = new Date();
var i = 0;
setInterval(function(){
var time = moment(messageTimeStamp).fromNow();
$("#chat-time").html('moment().from(messageTimeStamp): ' + time + '; setInterval calls made ' + i++);
}, 1000);
});
Here's a demo.
http://plnkr.co/edit/QuaMV6x1vNB0kYPaU6i1?p=preview
I dont see any problem using setInterval (). AngularJS wrapper setInterval on $interval service module . Check out these urls: interval Angular and Wrapper SetInterval
I'm using a script called "HIT Scraper WITH EXPORT" to help me with my job. Right now it's set up in a way that any time there is a new posting the page plays a audible sound/ding. Normally when this happens I have to switch tabs and manually click on the new listing to preview it. I'm trying to make it so it automatically opens the listing before/after dinging. Also if possible having it put focus on that tab if I'm in a different one. Is any of this possible, where should I start? I'll post the code and some areas of interest I noticed, I just don't know what to do with these areas.. Thank you in advance.
The function that runs when a new hit is found I think:
function newHits(dingNoise) {
//console.log(dingNoise);
if (dingNoise || newHitDing)
document.getElementById("ding_noise"+audio_index).play();
}
I think "preview_link" is the var I need to automatically open after the ding sound plays.
var preview_link = "/mturk/preview?groupId=" + group_ID;
So my logic was something like:
function newHits(dingNoise) {
//console.log(dingNoise);
if (dingNoise || newHitDing)
document.getElementById("ding_noise"+audio_index).play();
window.open("/mturk/preview?groupId=") + group_ID;
}
Which did not work.. Here's the full script if anyone has any ideas.. Thanks again.
https://greasyfork.org/en/scripts/2002-hit-scraper-with-export/code
EDIT: I don't think the way I originally wanted to do this will work, nothing in the code knows/points to the actual new listings. All that's defined in the code is the preview link function. If there is some way to have it call/open that "var preview_link = "/mturk/preview?groupId=" + group_ID;" after the ding, that would probably be what I need.
for (var j = 0; j < $requester.length; j++)
{
var $hits = $requester.eq(j).parent().parent().parent().parent().parent().parent().find('td[class="capsule_field_text"]');
var requester_name = $requester.eq(j).text().trim();
var requester_link = $requester.eq(j).attr('href');
var group_ID=(listy[j] ? listy[j] : "");
group_ID=group_ID.replace("/mturk/notqualified?hit","");
var masters = false;
var title = $title.eq(j).text().trim();
var preview_link = "/mturk/preview?groupId=" + group_ID;
//console.log(listy[j]);
//console.log(title+" "+group_ID +" "+ listy[j]);
if (!group_ID || group_ID.length == 0){
preview_link = requester_link;
title += " (Requester link substituted)";
}
var reward = $reward.eq(j).text().trim();
var hits = $hits.eq(4).text().trim();
var time = $times.eq(j).parent()[0].nextSibling.nextSibling.innerHTML;
var description = $descriptions.eq(j).parent()[0].nextSibling.nextSibling.innerHTML;
//console.log(description);
var requester_id = requester_link.replace('/mturk/searchbar?selectedSearchType=hitgroups&requesterId=','');
var accept_link;
accept_link = preview_link.replace('preview','previewandaccept');
I'm thinking you want to do:
window.location.replace(window.location.host + '/mturk/preview?groupId='+ group_ID)
I'm actually not sure if you need the window.location.host + part.
I am trying to fix some javascript code that I am currently using on a website - which was working perfectly until IE 11 came along. The script is used to first detect the type of browser used then autofills the name of a file (like a JPEG or PDF) into a specified textfield, after the file has been uploaded to the site. However I am not the original author of this script and I am very unfamiliar with Javascript. I have searched everywhere for a solution and so far have found nothing to help me with this problem. Hoping someone can help. Here is the current code:
<script langauge="javascript">
function post_value(){
BrowserDetect.init();
if(BrowserDetect.browser=='Explorer'){
var str=document.formSmallPhoto.file1.value;
var index=str.lastIndexOf("\\");
opener.document.form1.small_photo.value = str.substring(index+1);
}
BrowserDetect.init();
if(BrowserDetect.browser=='Explorer'){
var str=document.formSmallPhoto.file1.value;
var index=str.lastIndexOf("\\");
opener.document.form1.small_photo.value = str.substring(index+1);
}
if(BrowserDetect.browser=='Safari'){
var str=document.formSmallPhoto.file1.value;
var index=str.lastIndexOf("\\");
opener.document.form1.small_photo.value = str.substring(index+1);
}
if(BrowserDetect.browser=='Chrome'){
var str=document.formSmallPhoto.file1.value;
var index=str.lastIndexOf("\\");
opener.document.form1.small_photo.value = str.substring(index+1);
}
if(BrowserDetect.browser=='Opera'){
var str=document.formSmallPhoto.file1.value;
var index=str.lastIndexOf("\\");
opener.document.form1.small_photo.value = str.substring(index+1);
}
if(BrowserDetect.browser=='Firefox'){
var str=document.formSmallPhoto.file1.value;
var index=str.lastIndexOf("\\");
opener.document.form1.small_photo.value = str.substring(index+1);
}
}
function closeChildWindow(){
self.close();
}
</script>
After thinking about your comments about browser detection, I decided to play with the code a little and discovered that it's not needed and works great now. Thanks Eric Barber for your help in pointing me in the right direction! Here is the amended code:
<script langauge="javascript">
function post_value(){
{
var str=document.formSmallPhoto.file1.value;
var index=str.lastIndexOf("\\");
opener.document.form1.small_photo.value = str.substring(index+1);
}
}
function closeChildWindow(){
self.close();
}
</script>
I'm trying to figure out how to onClick a buttom so that it automatically figures what day the machine is in and find the website according to it (e.g. if it is Sunday, it will find Sunday.html)
Being a beginner at HTML, CSS and Javascript, I got the code from w3schools and changed the output to just .html - obviously, it didn't work. I was wondering is there any simple way of correcting this?
<button onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
var d = new Date();
var weekday=new Array(7);
weekday[0]="Sunday.html";
weekday[1]="Monday.html";
weekday[2]="Tuesday.html";
weekday[3]="Wednesday.html";
weekday[4]="Thursday.html";
weekday[5]="Friday.html";
weekday[6]="Saturday.html";
var x = document.getElementById("demo");
x.innerHTML=weekday[d.getDay()];
}
</script>
I've also did another way through using if statement,
if (currentDay == 6)
{
window.location = 'saturday.html';
}
}
else if (currentDay == 0)
{
window.location = 'sunday.html';
}
etc.
Again, it doesn't seem to work. Is there simple way of doing this?
Thanks in advance
The second method of doing window.location to the url is correct.
I did minor modification to your code. Please try the fiddle (http://jsfiddle.net/QK2TL/1/).
Open the debug console to see the messages.
var d = new Date();
var loc = weekday[d.getDay()];
alert("about to navigate to " + weekday[d.getDay()]);
window.location = loc;
function myFunction()
{
var d = new Date();
var weekday=[];
weekday[0]="Sunday.html";
weekday[1]="Monday.html";
weekday[2]="Tuesday.html";
weekday[3]="Wednesday.html";
weekday[4]="Thursday.html";
weekday[5]="Friday.html";
weekday[6]="Saturday.html";
return weekday[d.getDay()];
}
window.location = myFunction();