JQuery Css

css in jquery

The JQuery CSS method is used to get (return)or set style properties or values for selected elements. It facilitates you to get one or more style properties.

jQuery CSS() method provides two ways:

i) Return a CSS property:

It is used to get the value of a specified CSS property.

Syntax:

css(“propertyname”);

Example:

Let’s take an example to demonstrate this property.
<!DOCTYPE html>
<html>
<head>
<script src=”https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js”></script>
<script>
$(document).ready(function(){
    $(“button”).click(function(){
        alert(“Background color = ” + $(“p”).css(“background-color”));
    });
});
</script>
</head>
<body>
<h2>This is a heading</h2>
<p style=”background-color:#ff6a00″>The background-color of this paragraph is red.</p>
<p style=”background-color:#808080″>Another background-color of this paragraph is grey.</p>
<p style=”background-color:#b6ff00″>The background-color of this paragraph is green.</p>
</body>
</html>

ii) Set a JQuery CSS property:

This property is used to set a specific value for all matched element.

Syntax:

css(“propertyname”,”value”);

Example:

<!DOCTYPE html>
<html>
<head>
<script src=”https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js”></script>
<script>
$(document).ready(function(){
    $(“button”).click(function(){
        $(“p”).css(“background-color”, “violet”);
    });
});
</script>
</head>
<body>
<p style=”background-color:#ff6a00″>The background-color of this paragraph is orange.</</p>
<p style=”background-color:#808080″>Next background-color of this paragraph is grey.</</p>
<p style=”background-color:#b6ff00″>The background-color of this paragraph is green.</</p>
<p>This paragraph has no background-color. </p>
</body>
</html>

iii) Set multiple CSS properties:

It is just an extension of Set CSS property. It facilitates you to add multiple property values together.

Syntax:

 css({“propertyname”:”value”,”propertyname”:”value”,…}); 

Let’s take an example to demonstrate this property. In this example we add two properties background-color and font-size for all element.

Example:

<!DOCTYPE html>
<html>
<head>
<script src=”https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js”></script>
<script>
$(document).ready(function(){
    $(“button”).click(function(){
        $(“p”).css({“background-color”: “yellow”, “font-size”: “200%”});
    });
});
</script>
</head>
<body>
<h2>This is a heading</h2>
<p style=”background-color:#ff6a00″>The background-color of this paragraph is orange.</p>
<p style=”background-color:#808080″>Another background-color of this paragraph is grey.</p>
<p style=”background-color:#b6ff00″>The background-color of this paragraph is green.</p>
<p>This paragraph has no background-color.</p>
</body>
</html>

Spread the love

Leave a Comment

Your email address will not be published. Required fields are marked *