Open In App

How to get the background color of a clicked division using jQuery ?

Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will learn how to get the background color of a clicked division using jQuery.

Approach: All the divisions on the page are first selected using a common selector and a click binding is applied to trigger the color detection using the click() method. The division that is then currently clicked can then be found out by using this as the selector.

The css() method in jQuery is used for getting and setting the computed styles of the element it is used on. It accepts two parameters where the first parameter defines the style for which we need to get or set the style, and the second parameter defines the value it has to be set. We can use this method to get the current color by passing the parameter as “background-color”  for getting the current background color. This can then be shown as a text in RGB values or assigned to another element.

Syntax: 
 

$(".box").click(function () {

    // Get background color of element
    let current_color =
        $(this).css("background-color");

    // Show the color text on the same box
    $(".current-color-text").text(
        current_color
    );

    $(".box").html('');
    $(this).html('<b class="current-color-text">'+current_color+'</b>');
    
    });

The below example illustrates the above approach:

Example:

HTML




<html>
<head>
</script>
<style>
    .container {
    display: flex;
    }
 
    .box {
    height: 125px;
    width: 125px;
    margin-right: 16px;
    }
 
    .yellowgreen-bg {
    background-color: yellowgreen;
    }
 
    .orangered-bg {
    background-color: orangered;
    }
 
    .slateblue-bg {
    background-color: slateblue;
    }
 
    .gold-bg {
    background-color: gold;
    }
 
    .current-color {
    height: 75px;
    width: 75px;
    }
</style>
</head>
 
<body>
<h1 style="color: green">
    GeeksforGeeks
</h1>
<b>How to get the background color of a
    clicked division using jQuery?</b>
 
<p>
    Click on any division to get its
    background color
</p>
 
 
 
<div class="container">
     
    <!-- Define the division's with
    background color -->
    <div class="box yellowgreen-bg"></div>
    <div class="box orangered-bg"></div>
    <div class="box slateblue-bg"></div>
    <div class="box gold-bg"></div>
</div>
 
 
<script>
    $(".box").click(function () {
 
    // Get background color of element
    let current_color =
        $(this).css("background-color");
 
    // Show the color text on the same box
    $(".current-color-text").text(
        current_color
    );
 
    $(".box").html('');
    $(this).html('<b class="current-color-text">'+current_color+'</b>');
     
    });
</script>
</body>
</html>


Output:

Color is shown on the same box after clicking

 



Last Updated : 02 Nov, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads