Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change css property using jquery with this code

Tags:

jquery

css

"#business" is currently set to background: #323232; How can I change it to #000; after I click on "#business" and back to 323232 once the menu is closed?

$(document).ready(function() {

    $("#business").click(function(){
        jQuery.fx.off = true;
        $("#businessmenu").toggle("");
    });

    $('html').click(function() {
        $("#businessmenu").hide("");
    });

    $('#business').click(function(event){
        event.stopPropagation();
    });

});

Here is the html:

<a href="#" id="business">Biz name</a>
<div id="businessmenu">
    <a href="help.html">Help</a>
</div>
like image 225
Josh Avatar asked Feb 14 '12 23:02

Josh


People also ask

Can we change CSS properties value using JavaScript and jQuery?

css('opacity', '0.2'); Finally, setting multiple css properties with jQuery can be done by passing in a javascript object. The key is name of the css property, and the value will be the css value.

How do you change the style of an element using jQuery?

The css() method in JQuery is used to change the style property of the selected element.

What is the jQuery syntax to get the value of a CSS property?

css() Get the value of a computed style property for the first element in the set of matched elements or set one or more CSS properties for every matched element.


2 Answers

You can use the css method to change a CSS property (or multiple properties if necessary):

$("#business").click(function(event){
    jQuery.fx.off = true;
    $("#businessmenu").toggle("");
    $(this).css("background-color", "#000");
    event.stopPropagation();
});
$('html').click(function() {
    $("#businessmenu").hide();
    $("#business").css("background-color", "#323232");
});

Note that I've combined the 2 event listeners you had bound to #business as it's makes no difference to just bind the one.

As a side note, is there a reason you are passing an empty string to hide? That shouldn't be necessary.

like image 121
James Allardice Avatar answered Nov 08 '22 10:11

James Allardice


If you want to change the background of an element (in your case "#business") to a color, you simply do:

$("#business").css({
     "background": "#000"
});

But I am not sure what you mean by the "menu", you should probably show us the code of your HTML!

like image 40
Rorchackh Avatar answered Nov 08 '22 09:11

Rorchackh