Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set css attribute in onclick event

I have a problem with set fontStyle attribute to single element(by id) in popover. I get onClick event, put style (bold font style) to all class elements and then try to put another style(normal) to one(clicked) element. My code is:

$(document).on('click', '.listElement', function () {
    $('.listElement').css('font-weight', 'bold');
    alert(this.id);
    $(this).css('font-weight', 'normal');
});

There is a demo

Setting bold style for all class elements works and dialog shows correctly id so this is right element(in this) but .css() method doesn't work. I tried to put style by using id like:

$('#A').css('font-weight', 'normal');

and there is no error in console but it doesn't work as well. Is there any other way to set fontStyle to single unique element?

like image 656
barmi Avatar asked Oct 29 '22 09:10

barmi


1 Answers

Rather than removing CSS styling why not just never add it to the clicked object??

Get the ID of the clicked object and use that...

$(document).on('click', '.listElement', function () {
var clickEl = this.id; //ID of clicked object
$('.listElement').not('#' + clickEl).css('font-weight', 'bold'); //bolds everything which is NOT the clicked item.
alert(this.id);
});

or

$(document).on('click', '.listElement', function () {
$('.listElement').not('#' + this.id).css('font-weight', 'bold'); //bolds everything which is NOT the clicked item.
alert(this.id);
});

Updated Fiddle


if there is a specific reason you need to remove the styling rather than never applying it...

$(document).on('click', '.listElement', function () {
$('.listElement').css('font-weight', 'bold');
alert(this.id);
$('.listElement#' + this.id).css('font-weight', 'normal');
});

Fiddle for that

like image 88
Scott Avatar answered Nov 15 '22 05:11

Scott