How to put a JavaScript timer in a box? - javascript

I have this JavaScript code:
<script type="text/javascript">
function timeMsg() {
var t=setTimeout("doRedirect()",10000);
}
function doRedirect() {
window.location.replace( "http://www.codemeh.com/" );
}
timeMsg();
</script>
But I want to show how much time is left in a box that floats at the top right, and with my l;ittle knowledge of JavaScript i have no idea where to start :(
Can someone help me?

(function(count) {
setInterval(function() {
if( count === 0) {
window.location.href = "http://www.codemeh.com/";
}
else {
document.getElementById('box_that_floats_top_right').innerHTML = 'Timeleft: ' + (count / 1000);
count -= 1000;
}
}, 1000);
}(10000));
Demo: http://www.jsfiddle.net/4yUqL/77/

A quick solution for you:
<input id="box" type="text" size="8" />
<script>
//Init vars
var milsec=0;
var sec=30;
var box = document.getElementById("box");
function display() {
if (milsec <= 0){
milsec=9;
sec-=1;
}
if (sec <= -1){
milsec=0 ;
sec+=1;
} else {
milsec-=1 ;
box.value = sec + "." + milsec;
//call function display after 100ms
setTimeout(function() {display();},100);
}
}
display();
</script>

<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
timeLeft = 10;
function timeMsg() {
if(--timeLeft == 0) {
doRedirect();
} else {
$("#time").val(timeLeft);
setTimeout("timeMsg()",1000);
}
}
function doRedirect() {
window.location.replace( "http://www.codemeh.com/" );
}
$(document).ready(function() {
$("#time").val(timeLeft);
setTimeout("timeMsg()",1000);
});
</script>
<input id="time" size="5"></input>

Related

Javascript if - else if inside switch using ("#id").length

Code edited. Apologizes for the incomplete first code
I've this code that takes input from the user, and it appends an image that matches that input. What I want to do is to set different buttons (200 aprox.) to append a different image if other button is pressed. The approaching I'm doing for this is to target the first if, within the first switch case, with the ("#id").length condition.
This is a short example of my code:
HTML:
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://code.jquery.com/jquery-3.1.1.js"></script>
</head>
<body>
<section id="section">
<input id="input">
<button id="1"></button>
<button id="2"></button>
</section>
<div id="div"></div>
</body>
</html>
Javascript:
$(document).ready(function() {
var str;
$("#1, #2").click(function () { test(); });
});
var input = ['a','b','c'];
function test() {
var interval = setInterval(match, 1);
$("div").html("");
str = $("input").val().toLowerCase();
var i = 0;
function match() {
var imgs = ["<img src='https://1.bp.blogspot.com/-v2N2hPY33pc/V488gHu5aWI/AAAAAAAAHFM/loGVDK5OlGcft5UUz8-AHZjAd3E7OlZjACLcB/s1600/colorful-background-with-waves.jpg' alt='0'>",
"<img src='https://upload.wikimedia.org/wikipedia/commons/c/c8/Widget_icon.png' alt='1'>"];
if (i < str.length) {
switch (str[i]) {
case input[0]:
if ($("#1").length){
$("div").append(imgs[0]);
i++;
break;
}else if ($("#2").length){
$("div").append(imgs[1]);
i++;
break;
}
}
else {
clearInterval(interval);
$("input").val("");
}
}
}
Now, I've managed to make the if work, it shows the image, but if I press the second button, the else-if never works. What am I doing wrong?
Well I can't for the life of me figure out what you're trying to do with this code, but here is a working version of it...
$(document).ready(function() {
var str;
$("#1, #2").click(function () { test(this); });
});
var input = ['a','b','c'];
function test(caller) {
var interval = setInterval(match, 1);
var i = 0;
$("div").html("");
str = $("input").val().toLowerCase();
function match() {
var imgs = ["<img src='https://1.bp.blogspot.com/-v2N2hPY33pc/V488gHu5aWI/AAAAAAAAHFM/loGVDK5OlGcft5UUz8-AHZjAd3E7OlZjACLcB/s1600/colorful-background-with-waves.jpg' alt='0'>","<img src='https://upload.wikimedia.org/wikipedia/commons/c/c8/Widget_icon.png' alt='1'>","<img src='https://upload.wikimedia.org/wikipedia/commons/thumb/e/ec/Mona_Lisa%2C_by_Leonardo_da_Vinci%2C_from_C2RMF_retouched.jpg/100px-Mona_Lisa%2C_by_Leonardo_da_Vinci%2C_from_C2RMF_retouched.jpg' alt='2'/>","<img src='https://upload.wikimedia.org/wikipedia/commons/thumb/1/11/Corythucha_ciliata.jpg/120px-Corythucha_ciliata.jpg' alt='3'/>"];
if (i < str.length) {
switch (str[i]) {
case input[0]:
if (caller.id == "1") {
$("div").append(imgs[0]);
i++;
break;
} else if (caller.id == "2") {
$("div").append(imgs[1]);
i++;
break;
}
case input[1]:
if (caller.id == "1") {
$("div").append(imgs[2]);
i++;
break;
} else if (caller.id == "2") {
$("div").append(imgs[3]);
i++;
break;
}
}
} else {
clearInterval(interval);
$("input").val("");
}
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="input"/>
<button id="1">1</button>
<button id="2">2</button>
<div></div>

How to do this in jQuery?

I want to transform this code from JavaScript into jQuery.
This is the current code:
var i = 0;
var start = true;
document.getElementById("startclick").addEventListener("click", function() {
if (start) {
start = false;
interval = setInterval(function() {
i++;
document.getElementById('list').innerHTML += "albastru_" + i + '<br>' ;
}, 3000);
} else {
start = true;
clearInterval(interval);
}
});
Here is my attempt:
$x = 0;
$start = true;
$(document).ready(function () {
$('#buton2').on('click',function () {
if($start){
$start = false;
$interval = setInterval(function () {
$x ++;
$('#list').html('<p>albastru_</p>' + $x + '<br>'); }, 1000);
} else {
$start = true;
clearInterval($interval);
}
})
});
You can do something like below. I'm assuming startclick is a button, after you click it .append() will add the required data to #list div after 3 seconds.
Updated Answer with start and stop buttons.
var i = 0;
var start = true;
var interval = null;
$('#startclick').click(function() {
if (interval !== null) return;
interval = setInterval(function() {
i++;
$('#list').append("albastru_" + i + '<br>');
}, 3000);
});
$("#stop").click(function() {
clearInterval(interval);
interval = null;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="list">
</div>
<br />
<button id="startclick">START!</button>
<button id="stop">STOP!</button>

how to clear Interval on Mouse Over in java script?

<script type="text/javascript">
var images=["cod.jpg","cod2.jpg","cod3.jpg","cod4.jpg"];
var i=0;
window.onload=function(){
changeimage();
var stopinterval = setInterval(changeimage,3000);
}
function changeimage(){
if(i==images.length||i>images.length){
i=0;
}
document.getElementById('metroslider').src=images[i];
i++;
}
function stopanim(){
clearInterval(stopinterval);
}
</script>
**body is below **
<div class="sliderbtns" onMouseMove="stopanim();">
But its not working please help me how to stop the interval using On mousOver function .
Thanks .
var images = ["cod.jpg", "cod2.jpg", "cod3.jpg", "cod4.jpg"];
var i = 0;
var stopinterval;
window.onload = function() {
changeimage();
stopinterval = setInterval(changeimage, 333);
}
function changeimage() {
document.querySelector('div').innerHTML = i;
i++;
}
function startAnim() {
if (stopinterval === null) {
stopinterval = setInterval(changeimage, 333);
}
}
function stopanim() {
if (stopinterval) {
clearInterval(stopinterval);
stopinterval = null;
}
}
<div onmouseover="stopanim()" onmouseout="startAnim()">mouse over to stop</div>

Javascript show variable every 50 ms

I want to make a little 'loading...' widget for my website, using javascript.
var percent=0;
var message="Loading... "
var per="%"
function count(){
percent=percent+1;
if(percent==100){
alert("Loading end.")
}else{
setTimeout("count",50)
document.write(message)
document.write(percent)
document.write(per)
}
But it isn't running. I think I've got some mistake (or maybe totally wrong). How can I do this? I want to update the shown message every 50ms.
try with interval and clear it when progress is finished:
<!DOCTYPE html>
<html>
<head>
<title>testing</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<div id="progress">MSG</div>
<script type="text/javascript">
var percent = 0;
var message = "Loading... ";
var per = "%";
var dom = document.getElementById('progress');
var iv = setInterval(function(){
console.log(message);
dom.innerHTML = ((percent++) + per +' '+ message);
if(percent === 100){
console.log("Loading end.");
clearInterval(iv);
return false;
}
}, 50);
</script>
</body>
</html>
try
setInterval(count,50);
instead of setTimeOut("count",50)
You want to set an interval which runs every x milliseconds, passing in an anonymous function to call the function to call
var percent=0;
var message="Loading... "
var per="%"
function count(){
percent=percent+1;
if(percent==100){
alert("Loading end.")
}else{
setInterval(function() { count() },50)
document.write(message)
document.write(percent)
document.write(per)
}
} <--- you were also missing this ending brace
Script:
var percent = 0;
var message = "Loading... ";
var per = "%";
$(document).ready(function () {
count();
});
function count() {
percent = percent + 1;
if (percent == 100) {
alert("Loading end.");
} else {
setTimeout(function () {
count();
}, 50);
document.write(message);
document.write(percent);
document.write(per);
}
}
see this fiddle for more http://jsfiddle.net/8nhmU/19/
See this jsfiddle
HTML:
<span id="loading"></span>
Javascript:
var percent = 0;
var message = "Loading...";
var per = "%";
var element = document.getElementById('loading');
var interval = setInterval(function() {
element.innerHTML = message + percent + per;
percent += 1;
if(percent > 100) {
clearInterval(interval)
};
}, 50)
The code in your example is missing a great deal of semi-colons and the ending curly-bracket, but that's not the end-issue.
The "problem" with your call to setTimeout is that the first argument must be an actual function, not a string. If you remove the quotes around the call, it will work.
Here is a copy of your code, re-formatted:
var percent=0;
var message="Loading... ";
var per="%";
function count() {
percent++;
if (percent == 100) {
alert("Loading end.");
} else {
setTimeout(count, 50);
document.write(message);
document.write(percent);
document.write(per);
}
}
You are doing it wrong way. You should call the setInterval method when window loads. And when loading is completed, you should stop interval by clearing it using its ID.
var countId;
window.onload = function(){
countId=setInterval(count,50);
}
function count(){
if(per=99){
clearInterval(countId);
}
per++;
//show your message
}

Life Counter Issue

I was builiding lately life counter and i can't figure out what the issue around here, I mean i got 2 divs, when you on div with class "alive" you get score up and when you in "dead" div you get score down.
Now I've made this code that work on seconds, but it not working stright, I mean 1, 2, 3. But it working like this: http://jsfiddle.net/4Tby5/
Or as visual code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Alive - Dead</title>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
var l = 1;
var good = " Excelent!";
var bad = " OH NO!";
$(document).ready(function () {
$('#alive').hover(function () {
if (l > 100) {
window.clearTimeout("tim");
}
else {
document.getElementById("percent").innerHTML = "Life: " + l + good;
l++;
var tim = window.setTimeout("count()", 1000);
}
count();
});
});
$(document).ready(function () {
$('#dead').hover(function () {
if (l < 0) {
window.clearTimeout("tim");
}
else {
document.getElementById("percent").innerHTML = "Life: " + l + bad;
l--;
var tim = window.setTimeout("count()", 1000);
}
count();
});
});
</script>
<style>
body {
background: red;
}
.dead {
cursor: url(thumb-down.cur) 6 6, auto;
padding-bottom: 285px;
}
.alive {
background: #32ff0a;
height: 300px;
margin: -8px;
cursor: url(thumb-up.cur) 6 6, auto;
}
</style>
</head>
<body>
<div class="alive" id="alive">
Stay here to survive!
</div>
<div class="dead" id="dead">
<br />
Stay away from dead area!
</div>
<div id="percent"></div>
</body>
</html>
So my question is how can i fix this to get it 1,2,3 (replace 1 with 2 and 3, 4...)?
You do not have a count function, make one
And you clear a timeout using the variable itself not its name
window.clearTimeout(tim);
also with your current code you will need to use a global variable
window.tim = window.setTimeout("count()", 1000);
window.clearTimeout(window.tim);
otherwise the clearTimeout wont see it.
Here is solution to your problem.
Problem in your code is... Hover function is calulated only when Mouse enters... Not as long as mouse remains inside.
http://jsfiddle.net/Vdq39/2/
$(document).ready(function () {
var good = " Excelent!";
var bad = " OH NO!";
var tim;
var counter = 0;
function count() {
counter++;
document.getElementById("percent").innerHTML = "Life: " + counter + good;
if (counter > 100) {
window.clearInterval(tim);
}
}
function countDown() {
counter--;
document.getElementById("percent").innerHTML = "Life: " + counter + bad;
if (counter < 0) {
window.clearInterval(tim);
}
}
$('#alive').hover(function () {
if (counter > 100) {
window.clearInterval(tim);
} else {
tim = window.setInterval(count, 1000);
}
}, function () {
window.clearInterval(tim);
});
$('#dead').hover(function () {
if (counter < 0) {
window.clearInterval(tim);
} else {
tim = window.setInterval(countDown, 1000);
}
},
function () {
window.clearInterval(tim);
});
});

Categories