new mail counter javascript - javascript

I am having some major problems with a javascript app I'm working on. I want my window to open to a closed envelope and then after five seconds to change to an open envelope with a little 1 counter in the corner of it. I want the counter to continue to move up every five seconds unless the envelope is clicked. If clicked I want the count to start over. So far I have only gotten my closed envelope showing up. I'm new and have no idea what I am doing wrong so any help would be awesome!
My html:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="mail.js"></script>
</head>
<body>
<img id"closed" src="closed.png" onclick="resetTimer()">
<span id="counter"></span>
</body>
</html>
And my JavaScript:
window.onload = function(){
var counter = 0;
var timer = setInterval(
function(){
counter++;
document.getElementById("demo").firstChild.nodeValue = counter;
},
5000
);
function openEnvelope(){
var img = document.getElementById("picture");
if (counter > 1){
img.src = "open.png"
}
}
open = setTimeout("open()", 1000);
function resetTimer(){
clearInterval(timer);
}
}

You need to increment your counter and set the counter span to have that value :
var counter = 0;
//Create your timer (setTimeout will only run once, setInterval will start again once run.
//1000 = 1 second
var timer = setInterval(openEnvelope, 1000);
function openEnvelope() {
var img = document.getElementById("picture");
var counterSpan = document.getElementById("counter");
if (counter > 1) {
img.src = "open.png"
counterSpan.innerHTML = counter;
}
//Add 1 to Counter
counter++;
}
function resetTimer() {
clearInterval(timer);
counter = 0;
}
This will run your openEnvelope function every second, and if the counter value is more than 1 it will set the Img Source to be open.png and the counter span to have the counters value. On the click of the Envelope it will clear the timer and reset the counter.
And your HTML will become :
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="mail.js"></script>
</head>
<body>
<img id"picture" src="closed.png" onclick="resetTimer()">
<span id="counter"></span>
</body>
</html>
Here is a working JSFiddle for your problem, try creating a blank page and copying the HTML straight into the <body> tag and the Javascript into <script></script> tags in the <head> of your page.

Related

How to do an action when a variable hits a specific number javascript

So basically I have done this code down bellow and I am trying to have a button that adds 1 to a variable and when that variable hits the specific number it plays an action. My final goal is to make it so when the variable hits the specific number it redirects to another page. I have tried for way too long and my friends don't know the solution either.
<!DOCTYPE html>
<head> </head>
<!DOCTYPE html>
<html>
<head>
<title> click tester </title>
<Meta charset="utf-8">
</head>
<body>
<script>
var theClicks = 1;
const win = 25;
if(theClicks >= win) {
alert('over 25');
}
</script>
<button onclick=theClicks++;>Button that adds1 to variable</button>
</body>
</html>
<button onclick=theClicks++;>Button that adds1 to variable</button>
Just increments the variable. To expand that you could add more actions in the button onclick event, but it's much better to just put it all in a function you can call.
<script>
var theClicks = 1;
const win = 25;
function doThing() {
if (++theClicks >= win) {
alert('over 25');
}
}
</script>
<button onclick='doThing()'>Button that adds1 to variable</button>
You could take an approach like below. Basically create a function that keeps track of a counter variable (i.e., i). Next add a click event listener to the button and increment the counter on each click. When the counter reaches 25 then do some action (I made it only needed to be clicked 3 times in the code below for demo convenience) .
For example:
// Reference to the DOM elements
const countEl = document.querySelector('#count-el');
const buttonEl = document.querySelector('button');
// Init a counter variable and return a function that increments it
const increment = (() => {
let i = 1;
return () => i++;
})();
// The click event listener
buttonEl.addEventListener('click', () => {
// Increment the count and update the UI if current click count is 3
if (increment() === 3) {
countEl.textContent = 'Do action now!';
}
});
<span id="count-el"></span>
<br />
<button>Click 3 times to do action</button>

object.innerHTML not updating properly?

