setInterval function using innerHTML not updating - javascript

I just can't seem to wrap my head around why this will not update what is displayed in the output. I've made a jsfiddle for anyone to look at.
http://jsfiddle.net/sQrn7/
and here's the code:
function getPrices(basePrice){
var dogeValue = 0.005343614; //When changed the output should change.
var postage = 0.49/dogeValue;
var sellAmount = (basePrice/dogeValue - postage) - (basePrice*0.1/dogeValue);
rounded = Math.round(sellAmount);
document.getElementById("txt").innerHTML = rounded;
}
var timer = setInterval(function() { getPrices(10) }, 1000);
Original/complete code:
<html>
<script>
var rounded = 0;
function getPrices(basePrice){
var dogeValue = <?php echo(file_get_contents("https://www.dogeapi.com/wow/?a=get_current_price")); ?>;
var postage = 0.49/dogeValue;
var sellAmount = (basePrice/dogeValue - postage) - (basePrice*0.1/dogeValue);
rounded = Math.round(sellAmount);
document.getElementById("txt").innerHTML = rounded;
}
var timer = setInterval(function() { getPrices(10) }, 1000);
</script>
<body onload="getPrices(10);">
<div id="txt"></div>
</body>

The PHP part is executed only once on page load. Take a look at the source code (right click on the page, "show source code"), you'll see the value assigned statically, since it's generated with PHP before the page is loaded into the browser. Keep in mind that Javascript and PHP are executed in separated contexts : PHP > server side, Javascript > client side.
A little help to resolve your problem : http://www.w3schools.com/ajax/.

If you take a look at the console, it will say Uncaught ReferenceError: sellAmount is not defined
The reason: you are missing space at the definition of the variable sellAmount: you wrote varsellAmount = ...
Use this, and it will work:
function getPrices(basePrice){
var dogeValue = 0.005343614; //When changed the output should change.
var postage = 0.49/dogeValue;
var sellAmount = (basePrice/dogeValue - postage) - (basePrice*0.1/dogeValue);
var rounded = Math.round(sellAmount);
document.getElementById("txt").innerHTML = rounded;
}
var timer = setInterval(function() { getPrices(10) }, 1000);
See your updated feedle here: http://jsfiddle.net/sQrn7/
EDIT: after your edited Question, see this fiddle: http://jsfiddle.net/Ne2gN/
The output is always the same, because the value of the dogeValue always stays the same. You have to change the value, in order to see a change in the output.
This is the new code:
var dogeValue = 0.005343614; //When changed the output should change.
function getPrices(basePrice){
var postage = 0.49/dogeValue;
var sellAmount = (basePrice/dogeValue - postage) - (basePrice*0.1/dogeValue);
var rounded = Math.round(sellAmount);
document.getElementById("txt").innerHTML = rounded;
dogeValue+=0.1;
}
var timer = setInterval(function() { getPrices(10) }, 1000);
Edit 2: After your question-edit, the answer stays the same - you can still define it globally:
<html>
<script>
var rounded = 0;
var dogeValue = <?php echo(file_get_contents("https://www.dogeapi.com/wow/?a=get_current_price")); ?>;
function getPrices(basePrice){
var postage = 0.49/dogeValue;
var sellAmount = (basePrice/dogeValue - postage) - (basePrice*0.1/dogeValue);
rounded = Math.round(sellAmount);
document.getElementById("txt").innerHTML = rounded;
dogeValue+=0.1; //change it
}
var timer = setInterval(function() { getPrices(10) }, 1000);
</script>
<body onload="getPrices(10);">
<div id="txt"></div>
</body>
You can place your php-Tags everywhere in your code - it doesn't matter if they are inside our outside a function. This code does exacly the same as yours, with the only difference, that getPrices() is now able to change the dogeValue.

Related

I want to update an article every 5 minutes with javascript, can't get it to work

