css method in jQuery with example


1. css() method gets the value of the style property for the first element from the set of matched elements.
2. We can change style of an element using this method.
3. We can set single or multiple style properties at once.


Example 1 :

        <html>
        <head>
        <title>CSS</title>
        <style>
        #myDiv
        {
        background-color:Green;
        width:200px;
        height:200px;
        }
        </style>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"> 
        </script>
        <script type="text/javascript">
            $(document).ready(function () {
                $("#myDiv").hover(function () {
                    $(this).css("background-color", "red");
                }, function () {
                    $(this).css("background-color", "Green");
                });
            });
        </script>
        </head>
        <body>
        <div id="myDiv">
        </div>
        </div>
        </body>
        </html>
    
Demo :




In the above example, we have shown how to use css() method. We created a simple div with initial background color as green. On hover of div we are changing its background color.


Example 2 : CSS - Multiple Property



        <html>
        <head>
        <title>CSS Multiple</title>
        <style>
        #myDiv
        {
        background-color:Green;
        width:200px;
        height:200px;
        color:White;
        }
        </style>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"> 
        </script>
        <script type="text/javascript">
            $(document).ready(function () {
                $("#myDiv").click(function () {
                    $(this).css({ 'background-color': 'red', 'margin-left': '400px' });
                });
            });
        </script>
        </head>
        <body>
        <div id="myDiv"><br />
        <input type="button" id="reset" value="Reset" onclick="location.reload()" />
        </div>
        </body>
        </html>
        
Demo :



In the above example, we are setting or changing two properties i.e background color and margin-left using css() method. Similarly we can apply many other style properties.


0 comments:

Post a Comment