I tried to make a progress bar in javascript, but it didnt load till my
program was finished. How can i make it updating while the program is still running?
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div id="main" onclick="my()">1</div>
<button onclick="myFunction()">start</button>
<script>
function myFunction() {
for(var i=0;i<1000000;i++){
document.getElementById("main").innerHTML=i;
}
}
</script>
</body>
</html>
Use setInterval method which runs in the background without blocking. Once reached the condition you can clear the interval using clearInterval method.
function myFunction() {
// get element reference and cache in a variable
let main = document.getElementById("main"),
// initialize i as 0
i = 0;
// keep interval reference for clearing once i reached 1000000
let intrvl = setInterval(() => {
// check value of i and increment, if reached 1000000 clear the interval
if (i++ === 1000000) clearInterval(intrvl);
// update the content of main element
main.innerHTML = i;
}, 1000); // set required delay in millisecond, any value lesser than 10 will be automatically converts to 10
}
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div id="main" onclick="my()">1</div>
<button onclick="myFunction()">start</button>
<script>
function myFunction() {
let main = document.getElementById("main"),
i = 0;
let intrvl = setInterval(() => {
if (i++ === 1000000) clearInterval(intrvl);
main.innerHTML = i;
},1000);
}
</script>
</body>
</html>
I used setInterval instead of for cicle and i used parseInt() to get integer value of your div innerHTML and then increment it
setInterval(myFunction, 1000) runs myFunction() every 1000 milliseconds
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div id="main" onclick="my()">1</div>
<button onclick="setInterval(myFunction, 1000)">start</button>
<script>
function myFunction(){
var value = parseInt(document.getElementById("main").innerHTML);
document.getElementById("main").innerHTML=value+1;
}
</script>
</body>
</html>

How to add a timer for images in JavaScript?

I've been working on this code which displays the next traffic light when a button is pressed. Now I am trying to diplay the images in the array every 3 seconds. I have tried using setTimeOut in my code but my code juts stays on the first traffic light.
code:
EDIT(FIXED)
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Code</h1>
<p>Traffic Light</p>
<img id="traffic" src="only red1.jpg">
<button type="button" onclick="ChangeLight()">Change Light</button>
<script>
var list = ["only red1.jpg","red-yellow 2.jpg", "green3.jpg","yellowonly4.jpg"];
var nextlight = 0;
var timer;
function ChangeLight() {
nextlight = nextlight + 1;
if (nextlight == list.length)
nextlight = 0;
var firstlight = document.getElementById('traffic');
firstlight.src = list[nextlight];
}
timer = setInterval(ChangeLight, 3000);
</script>
</body>
</html>
Solution:
timer = setInterval("ChangeLight", 3000);
Put it out of the function ^^
2 things:
It's supposed to be setInterval(ChangeLight, 3000);
timer is inside the ChangeLight function. You should move it outside.
You may want to change timer = setTimeout("ChangeLight", 3000); into timer = setTimeout(ChangeLight, 3000);.

JavaScript Timeout Function

I was looking in other posts for the answer, but the answers never seem to work in my favor. I'm trying to make an image fade when the page finishes loading. I've figured out I can loop until the counter reaches 0 (when image is invisible) and fade the image slowly.
The problem is, the setTimeout() function doesn't seem to be working.
Here's the code:
function timeout() {
setTimeout(function () {
//A comment said something about looping,
//but it was confusing to understand...
}, 50);
}
function setup() {
var load = document.getElementById('img');
load.style.opacity = 0 //Start at being visible
for (var i = 10; i > 0; i = i - 0.1) { //For loop
load.style.opacity = i; //Use the index variable and use that to set the opacity
setTimeout(); //Set the timeout, but this function does not pause the program for some reason...
//I need to pause for 0.05 seconds.
}
}
window.addEventListener('load', setup, true); //Add event listener for when the page is done loading
<!DOCTYPE html>
<html>
<head>
<title>Webpage</title>
</head>
<body>
<div id="img">
<img src="http://www.downgraf.com/wp-content/uploads/2014/09/01-progress.gif" width="200" height="150">
</div>
</body>
</html>
I put the javascript in a seperate file, I just can't access it from Stack Overflow...
Can someone help? And also, sometimes the image can be finicky at times as well, like sometimes it won't hide like it's supposed to do. Thanks!
You declared a setTimeout without arguments, hence the error:
'Window': 1 argument required, but only 0 present."
Give it the appropriate amount of arguments:
for (var i = 10; i > 0; i = i - 0.1) { //For the loop
load.style.opacity = i;
setTimeout(functionName, milliseconds);
}
If you intended to use your timeout() function instead, call it. You're just instantiating a new setTimeout from the one you already created in the timeout() function.
You can use a recursive function instead of a loop
var load = document.getElementById('img');
function setup() {
load.style.opacity = "1"; //Start at being visible
timeout(1);
}
function timeout(i) {
setTimeout(function() {
i -= 0.1;
if(i<=0)
return;
load.style.opacity = i.toString();
timeout(i);
}, 200);
}
window.addEventListener('load', setup, true); //Add event listener for when the page is done loading
<!DOCTYPE html>
<html>
<head>
<title>Webpage</title>
</head>
<body>
<div>
<img src="http://www.downgraf.com/wp-content/uploads/2014/09/01-progress.gif" width="200" height="150" id="img">
</div>
</body>
</html>
Basically you want to countdown the opacity with a recursive call. Here we are going from 1 down to 0 in 0.01 increments. The setTimeout will trigger the next recursive call after pausing for 50 msecs. These values, can of course, be adjusted as needed but the opacity needs to be a number from 1 (visible) to 0 (invisible).
function setOpacity(el, lvl) {
el.style.opacity = lvl;
}
function countDown(el, lvl) {
function action(el, lvl) {
return function () {
countDown(el, lvl);
}
}
setOpacity(el, lvl);
if (lvl > 0) {
lvl -= 0.01
setTimeout(action(el, lvl), 50);
}
}
function setup() {
var load = document.getElementById('img');
load.style.opacity = 1; //Start at being visible
countDown(load, 1);
}
window.addEventListener('load', setup, true);
<!DOCTYPE html>
<html>
<head>
<title>Webpage</title>
</head>
<body>
<div id="img">
<img src="http://www.downgraf.com/wp-content/uploads/2014/09/01-progress.gif" width="200" height="150">
</div>
</body>
</html>
function setup() {
var load = document.getElementById('img');
(function(){
var i = 1;
setTimeout(function () {
i -= 0.1;
load.style.opacity = i;
if (i > 0) {
setTimeout(arguments.callee, 100);
}
}, 100);
})();
}
window.addEventListener('load', setup, true); //Add event listener for when the page is done loading
<div id="img">
<img src="http://www.downgraf.com/wp-content/uploads/2014/09/01-progress.gif" width="200" height="150">
</div>

