4

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> 

2 Answers 2

3

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)

Sign up to request clarification or add additional context in comments.

3 Comments

Looks like the issue is that you are trying to assign the element to x before the DOM is ready. Replacing the script block with the above edit.should work.
A lot of remarks in the answer but not what was really important it's not there. A pity.
@Alexander - Did i miss out any important detail? Let me know. I'll be happy to add it to the answer.
3

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

1 Comment

You can shorten this function bold(){$(x).toggleClass('bold')}

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.