Sunday, February 3, 2019

How to define multiple CSS attributes in jQuery?



Is there any syntactical way in jQuery to define multiple CSS attributes without stringing everything out to the right like this:



$("#message").css("width", "550px").css("height", "300px").css("font-size", "8pt");



If you have, say, 20 of these your code will become hard to read, any solutions?



From jQuery API, for example, jQuery understands and returns the correct value for both



.css({ "background-color": "#ffe", "border-left": "5px solid #ccc" }) 


and




.css({backgroundColor: "#ffe", borderLeft: "5px solid #ccc" }).


Notice that with the DOM notation, quotation marks around the property names are optional, but with CSS notation they're required due to the hyphen in the name.


Answer



Better to just use .addClass() even if you have 1 or more. More maintainable and readable.



If you really have the urge to do multiple CSS properties then use the following:




.css({
'font-size' : '10px',
'width' : '30px',
'height' : '10px'
});


NB!
Any CSS properties with a hyphen need to be quoted.
I've placed the quotes so no one will need to clarify that, and the code will be 100% functional.


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...