Introduction to JQUERY - Introduction with JQUERY – Tinkering CSS Elements with CSS() Method Part 2

Guest Posts Paolo Nikko Nuñal

JQUERY can do a lot of things most especially when it comes to handling CSS elements. Have you you ever wondered how beautiful and attractive those websites are everytime you click on a button or hover on an element? Well, you can do it easily thanks to the css() method. In this tutorial we are going to see how you can play set and return a css property of an HTML element.

Syntax:

css("[PROPERTYNAME]");

Using the syntax above you can return the background-color value of the FIRST matched element.

Code:

<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
    $("#btn-return").click(function(){
       alert("Background color = " + $("#header1").css("background-color"));
    });
});
</script>
</head>
<body>
<h1 id="header1" style="background-color:#ff0000">This is a header </h1>
<button type="button" id="btn-return">Return BG Color</button>
</body>
</html>


So when you click on the "Return BG Color" button, it will automatically return what the background color of the <h1> tag with the id "header1" which is "RED" or HEXA equivalent rgb(255, 0, 0). Now you know how to get the value of a CSS property, this time around, you will going to learn how to set a CSS property and create dynamic websites that changes color or whatever you would like on a website.

Syntax:

css("[PROPERTYNAME]","[VALUE]");

Code:

<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
    $("#btn-return").click(function(){
        $("#header1").css("background-color","green");
    });
});
</script>
</head>
<body>
<h1 id="header1" style="background-color:#ff0000">This is a header </h1>
<button type="button" id="btn-return">Change Color to Green</button>
</body>
</html>


As a sidenote, you can also use hexa decimal properties. It is not only limited to changing to background-color but you can also do a wide array of things like changing fonts and the like as long as you know the CSS PROPERTY that you are going to modify, and the value you would like to set. You can also do this with multiple CSS elements by pairing them and seperating them with a comma.

css("[PROPERTYNAME]","[VALUE]",[PROPERTYNAME]","[VALUE]",[PROPERTYNAME]","[VALUE]". ....);