Closure in javascript seems not working properly - javascript

I've the following code and it is not working properly. My aim is whenever i click the 'font size' such as 12, 14 and 16, then, the font size and its color need to change accordingly and simultaneously. But, it is not working as expected, Any help?
<body>
<p>Some paragraph text</p>
<h1>some heading 1 text</h1>
<h2>some heading 2 text</h2>
12
14
16
<script type="text/javascript">
function makeSizer(size) {
return function(oclor) {
document.body.style.fontSize = size + 'px';
document.body.style.color = oclor;
};
}
var a= "green", b= "blue", c="red";
var size12 = makeSizer(12)(a);
var size14 = makeSizer(14)(b);
var size16 = makeSizer(16)(c);
document.getElementById('size-12').onclick = size12;
document.getElementById('size-14').onclick = size14;
document.getElementById('size-16').onclick = size16;
</script>
</body>

This is where your problem is.
You're setting the variables to the result of the anonymous function. Which is undefined.
Then you're setting the onclick events to the results.
var size12 = makeSizer(12)(a);
var size14 = makeSizer(14)(b);
var size16 = makeSizer(16)(c);
document.getElementById('size-12').onclick = size12;
document.getElementById('size-14').onclick = size14;
document.getElementById('size-16').onclick = size16;
What you want is to set the variables to functions as well. Such as:
var size12 = function(){makeSizer(12)(a)};

Is there a reason why you can't do the following?
Edit: Sorry, missed the return function. Thanks for pointing that out #DanielKnippers
function makeSizer(size,oclor) {
return function () {
document.body.style.fontSize = size + 'px';
document.body.style.color = oclor;
};
}
var size12 = makeSizer(12,'green');
var size14 = makeSizer(14,'blue');
var size16 = makeSizer(16,'red');

Related

How to make fontSize of text area increase by 2 in javascript?

I have textarea that I want to add 2 to its text font size every time a button is clicked. I wrote this code but not working.
My HTML code is
function makebold() {
alert(document.getElementById("input-text").style.fontSize);
var currentfontsize = document.getElementById("input-text").style.fontSize;
console.log(currentfontsize);
var current = parseInt(currentfontsize);
console.log(current);
var updatedfontsize = current + 2;
console.log(updatedfontsize);
var newfont = updatedfontsize;
console.log(newfont);;
document.getElementById("input-text").style.fontSize = newfont;
}
<fieldset>
<legend>Text</legend>
<textarea name="input-text" id="input-text" cols="30" rows="4"></textarea>
</fieldset>
<fieldset>
<legend>Decoration</legend>
<button id="button1" onclick="makebold()">Bigger Decorations!</button><br>
<input type="checkbox" onclick="displayalert()" name="bling" id="bling" value="Bling">Bling
</fieldset>
Can anyone please help?
Use this way to get the font size:
var currentfontsize = window.getComputedStyle(document.getElementById("input-text")).fontSize;
And update your last line
document.getElementById("input-text").style.fontSize = newfont+'px';
You are not adding px to the font. Without px it won't work.
Working Fiddle
https://jsfiddle.net/3napv795/
function increaseFont(elem, inc) {
const val = window.getComputedStyle(elem).getPropertyValue("font-size"); // gets font-size in string format
const currentSize = parseFloat(val); // removes 'px'
elem.style.fontSize = currentSize + inc + "px"; // set new size by adding increment to current font size
}
Usage:
const button = document.getElementById("button1");
button.addEventListener("click", () => increaseFont(button, 2))
Adding an initial font-size will solve the problem:
function makebold(){
alert(document.getElementById("input-text").style.fontSize);
//add initial font-size
document.getElementById("input-text").style.fontSize = '10px';
var currentfontsize = document.getElementById("input-text").style.fontSize;
console.log(currentfontsize);
var current = parseInt(currentfontsize);
console.log(current);
var updatedfontsize = current + 2;
console.log(updatedfontsize);
var newfont = updatedfontsize;
console.log(newfont);;
document.getElementById("input-text").style.fontSize = newfont;
}
Correcting your code while updating to a newer syntax ....
JS
const textarea = document.getElementById("input-text");
function makebold() {
let fontUnit = "px"; // setting a unit for font size
let increment = 2; // increase the font size by 2 px/rem/em etc ..
// Getting current font size
let currentfontsize = window.getComputedStyle(textarea).fontSize;
currentfontsize = parseInt(currentfontsize);
// getting final value
const updatedfontsize = currentfontsize + increment + fontUnit;
textarea.style.fontSize = updatedfontsize;
}

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

Add multiple label dynamically in html page using javascript

I used following code for adding label dynamically.
var array_resp=[CorrectStreet,CorrectCity,CorrectState,CorrectZip];
// var stateName=map.getKey(CorrectState);
if(array_resp.length > 0) {
var answers = [];
for(var i = 0; i <= array_resp.length - 2; i++) {
answers[i] = document.createLabel({
color : '#000',
text : array_resp[i],
top : top,
left : '30 px',
width : '420 px',
height : '100 px',
visible : 'true',
backgroundColor : 'white',
font : FontNormal,
});
document.body.appendChild(answers[i]);
}
}
in html:-
<button onclick="myFunction()">Try it</button>
But it doesn't give correct output,when I am click on button.
Why it happen? Can someone help me please.
Some issues in your code:
There are no function of createLabel for creating LABEL element
To assign the style / properties in wrong way, never in object type
There is no SPACE between 30 and px for left, width & height.
Try this:
<body>
<script>
function myFunction(){
var array_resp=['CorrectStreet','CorrectCity','CorrectState','CorrectZip'];
// var stateName=map.getKey(CorrectState);
if(array_resp.length > 0) {
for(var i = 0; i <= array_resp.length - 2; i++) {
var label = document.createElement('label');
label.style.color = '#000';
label.style.top = 'top';
label.style.left = '30px';
label.style.width = '420px';
label.style.height = '100px';
label.style.visible = 'true';
label.style.backgroundColor = 'white';
label.style.font = 'FontNormal';
label.innerHTML = array_resp[i];
document.body.appendChild(label);
}
}
}
</script>
<button onclick="myFunction()">Try it</button>
</body>

setInterval function using innerHTML not updating

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.

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