I'm have been trying to get a single article on my website and have it swtich to another article on interval. I'm using flask to scrape the arcile title,image and text from 3 different source. Then I render a template with those elements in a list.
See code:
#app.route('/test')
def hello_world():
offshorenergyfeed = feedparser.parse('https://feeds.feedburner.com/OffshoreEnergyToday?format=xml')
offshorewindfeed = feedparser.parse('http://feeds.feedburner.com/OffshoreWindNews?format=xml')
rechargefeed = feedparser.parse('http://www.rechargenews.com/rss/')
feedlinks = [offshorenergyfeed.entries[0]['link'],offshorewindfeed.entries[0]['link'],rechargefeed.entries[0]['link']]
artikel_tekst = []
artikel_titel = []
artikel_image = []
for link in feedlinks:
artikel = Article(link)
artikel.download()
artikel.parse()
artikel_tekst.append(artikel.text)
artikel_titel.append(artikel.title)
artikel_image.append(artikel.top_image)
return render_template('graph.html',
artikel_tekst = artikel_tekst,
artikel_titel = artikel_titel,
artikel_image = artikel_image,
)
Now I want to I want to display 1 article at the time and swtich it to another with an interval(lets say 5 minutes). For some reason I can only get it to work with the title switch. Text and Image won't switch with the given code:
<div id=newsarticle_container>
<h1 id='titel'>{{artikel_titel[0]}}</h1>
<img id=plaatje src="{{artikel_image[0]}}">
<div id='tekst'>{{artikel_tekst[0]}}</div>
</div>
<script>
var titles = ["{{artikel_titel[0]}}", "{{artikel_titel[1]}}", "{{artikel_titel[2]}}"];
var images = ["{{artikel_image[0]}}", "{{artikel_image[1]}}", "{{artikel_image[2]}}"];
var text = ["{{artikel_tekst[0]}}", "{{artikel_tekst[1]}}", "{{artikel_tekst[2]}}"];
var counter = 0;
var elem1 = document.getElementById("titel");
var elem2 = document.getElementById("plaatje");
var elem3 = document.getElementById("plaatje");
var inst = setInterval(change, 2000);
function change() {
elem1.innerHTML = titles[counter];
elem2.innerHTML = images[counter];
elem3.innerHTML = text[counter];
counter++;
if (counter >= titles.length) {
counter = 0;
}
}
</script>
Can someone please help me out. I have been struggeling on this for a long time. I think i'm close to the solution but maybe it's needs to be way different. Let me know.
Thanks in advance!
you have
<h1 id='titel'>{{artikel_titel[0]}}</h1>
<img id=plaatje src="{{artikel_image[0]}}">
<div id='tekst'>{{artikel_tekst[0]}}</div>
which should be
<h1 id='titel'>{{artikel_titel[0]}}</h1>
<img id='plaatje' src="{{artikel_image[0]}}">
<div id='tekst'>{{artikel_tekst[0]}}</div>
later in your code you have
var elem1 = document.getElementById("titel");
var elem2 = document.getElementById("plaatje");
var elem3 = document.getElementById("plaatje");
which should be changed to
var elem1 = document.getElementById("titel");
var elem2 = document.getElementById("plaatje");
var elem3 = document.getElementById("text");

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);
});

Different intervals between images

I am studying for GCSE computing and need to be able to change the interval between different images. My code at the moment looks something like this...
<!DOCTYPE html>
<html>
<body>
<h1> Traffic lights can change on their own </h1>
<img src="RED.jpg" id= "traffic" width="155" height="198">
<script>
var myImage = document.getElementById("traffic");
var imageArray = ["RED.jpg", "RED-ORANGE.jpg", "GREEN.jpg", "ORANGE.jpg"];
var imageIndex = 0;
function changeImage()
{
myImage.setAttribute("src",imageArray[imageIndex]);
imageIndex++;
if (imageIndex >= imageArray.length) {
imageIndex = 0;
}
}
setInterval(changeImage,1000);
</script>
</body>
</html>+
If you could include some of this code whilst changing the intervals that would be ideal.
Supposing you want to solve this using Javascript only:
Source documentation
// Save the var timeoutID = window.setTimeout(code, [delay]);
var imageTimers = [500, 1000, 2000, 4000];
var timeTochange = Math.random() * 3000; // or whatever you want to use...
var aTimer = setTimeout(changeImage, timeTochange);
// On the changeImage, alter the timeTochange var.
function changeImage() {
// ...stuffs...
clearTimeout(aTimer);
timeTochange = imageTimers[imageIndex];
aTimer = setTimeout(changeImage, timeTochange);
}

