DJDMorrison
DJDMorrison

Reputation: 1319

Toggle Elements FontWeight - Javascript

I'm trying to make it so that the text inside a text area can be toggled to be bold or not, by pressing a button. I have the following code:

function bold()
{
    var ta = document.getElementById("textArea");

    if(ta.style.fontWeight == "normal"){
        ta.style.fontWeight = "bold";
    }
    else{
        ta.style.fontWeight = "normal";
    }
}

When the I press the button, nothing happens the first time. But I press it a second time and it runs perfectly. Running it through a debugger, the variable "ta" becomes equal to "" the first time, and then "normal" the second time, despite the text area being set to normal in the css.

Any ideas?

Thanks

Upvotes: 1

Views: 256

Answers (2)

jdcantrell
jdcantrell

Reputation: 2631

So the reason this is happening is because ta.style is accessing the style attribute of the textarea element, which will not have any information about styles coming from CSS. You could write your textarea like this, and it should work with what you have:

<textarea id="textArea" style="font-weight:normal"></textarea>

But, I'd recommend you do something along these lines in your js:

function bold()
{
    var ta = document.getElementById("textArea");

    if(ta.style.fontWeight !== "bold"){
        ta.style.fontWeight = "bold";
    }
    else{
        ta.style.fontWeight = "normal";
    }
}

Might also be helpful to rename your function to toggleBold ;)

Upvotes: 2

Explosion Pills
Explosion Pills

Reputation: 191789

Instead of trying to fight it, just change your condition:

if (ta.style.fontWeight == "normal" || ta.style.fontWeight === '') {

Upvotes: 1

Related Questions