user2371301
user2371301

Reputation: 3474

Button that makes textarea text bold

I have a button that has an onclick="bold()" and it is supposed to be changing the font weight from normal to bold and then back to normal. It isn't doing anything though. What do I need to change or add? Here is a jsfiddle if that helps: http://jsfiddle.net/dZVfh/

<script>
    var x = document.getElementById('description-box');
    function bold() {
      if( $(x).css("font-weight") == "normal") {
        $(x).css("font-weight"), "bold");
      }
      else {
        $(x).css("font-weight", "normal");
      }
    }
  </script>

Upvotes: 4

Views: 2063

Answers (2)

yeahman
yeahman

Reputation: 2767

i prefer to have it change class :

add this style

.bold{
    font-weight: bold;
}

change your function :

function bold(){
  if( $(x).hasClass("bold")) {
     $(x).removeClass("bold");
  }
  else {
    $(x).addClass("bold");
  }
}

Upvotes: 3

techfoobar
techfoobar

Reputation: 66663

There is a syntax error in your code:

Change

$(x).css("font-weight"), "bold");

to

$(x).css("font-weight", "bold");


Full function

function bold() {
    var x = $('#description-box');
    if (x.css("font-weight") !== "bold") {
        x.css("font-weight", "bold");
    } else {
        x.css("font-weight", "normal");
    }
}

Working fiddle: http://jsfiddle.net/dZVfh/3/

There were a number of problems in your original fiddle.

  • jQuery was not being included

  • The function was defined inside domReady - which means it isn't visible when clicking the button

  • The CSS block had a syntax error. The style was being closed with a ) instead of a }

  • You were trying to assign the element to x before the DOM was ready. The new fiddle does this inside the function (by which time the DOM is ready)

Upvotes: 3

Related Questions