Meter bar not updating - javascript

This is the code:
<!DOCTYPE html>
<style>
h1 {
color: white;
}
body {
background-color: black;
}
.scroller {
background: linear-gradient(#94ff98, green);
}
</style>
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<h1 align="center">Fetching data...</h1>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<meter id="prog" value="0" max="100" style="width: 100%"></meter>
<script>
setInterval(
function () {
var prog = document.getElementById("prog");
var i = 0;
i = i + 1;
prog.setAttribute("value", i)
},
10
);
</script>
</body>
</html>
Yes, I know the meter element isn't for progress bars, but im just using it merely for aesthetics and it isn't doing anything at all, really.
So why is it not updating, setinterval only runs once?

The variable declaration of i should be moved outside of the setInterval callback. The variable i is reinitialize to zero for each interval.
Also, it's better to clear the interval after i has reached 100.
Demo
var i = 0;
var interval = setInterval(function() {
var prog = document.getElementById("prog");
i = i + 1;
prog.value = i;
console.log(i);
if (i >= 100) {
clearInterval(interval);
}
}, 10);
h1 {
color: white;
}
body {
background-color: black;
}
.scroller {
background: linear-gradient(#94ff98, green);
}
<h1 align="center">Fetching data...</h1>
<br>
<br>
<meter id="prog" value="10" max="100" style="width: 100%"></meter>

Try this code It will help you
<script>
var i = 0;
var interval = setInterval(function () {
var prog = document.getElementById("prog");
i = i + 1;
prog.value = i;
console.log(i);
if (i >= 100) {
clearInterval(interval);
}
}, 35);
</script>

Your code is saying: every 10 milliseconds,
access the DOM,
1 declare a variable, assign it's value to 0,
add 1 to i (0 + 1 = 1)
then set the value of your DOM element to i (e.g 1)
The problem is that your code keeps creating a new locally scoped variable i and setting it to zero each time that function is called.
You need to move i outside the scope of your anonymous function.

Related

dynamic change in javascript, won't move my div

Hi there fellow programmers!
I Want to be able to type in to the boxes how much px i want my div to move. But it won't move and I cant see whats wrong with my code. Can someone with fresh eyes spot the problem?
Any help is much appreciated!
Here's the code so far:
<!DOCTYPE html>
<html lang="sv">
<head>
<meta charset="utf-8">
<title> javascript</title>
<style>
#changeme {
background-color: lightblue;
position: absolute;
}
</style>
<script>
var $Rob = {};
$Rob.moveUpp = 0;
$Rob.moveLeft = 0;
$Rob.elementid = "";
$Rob.move = function(elementid, movex, movey)
{
$Rob.moveUpp = movey;
$Rob.moveLeft = movex;
$Rob.elementid = elementid;
$Rob.movesoft();
}
$Rob.movesoft = function() {
var elem = document.getElementById($Rob.elementid);
if ($Rob.moveUpp > 0) {
elem.style.top = (parseInt(elem.style.top) + 1) +
"px";
$Rob.moveUpp--;
} else if ($Rob.moveUpp < 0) {
elem.style.top = (parseInt(elem.style.top) - 1) +
"px";
$Rob.moveUpp++;
}
if ($Rob.moveUpp != 0) {
setTimeout($Rob.movesoft, 100);
}
}
</script>
</head>
<body>
<h1> Dynamic changes </h1>
<form>
<p>Move right:</p> <input value="0" type="text" id="moveRight" />
<p>Move down: </p> <input value="0" type="text" id="moveDown" />
<input type="button" value="Move" onClick="$Rob.move(document.getElementById('changeme'),parseInt(document.getElementById('moveRight').value),parseInt(document.getElementById('moveDown').value));" />
</form>
<div id="changeme" style="top: 100px;left: 100px;"> Hello </div>
</body>
</html>
All the best
I love Stackoverflow and its members!
cheers
// Mcgayjver
You're doing:
$Rob.move(document.getElementById('changeme'), x, y).
When you should just be doing:
$Rob.move('changeme, x, y)
Because $Rob.move expects an elementID string as a first parameter, not an actual HTMLElement.

Method fired multiple times on click event

I'm building a web app in which the user can type in any key word or statement and get in return twenty results from wikipedia using the wikipedia API. AJAX works just fine. When the web app pulls data from wikipedia it should display each result in a DIV created dynamically.
What happens is that, when the click event is fired, the twenty DIVs are created five times, so one hundred in total. I don't know why but, as you can see in the snippet below, the web app creates twenty DIVs for each DOM element that has been hidden (through .hide) when the click event is fired.
Here's is the code:
function main() {
function positive() {
var bar = document.getElementById("sb").childNodes[1];
var value = bar.value;
if (!value) {
window.alert("Type in anything to start the research");
} else {
var ex = /\s+/g;
var space_count = value.match(ex);
if (space_count == null) {
var new_text = value;
} else {
new_text = value.replace(ex, "%20");
//console.log(new_text);
}
url = "https://en.wikipedia.org/w/api.php?action=query&format=json&prop=&list=search&continue=-%7C%7C&srsearch=" + new_text + "&srlimit=20&sroffset=20&srprop=snippet&origin=*";
var request = new XMLHttpRequest();
request.open("GET", url);
//request.setRequestHeader("Api-User-Agent", "Example/1.0");
request.onload = function() {
var data = JSON.parse(request.responseText);
render(data);
//console.log(data);
}
request.send();
}
}
function render(data) {
$("#first_h1, #first_h3, #sb label, #second_h1, #second_h3").hide("slow", function() {
$("#sb input").css({
"float":"left",
"margin-left":"130px"
});
$("#first_btn").css({
"float":"left"
});
var title = data.query.search[0].title;
var new_text = document.createTextNode(title);
var new_window = document.createElement("div");
new_window.appendChild(new_text);
new_window.setAttribute("class", "window");
var position = document.getElementsByTagName("body")[0];
position.appendChild(new_window);
//}
});
}
var first_btn = document.getElementById("first_btn");
first_btn.addEventListener("click", positive, false);
}
$(document).ready(main);
html {
font-size: 16px;
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;ù
}
.align {
text-align: center;
}
#first_h1 {
margin-top: 30px;
}
#first_h3 {
margin-bottom: 30px;
}
#sb {
margin-bottom: 10px;
}
#second_h1 {
margin-top: 30px;
}
#second_h3 {
margin-bottom: 30px;
}
.window {
width: 70%;
height: 150px;
border: 3px solid black;
margin: 0 auto;
margin-top: 20px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Wikipedia Viewer</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href="css/main.css">
</head>
<body>
<h1 class="align" id="first_h1">Wikipedia Viewer</h1>
<h3 class="align" id="first_h3">Type in a key word about the topic you are after<br>and see what Wkipedia has for you..</h3>
<p class="align" id="sb">
<input type="text" name="search_box" placeholder="Write here">
<label for="search_box">Your search starts here...</label>
</p>
<p class="align" id="first_btn">
<input type="submit" value="SEND">
</p>
<h1 class="align" id="second_h1">...Or...</h1>
<h3 class="align" id="second_h3">If you just feel eager of random knowledge,<br>punch the button below and see what's next for you...</h3>
<p class="align" id="second_btn">
<input type="submit" value="Enjoy!">
</p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
window.jQuery || document.write('<script src="js/jquery-3.2.1.min.js"><\/script>')
</script>
<script type="text/javascript" src="js/script.js"></script>
</body>
</html>
I made the code easier to read by erasing the for loop. As you can see, even with just one result, it is displayed five times.
Do you know guys why it happens?
thanks
The line:
$("#first_h1, #first_h3, #sb label, #second_h1, #second_h3").hide("slow", function() {})
Says, for every element in this "list", hide the element and run this block of code after hidden.
This code is the culprit:
$("#first_h1, #first_h3, #sb label, #second_h1, #second_h3").hide("slow",
function() {...});
The callback function is called five times, one for each ID listed, not once for all of them, as you might expect.
A workaround is to create a class (say, "hideme"), apply it to each element you want to hide, and write:
$('.hideme').hide("slow", function() {...});
function render(data) {
$("#first_h1, #first_h3, #sb label, #second_h1, #second_h3").hide("slow", function() {
$("#sb input").css({
"float":"left",
"margin-left":"130px"
});
$("#first_btn").css({
"float":"left"
});
}); // Finish it here..
var title = data.query.search[0].title;
var new_text = document.createTextNode(title);
var new_window = document.createElement("div");
new_window.appendChild(new_text);
new_window.setAttribute("class", "window");
var position = document.getElementsByTagName("body")[0];
position.appendChild(new_window);
//}
// }); Move this line..
}
As described in the docs:
complete: A function to call once the animation is complete, called once per matched element.
Which means this line will call the handle function 5 times with 5 matched elements.
$("#first_h1, #first_h3, #sb label, #second_h1, #second_h3").hide("slow", function() {
The easiest solution is moving the render codes outside of the hide event handler

Function not defined, even though I defined it

I’m making a game and a function that I defined says that it’s not defined.
I looked and it said that the other person with the same issue had an extra ) somewhere but I looked and I don’t have that problem.
I don’t have anything extra that is not needed.
<DOCTYPE html>
<html>
<head>
<title>Programing Clicker</title>
<style>
h1{
color:#333;
font-family:helvetica;
font-weight: bold;
font-size:2.5em;
}
h2{
font-size:2em;
position: relative;
left:250px;
display: block;
}
h3{
font-size:1.75em;
position: relative;
left: 250px;
display: block;
}
</style>
</head>
<body>
<center>
<h1>Programing Clicker</h1>
<hr>
</center>
<h2>Skill</h2>
<h3 id="skill_show"></h3>
<h2>Money</h2>
<h3 id = "moneyShow"></h3>
<h2>Language</h2>
<br>
<br>
<p id="timer"></p>
<button onClick = "scriptMake()">Make a script</button>
<script>
var money = 1;
var skill = 1;
var language = 1;
var scriptTime = 100/skill;
var scriptTime2 = scriptTime;
function scriptMake(){
for(var x = 100,x >= 0, x += skill){
document.getElementById("timer").innerHTML = x;
}
}
setInterval(
function showvars(){
document.getElementById("skill_show").innerHTML = skill;
document.getElementById("moneyShow").innerHTML = money;
},1
)
</script>
</body>
your problem is here
for(var x = 100,x >= 0, x += skill){
You need semicolons instead of commas like so
for(var x = 100;x >= 0; x += skill){
Depending on which browser you are using to view the game, look up how to open the console in the browser. It will help you debug these things in a second.

Remove <div> elements created by Javascript by using javascript

My code atm looks like this:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Oppgave 2</title>
<style type="text/css">
div{
width: 100px;
height: 100px;
background-color: rgb(100, 100, 100);
margin: 5px;
float: left;
}
</style>
</head>
<body>
<label>
<ul>
<li>Antall <input id="numberFigInput" type="text"></li>
</ul>
</label>
<input id="genFigBtn" type="button" value="Generate">
<input id="removeFigBtn" type="button" value="Remove All">
<section id="myFigures"></section>
<script>
var numberFig, genFigBtn, myFigures;
function init(){
numberFigInput = document.getElementById("numberFigInput");
myFigures = document.getElementById("myFigures");
genFigBtn = document.getElementById("genFigBtn");
removeFigBtn = document.getElementById("removeFigBtn");
genFigBtn.onclick = genFigures;
removeFigBtn.onclick = removeFigures;
}
function genFigures(){
var numberFig = numberFigInput.value;
if (numberFig > 0, numberFig < 1001){
for(var amount = 0; amount < numberFig; amount++){
myFigures.innerHTML += "<div></div>"
}
}else{
alert("You have to input an integer over 0, but not over 1000!");
}
}
function removeFigures(){
}
init();
</script>
</body>
</html>
So what I want, is for the remove-button to remove the divs that im creating. Ive been googling around and have tried alot of different codes, cant seem to get it to work..
In your specific situation, you have two basic choices:
Just set innerHTML on the element to "":
myFigures.innerHTML = "";
It's slower than some alternatives, but you're not doing this in a tight loop, and it's easy.
Use a loop with removeChild:
while (myFigures.firstChild) {
myFigures.removeChild(myFigures.firstChild);
}
See this other SO answer for information comparing the two techniques.
Here's that first option in context:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Oppgave 2</title>
<style type="text/css">
div{
width: 100px;
height: 100px;
background-color: rgb(100, 100, 100);
margin: 5px;
float: left;
}
</style>
</head>
<body>
<label>
<ul>
<li>Antall <input id="numberFigInput" type="text"></li>
</ul>
</label>
<input id="genFigBtn" type="button" value="Generate">
<input id="removeFigBtn" type="button" value="Remove All">
<section id="myFigures"></section>
<script>
var numberFig, genFigBtn, myFigures;
function init(){
numberFigInput = document.getElementById("numberFigInput");
myFigures = document.getElementById("myFigures");
genFigBtn = document.getElementById("genFigBtn");
removeFigBtn = document.getElementById("removeFigBtn");
genFigBtn.onclick = genFigures;
removeFigBtn.onclick = removeFigures;
}
function genFigures(){
var numberFig = numberFigInput.value;
if (numberFig > 0, numberFig < 1001){
for(var amount = 0; amount < numberFig; amount++){
myFigures.innerHTML += "<div></div>"
}
}else{
alert("You have to input an integer over 0, but not over 1000!");
}
}
function removeFigures(){
myFigures.innerHTML = "";
}
init();
</script>
</body>
</html>
Like T.J. Crowder said,
myFigures.innerHTML = "";
would work. However, that assumes that myFigures is empty when your DOM is initially loaded. If that is NOT the case, you need to add a class to the div when you create it.
AddDiv function:
function genFigures(){
var numberFig = numberFigInput.value;
if (numberFig > 0, numberFig < 1001){
for(var amount = 0; amount < numberFig; amount++){
myFigures.innerHTML += "<div class='AddedDiv'></div>"
}
}else{
alert("You have to input an integer over 0, but not over 1000!");
}
}
To remove them:
$(".AddedDiv").each(function(){
$(this).parentNode.removeChild($(this));
});

Javascript Form Not Returning Values

It looks good, but it's not returning any values.
Any ideas?
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
<style type="text/css">
.out {
height: 22px;
width: 100px;
border:solid 1px;
margin: 4px;
padding: 3px;
line-height: 22px;
}
form input {
display: block;
}
</style>
</head>
<body>
<form>Number 1
<input type="text" id="firstNumber">Number 2
<input type="text" id="secondNumber">Number 3
<input type="text" id="thirdNumber">
<input type="button" value="Add Total" onclick="addIt()">
<div class="out" id="Total"></div>
<input type="button" value="Multiply Total" onclick="multiply()">
<div class="out" id="multiplyresult"></div>
<input type="button" value="Ave Total" onclick="averesult()">
<div class="out" id="averesult"></div>
</form>
</body>
</html>
<script type="text/javascript">
var result = getId('Total'),
multiplyresult = getId('multiplyresult'),
n1, n2, n3;
function getValues() {
n1 = getId('firstNumber').value, n2 = getId('secondNumber').value, n3 = getId('thirdNumber').value;
}
console.log((n1) * (n2) * (n3));
window.addIt = function() {
getValues();
result.innerText = (+n1) + (+n2) + (+n3);
};
window.multiply = function() {
getValues();
multiplyresult.innerText = (n1) * (n2) * (n3);
};
window.average = function() {
getValues();
averesult.innerText = (n1) + (n2) + (n3) / 3;
};
function getId(x) {
return document.getElementById(x);
}
</script>
I also was trying to figure out how to return and average value of the three numbers.
But as I am a total novice, I do not know how to do this.
The add and multiply functions are now working, but not the average.
Thanks in advance.
The average has to be calculated like so:
window.average = function() {
getValues();
averesult.innerText = ((n1) + (n2) + (n3)) / 3; //Note brackets around n1->n3
};
And your call to averesult() needs to be changed to average()
The problem is that you ran the script as soon as the page loaded, before all the elements had loaded. Because of that, you were trying to access elements that did not exist yet, and would not exist until the page had finished loading. This can be solved in one of two ways. The first way is wrapping it in a window.onload, and the second way is just moving the <script></script> tags to the end of the <body>

Categories