JQuery Change Div background Color and Text Color On Click

JQuery Change Div background Color and Text Color On Click

On click of div you want to change background color of div and text color. It’s not that hard but you may want to recall the syntax of it and here is tutorial for you.

Change div color and background color example

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>

<script type="text/javascript" language="javascript"> 
   
   $("document").ready(function(){
   
    $("div").click(function(){
    
        $(this).css("color","blue");
        $(this).css("background-color","red");
    
    });        
        
    });
    
</script>

Complete example of change div color on click

<html>
<head>
    <title>JQuery change div background color </title>

<
script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script> <script type="text/javascript" language="javascript"> $("document").ready(function(){ $("div").click(function(){ $(this).css("color","blue"); $(this).css("background-color","red"); }); }); </script> </head> <body> <div> Click here to change color of div to blue. </div> </body> </html>

Summery

To access all div elements in html use $(“div”) and to access properties of it like background color css
use $(“#divID”).css(“background-color”,”Color Name hex or text”).

You can apply this technique on all elements which has background color property and color property.

Just find the element by it’s ID or name or class name or element type. You have lots of choices to achieve your goal.

In real life situations your scenario may be different. However syntax for accessing elements background-color and color property will remain same as long as you use JQuery library.

Tags:

Jquery