March 2, 2012

Press button to "Bold" & press again to "Unbold"

Question by Jhon

I am new to javascript. I want to make a button in html using javascript. When user try to press the button
the specific <#id> is going to be “Bold” and press again to “Unbold”.

How can I do this ? please refer any helping material.
Thanks !

Answer by Purmou

Since the learning experience is vital, especially for Javascript, I’ll guide you in the right direction.

First, you should look into event binding and mouse event handling with jQuery. You can do some powerful stuff with this knowledge, including what you would like to do.

Second, look into basic jQuery selectors. It’s not hard to learn the simple CSS-based selectors that you can use to select your desired id.

Third, look at the css() function of jQuery, which falls under jQuery’s CSS category. You can use this to set different properties of elements, including font weight.

Answer by Starx

I am guessing, you are trying to build something like RTE, So, applying class to give bold effect would be better and efficient solution to this.

It can be done as simple as this

$(".boldtrigger").click(function() { //boldTrigger being the element initiating the trigger
    $(".text").toggleClass("bold");  //text being the element to where applied to it.
});

CSS

.bold { font-weight: bold; }

Demo

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!