How do you make a Variable decrease every time a button is clicked by the value of another Variable in JavaScript?

I'm trying to make a button that decreases a variable-defined number by another variable-defined number every time it's clicked.
Example:
[Button]
Number: 500
*Button Clicked
[Button]
Number: 475
*Button Clicked Again
[Button]
Number: 450
And so on..
I'd love to give code and what not but I can't even get it close to working so that would be useless..
The code could look like this:
var count = 500;
var decrementAmount = 25;
function reduceVariable() {
count -= decrementAmount;
}
Then, just call reduceVariable from your button click.
See this jsfiddle
HTML:
<div id="text">500</div>
<p><input type="button" id="button" value="Decrease me"></p>
Javascript:
var oButton = document.getElementById("button");
var oText = document.getElementById("text");
var count = 500;
oButton.addEventListener('click', function(i, a) {
oText.innerHTML = count -= 25;
}, false);
Try this as example:
HTML:
<span id="spnTest">500</span>
<button id="btnTest" >Decrease</button>
Javascript:
var ratio = 25;
var totalValue = 500;
function decrease(){
if(totalValue == 0) return;
totalValue -= ratio;
document.getElementById('spnTest').innerHTML = totalValue;
}
document.getElementById('btnTest').onclick = function(){ decrease(); }
Here is demo

Displaying a value on chrome

Hello i am trying to create a simple button game and i cannot get the value to be displayed on my chrome window.
here is my code and i'm trying to display the amount of money by using console.log().
<button type="sheep" onclick="BuySheep(1)>
Sheep: <span id"Sheep">0</span><br />
Cost: <span id"SheepCost">10</span>
<var sheep = 0;>
function BuySheep(){
var SheepCost = Math.floor(10*Math.pow(1.1,Sheep));
if(Sheep >= SheepCost){
Sheep = Sheep + 1;
Money = Money - SheepCost;
document.getElementById('Sheep').innerHTML = Sheep;
document.getElementById('Money').innerHTML = Money;
};
var nextCost = Math.floor(10*Math.pow(1.1,Sheep));
document.getElementById('Money').innerHTML = nextCost;
window.setInterval(function(){
MoneyClick(Sheep);
console.log(Money);
}, 1000);
the main problem is that ur script is not in js section.
You should separate your html from your script.
You can write it in separate js file or include it by adding
<script type="text/javascript"src="scriptNameHere.js"></script>
in the head section or by wrapping it with tag like this
<script>
function BuySheep(x){
...
}
</script>
<button type="sheep" onclick="BuySheep(1)>
Sheep: <span id"Sheep">0</span><br />
Cost: <span id"SheepCost">10</span>
<script type="text/javascript">
var sheep = 0;
function BuySheep(){
var SheepCost = Math.floor(10*Math.pow(1.1,Sheep));
if(Sheep >= SheepCost){
Sheep = Sheep + 1;
Money = Money - SheepCost;
document.getElementById('Sheep').innerHTML = Sheep;
document.getElementById('Money').innerHTML = Money;
};
var nextCost = Math.floor(10*Math.pow(1.1,Sheep));
document.getElementById('Money').innerHTML = nextCost;
window.setInterval(function(){
MoneyClick(Sheep);
console.log(Money);
}, 1000);
</script>
I stripped down your project to bare necessities and made a Fiddle for you to work on it.
Fiddle Here
var Sheep = 0;
var Money = 100;
var SheepCost = 10;
function BuySheep() {
Sheep++;
$('#Sheep').html(Sheep);
Money = Money - SheepCost;
}
window.setInterval(function () {
console.log(Money);
}, 1000);
Apart from all the errors listed in my comments above, you were using variables that weren't even declared.

Categories