Monday, April 10, 2017

[jQuery] Methods to assign multiple css values on an element


I have a ugly method to assign multiple css on  an element, but i think there should be a better way.

Sample Code:

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$( document ).ready(function() {        $("#element").css("width","100px").css("height","100px").css("background","blue").css("color","#fff");
    });

</script>
</head>
<body>
    <div id="element">fff</div>
</body>
</html>
I am lucky that find a more readable method provided in stackoverflow provided a pretty method and it works like a charm:

Edited Code version 1:

Pass an object pass to .css() method.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$( document ).ready(function() {
    $("#element").css({"width","100px",
                                   "height","100px",
                                  "background","blue",
                                  "color","#fff"});

});
</script>
</head>
<body>
    <div id="element">fff</div>
</body>
</html>
In this case an object {"width","100px","height","100px","background","blue","color","#fff"} is used as parameter to .css() method.

Edited Code version 2:

Using attr along with style.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$( document ).ready(function() {
    $("#element").attr("style","width:100px; height:100px; background: blue; color:#fff;");
});
</script>
</head>
<body>
    <div id="element">fff</div>
</body>
</html>

Edited Code version 3:

Using .addClass() method.
<html>
<head>
<style>.bluebox { width:100px; height:100px; background: blue; color:#fff; }</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$( document ).ready(function() {
    $("#element").addClass("bluebox");
});
</script>
</head>
<body>
    <div id="element">fff</div>
</body>
</html>
I think the last method is the cleanest way to handle the case but if there is any dynamic css value by JavaScript is used, I would more prefer the first method.

Reference

http://stackoverflow.com/questions/447197/how-to-define-multiple-css-attributes-in-jquery
http://api.jquery.com/css/#properties
 

No comments :

Post a Comment