Why wont my text update? (HTML + JS) - javascript

I am trying to make text on my site update. The variable in JS does, but the text on screen doesn't. (Yes I know the code is sloppy, I get it to work and then go through and make it pretty.)
<script>
var moneyTotal = 370; //Variable for money, filled with starter money
var moneyText = String(moneyTotal); //Variable for text
var OD2Clicked = 0;
</script>
<script>document.write("<h1 class='money'>Total: $"+ moneyText + "</h1>"); //Line for updating site </script>
<script>
function Check(){ //Function that checks for radio button change
if (document.getElementById('OD2').checked & OD2Clicked==0) {
OD2Clicked = 1;
Adding(20);
console.log("Adding");
}else if(document.getElementById('OD').checked & OD2Clicked>0){
OD2Clicked = 0;
Adding(-20);
console.log("Subtracting");
}
setTimeout(function() {Check()}, 5000);
}
function Adding(m1){ //Function for adding
moneyTotal += m1;
moneyText = String(moneyTotal);
console.log(moneyTotal);
console.log(moneyText+" Text");
}
</script>

Just like I mentioned above in the comment:
Your screen write happens only once when Browser will parse all tags. You need to update your text on the screen every time you modify the value.
Would this work for you?
<script>
var moneyTotal = 370; //Variable for money, filled with starter money
var OD2Clicked = false;
var timeoutPeriod = 5000;
</script>
<script>document.write("<h1 class='money'>Total: $0</h1>"); //Line for updating site </script>
<script>
function Check(){ //Function that checks for radio button change
if (document.getElementById('OD2').checked) {
if (!OD2Clicked) {
OD2Clicked = true;
moneyTotal += 20;
console.log('Adding');
} else if (OD2Clicked) {
OD2Clicked = false;
moneyTotal -= 20;
console.log('Subtracting');
}
// Find DOM element we need to update
document
.querySelectorAll('.money')[0]
.textContent = 'Total: $' + moneyTotal;
}
setTimeout(Check, timeoutPeriod);
}
</script>

Related

How do I change an HTML element with incrementing values?