Write sequence of random numbers in javascript to paragraph

Really a newbie question but I can't seem to find the answer. I need to have this html file show a bunch of random numbers, separated by 1 second intervals. For some reason (maybe obvious) it is only showing me the last one unless I have 1 alert after each random number generated. How can I correct this?
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var randomnumber
var message
function placePossibleWinner()
{
randomnumber=Math.floor(Math.random()*11);
message="Teste ";
message=message.concat(randomnumber.toString());
document.getElementById("WINNER").innerHTML=message;
//alert(".")
}
</script>
</head>
<body>
<script type="text/javascript">
function runDraw()
{
var i=1
alert("start")
while (i<20)
{
setTimeout("placePossibleWinner()",1000)
i++
}
}
</script>
<h1>H Draw</h1>
<p id="WINNER">Draw</p>
<p></p>
<button onclick="runDraw()">Get me winner!</button>
</body>
</html>
Thanks in advance for any answers/comments.
The problem is all your setTimeouts are being triggered at the same time. Adding alerts pauses the JavaScript execution, so you see each number. Without that, after 1 second, all 19 setTimeouts run (one after another) and you just see one number (the screen is updated so fast, you just see one).
Try using setInterval instead.
function runDraw() {
var i = 1;
var interval = setInterval(function(){
if(i < 20){
placePossibleWinner();
i++;
}
else{
clearInterval(interval);
}
}, 1000);
}​
This will run the function once every second, until i is 20, then it will clear the interval.
I believe you want setInterval instead. using setTimeout in a loop will just queue up 20 calls immediately and they will all fire at once 1 second later. Also, you are setting the innerHTML of the p which will overwrite any previous text.
function placePossibleWinner() {
// add a var here, implicit global
var randomnumber=Math.floor(Math.random()*11);
// add a var here, implicit global
message="Teste " + randomnumber + '\n'; // new line
document.getElementById("WINNER").innerHTML += message; // concat, don't assign
}
function runDraw() {
var counter = 1;
var intervalID = setInterval(function () {
if (counter < 20) {
placePossibleWinner();
counter++;
} else {
clearInterval(intervalID);
}
}, 1000);
}
You are resetting your message in your functions and you are calling placePossibleWinner() the wrong way... you want to use setInterval. Below is a modification of your html/javascript
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var randomnumber;
var message = "Teste ";
var timesCalled = 0;
var funtionPointer;
function placePossibleWinner()
{
timesCalled++;
randomnumber=Math.floor(Math.random()*11);
message=message.concat(randomnumber.toString());
document.getElementById("WINNER").innerHTML=message;
if (timesCalled > 20)
{
clearInterval(functionPointer);
}
}
</script>
</head>
<body>
<script type="text/javascript">
function runDraw()
{
var i=1
alert("start")
functionPointer = setInterval(placePossibleWinner,1000)
}
</script>
<h1>H Draw</h1>
<p id="WINNER">Draw</p>
<p></p>
<button onclick="runDraw()">Get me winner!</button>
</body>
</html>
To start with,
setTimeout("placePossibleWinner()",1000)
should be
setTimeout(placePossibleWinner,1000)
The parameter to setTimeput should be a reference to a function. See JavaScript,setTimeout

Categories