w3resource

jQuery: Get the background color of a clicked division

jQuery Fundamental - II : Exercise-63

Get the background color of a clicked division.

Sample solution :

HTML Code :

<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-git.js"></script>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Get the background color of a clicked division.</title>
</head>
<body>
<div style="background-color:blue;"></div>
<div style="background-color:rgb(15,99,30);"></div>
<div style="background-color:#123456;"></div>
<p></p>
</body>
</html>

CSS Code :

div {
width: 50px;
height: 50px;
margin: 5px;
float: left;
}

JavaScript Code :

$( "div" ).click(function() {
var color = $( this ).css( "background-color" );
$('p').html(color);
  });

See the Pen jquery-fundamental-exercise-63 by w3resource (@w3resource) on CodePen.


Contribute your code and comments through Disqus.

Previous: Using jQuery right click to toggle background color.
Next: Get the styles (width, height, text color, and background color) of a clicked division.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.