When I go on the page, I have 0 cookies to start with. I made an if statement saying if there are less than 10 cookies, hide the upgrade button. I'm clicking and incrementing the value by 1. Once I reach 10 cookies, how do I get the upgrade button to show? Would it be with an event listener or what?
var cookies = 0;
var cookieClick = 1;
function getCookie() {
cookies += cookieClick;
document.getElementById('cookieCount').innerHTML = cookies;
document.getElementById('img').style.visibility = 'visible';
}
if (cookies < 10) {
document.getElementById('up').style.visibility = 'hidden';
}
function upgrade() {
cookieClick *= 2;
document.getElementById('up').style.visibility = 'hidden';
alert('You have x2 the clicks!')
}
Your if (cookies < 10) { isn't part of any function, so it'll only run once on page load. You probably want to include it in your getCookie() function instead, with an else to show the upgrade button when needed.
function getCookie() {
cookies += cookieClick;
document.getElementById('cookieCount').innerHTML = cookies;
document.getElementById('img').style.visibility = 'visible';
if (cookies < 10) {
document.getElementById('up').style.visibility = 'hidden';
} else {
document.getElementById('up').style.visibility = 'visible';
}
}
(But if the cookie value never decreases, you could simplify this a bit by just loading the page with the element hidden initially and only check for cookies > 10 to reveal it.)
Yes, an onClick event listener could check your current cookie count and toggle your upgrade button for visibility.
<button onclick="incrementCount()"> b1 </button>
<button id="b2" style="visibility:hidden" onclick="something()">b2</button>
<script>
var cookies = 0;
var cookieClick = 0;
function incrementCount(){
cookieClick = cookieClick + 1;
console.log(cookieClick)
if(cookieClick == 10){
document.getElementById('b2').style.visibility = "visible"
}
}
function something(){
alert('i work')
}
</script>
You can try this simple piece of code.

jQuery nicescroll is not working with dynamic content and other JavaScript function that makes random effect

So here is the thing, I have a sidebar that has big height due the lots of navigation links. And I'm using jQuery nicescroll plugin to make it look fine. In the sidebar I also have h3 tag which makes a random effect of showing letters (see the code) every 4 seconds. So, when it's on - scroll is not working at all for these 4 seconds and you can't do any scrolling. I tried to use $("#sidebar").getNiceScroll().resize() but it doesn't work either. Is there any way to make it work?
<div id="sidebar">
<h3 id="output">Random</h3>
</div>
//Calling for nicescroll function for my sidebar
$(function(){
$("#sidebar").niceScroll({ cursorcolor:"#66aee9", cursorfixedheight: 400 });
})
//Random effect for my h3 tag
setInterval(function(){
$(document).ready(function(){
var theLetters = "abcdefghijklmnopqrstuvwxyz#%&^+=-"; //You can customize what letters it will cycle through
var ctnt = "Random"; // Your text goes here
var speed = 50; // ms per frame
var increment = 8; // frames per step. Must be >2
var clen = ctnt.length;
var si = 0;
var stri = 0;
var block = "";
var fixed = "";
//Call self x times, whole function wrapped in setTimeout
(function rustle (i) {
setTimeout(function () {
if (--i){rustle(i);}
nextFrame(i);
si = si + 1;
}, speed);
})(clen*increment+1);
function nextFrame(pos){
for (var i=0; i<clen-stri; i++) {
//Random number
var num = Math.floor(theLetters.length * Math.random());
//Get random letter
var letter = theLetters.charAt(num);
block = block + letter;
}
if (si == (increment-1)){
stri++;
}
if (si == increment){
// Add a letter;
// every speed*10 ms
fixed = fixed + ctnt.charAt(stri - 1);
si = 0;
}
$("#output").html(fixed + block);
block = "";
}
});
}, 4000);
I change to rows and check it in jsfiddle, looks like working scroll fine.
Before:
setInterval(function(){
$(document).ready(function(){
...
});
}, 4000);
After:
$(document).ready(function(){
setInterval(function(){
...
}, 4000);
});

Display dynamic values in javascript alertbox

Display dynamic value in confirm box. This is how i wanted it to work but it didnt. Can anyone tell me how it is done properly.
<script type='text/javascript'>
setTimeout(function(){
var url = document.URL;
var r = confirm("Your session is about to be timedout in " + for (var i = 10; i > 0; i--){ i } + " seconds! Would you like to logged in?");
if (r == true) {
location = url;
} else {
location = '../logoff.php'
}
}, 10000)
</script>
Aside from the flawed string concatenation logic, you cannot achieve this in a standard confirm box. The value is set when the box is instantiated and cannot be changed.
To do what you need you would need to use a modal plugin of some description which you have HTML/JS control over.
This is a work around example:
$(function() {
var out = $('#out'),
sec;
(function() {
var th = setInterval(function() {
sec = parseInt(out.text()) || 0;
if (!sec) {
clearInterval(th);
timeout();
} else {
sec--;
out.text(sec);
}
}, 1000);
})();
var timeout = function() {
if ($('#in').prop('checked')) {
alert('login ...');
} else {
alert('don\'t login ...');
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<center>
<h2>Your session is about to be timedout in <span id="out">10</span> seconds! Would you like to logged in?
<br/>
<input type='checkbox' id='in'/>Yes
</h2>
</center>

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
}

Can you count clicks on a certain frame in an animation in javascript?

I'm looking to build a very simple whack a mole-esque game in javascript. Right now I know how to do everything else except the scoring. My current animation code is as follows
<script language="JavaScript"
type="text/javascript">
var urls;
function animate(pos) {
pos %= urls.length;
document.images["animation"].src=urls[pos];
window.setTimeout("animate(" + (pos + 1) + ");",
500);
}
window.onload = function() {
urls = new Array(
"Frame1.jpg","Frame2.jpg"
);
animate(0);
}
</script>
So far it all works, the first frame is the hole and the second is the groundhog/mole out of the hole. I need to count the clicks on the second frame but I can't figure out how to incorporate a counter. Help? (Sorry if the code doesn't show up correctly, first time using this site)
Here is an example that counts clicks on the flashing animation: http://jsfiddle.net/maniator/TQqJ8/
JS:
function animate(pos) {
pos %= urls.length;
var animation = document.getElementById('animation');
var counter = document.getElementById('counter');
animation.src = urls[pos];
animation.onclick = function() {
counter.innerHTML = parseInt(counter.innerHTML) + 1;
}
setTimeout(function() {
animate(++pos);
}, 500);
}
UPDATE:
Here is a fiddle that only detects click on one of the images: http://jsfiddle.net/maniator/TQqJ8/8/

Categories