Skip to content
Related Articles

Related Articles

How to change background color of paragraph on double click using jQuery ?
  • Last Updated : 01 Apr, 2021

In this article, we will see how to change the background color of a paragraph using jQuery. To change the background color, we use on() method. The on() method is used to listen the event on an element. Here we are going to use dblclick event. For changing the background color we are going to use css() method. This method helps us to add CSS properties dynamically. For more details you can refer this article.

Syntax : 

$("p").on({
    dblclick: function(){
        $(this).css("property", "value");
    }
});

Here we have created a paragraph inside body tag i.e. <p> element. We added a double click event on it. If anyone double click on that paragraph the background color will toggle according to the given value.

Example 1: In this example, We are going to use css() method that adds the background color to our paragraph element dynamically.

HTML




<!DOCTYPE html>
<html lang="en">
  
<head>
    <script src=
    </script>
  
    <script>
        $(document).ready(function () {
            var toggle = true; // Toggle state
            $("p").on({
                dblclick: function () {
                    if (toggle) {
                      
                        // Change background to red
                        $(this).css("background-color", "red");
                        toggle = false;
                    } else {
  
                        // Change background to default
                        $(this).css("background-color", "white");
                        toggle = true;
                    }
                }
            });
        });
    </script>
</head>
  
<body>
    <p>Double click to change background color</p>
</body>
  
</html>


Output:

Example 2: In this example, we are going to use addClass() and removeClass() method to add or remove CSS dynamically.

HTML




<!DOCTYPE html>
<html lang="en">
  
<head>
    <script src=
    </script>
  
    <style>
        .toggle {
            background-color: green;
        }
    </style>
  
    <script>
        $(document).ready(function () {
            var toggle = true; // Toggle state
            $("p").on({
                dblclick: function () {
                    if (toggle) {
  
                        // Add class toggle to the paragraph
                        $(this).addClass("toggle");
                        toggle = false;
                    } else {
  
                        // Remove class toggle to the paragraph
                        $(this).removeClass("toggle");
                        toggle = true;
                    }
                }
            });
        });
    </script>
</head>
  
<body>
    <p>Hello GeeksforGeeks</p>
</body>
  
</html>


Output:




My Personal Notes arrow_drop_up
Recommended Articles
Page :