dav3ydark007
dav3ydark007

Reputation: 54

parseFloat keeps returning NaN when it should be -0.1 or 0.1

parseFloat keeps returning NaN when it should be -0.1 or 0.1 when I print it in console.log, I'm most-likely just getting tired, but I can't see the issue. Any help is greatly appreciated as always, Also not looking for a jQuery answer here, this must be JS

function startUp() {
    var fontButtons = document.getElementsByClassName("fontsizer");
    for (var i=0; i < fontButtons.length; i++) {
    document.getElementsByClassName("fontsizer")[i].addEventListener("click", resizeText);
    }
};

window.onload = startUp;

function resizeText() {
    var fontChange = parseFloat(this.value);
    console.log(fontChange);
    if (document.body.style = "") {
        document.body.setAttribute("style", "font-size:1.0em;");
    }
    var currentFontSize = parseFloat(document.body.style.fontSize.replace('em', ''));
    console.log(currentFontSize);
    document.body.style.fontSize = (currentFontSize + fontChange) + "em";
};

and the html

<div id="fontbuttons">
 <input class="fontsizer" value="-0.1" type="image" id="fontdown" alt="-" src="fontdown.png" />
 <input class="fontsizer" value="0.1" type="image" id="fontup" alt="+" src="fontup.png" />
</div>

Upvotes: 0

Views: 182

Answers (3)

SeanCannon
SeanCannon

Reputation: 77986

You have a few problems.

First, setting the attribute to onclick and passing in the callback as a string will use eval to invoke the function and this will point to the global object, so use addEventListener('click', resizeText) instead.


Second, you can't parseFloat on a number with letters like that - strip out the em before parsing:

var currentFontSize = parseFloat(document.body.style.fontSize.replace('em', ''));

Third, you're concatenating instead of adding. Change

document.body.style.fontSize = currentFontSize + fontChange + "em"

to

document.body.style.fontSize = (currentFontSize + fontChange) + "em"

Working demo : http://jsfiddle.net/8tv550us/

Upvotes: 1

Paul S.
Paul S.

Reputation: 66334

Add an event listener rather than setting an attribute and this will point to the correct object

document.getElementsByClassName("fontsizer")[i].addEventListener("click", resizeText);

Upvotes: 0

Liam Schauerman
Liam Schauerman

Reputation: 841

I believe this.value within your resizeText() function is where your error lies. what do you think 'this' is referring to here? I think it will be the window object at the moment.

Upvotes: 1

Related Questions