tags:

views:

98

answers:

4

Hi,

When I change a button's font-weight, the size will also be changed. My problem is that I can't give the button a predefined size, so I tried to fix it with .css('width','-=4px');

But that will not work. Hope somebody can help me.

HTML

<input id="b1" type="button" value="Hello world" />
<input id="b2" type="button" value="Blubba blib" />
<input id="b3" type="button" value="Bl" />
<input id="b4" type="button" value="Blubba 55" />

JS

$('input:button').click(function() {

  $('*').css('font-weight','normal');  
  $(this).css('font-weight','bold');    
  $(this).css('width','-=4px');      

});

Exmaple http://www.jsfiddle.net/V9Euk/618/

Thanks in advance!
Peter

A: 

You should try to set a larger size to your buttons from the start, so that when the text gets bold the size does not change.

GôTô
Can you give me a jsfiddle exmaple please?
Peter
Here: http://www.jsfiddle.net/V9Euk/630/
GôTô
+3  A: 

Edit:

Just add some extra width before making it bold.

$('input:button').width(function(){
    return $(this).outerWidth() + 20;
}).click(function() {
    $(this).css('font-weight', 'bold').siblings().css('font-weight', 'normal');
});

http://www.jsfiddle.net/djhRB/

there you go.

Stefanvds
Hi Stefanvds, your solution did not work :( -> http://www.jsfiddle.net/V9Euk/626/
Peter
Nice, thank you very much!
Peter
I see what you did there - but no, it's not the extra width that's making them hold their size - it's the fact that you're assigning them a fixed width. If you remove the `+ 20px` it'll work just the same. It's basically my solution, but better (though less flexible, if you want to change the contents of the button dynamically), so +1 there. I'm also updating your solution to one that's more efficient, hope you won't mind
Yi Jiang
+1  A: 

Hey Peter.

I got Ur Problem

and U can find out the width of the button and decrease width of that button like bellow.

            $('*').css('font-weight', 'normal');
            $(this).css('font-weight', 'bold');
            var wdth = $(this).width();
            wdth = wdth - 4;
            $(this).css({ width: wdth+'px' });

So When You ll click that button it ll find out the width of button and Decrease the width.

ultimately You can check the font-wight attribute and make it decrease or increase alternately according to your requirement.

Also you can make the size percentage to implement.

Umakanta.Swain
+3  A: 

Before going anywhere with this code you have to give the buttons some padding, so that when the text inside them expand, they don't overflow. This code uses .outerWidth to obtain the correct width and adjust the button accordingly.

$('input:button').click(function() {
    var w = $(this).outerWidth();

    $(this).css({
        'font-weight': 'bold',
        'width': w
    }).siblings().css({
        'width': 'auto',
        'font-weight': 'normal'
    });
});

See: http://www.jsfiddle.net/CegfY/2

Yi Jiang
Thats it! Thanks Yi Jiang!
Peter