Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • jQuery Tutorial
  • jQuery Selectors
  • jQuery Events
  • jQuery Effects
  • jQuery Traversing
  • jQuery HTML & CSS
  • jQuery AJAX
  • jQuery Properties
  • jQuery Examples
  • jQuery Interview Questions
  • jQuery Plugins
  • jQuery Cheat Sheet
  • jQuery UI
  • jQuery Mobile
  • jQWidgets
  • Easy UI
  • Web Technology
Open In App
Next Article:
How to get the background color of a clicked division using jQuery ?
Next article icon

How to toggle background color using right click in jQuery ?

Last Updated : 18 Apr, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, we will learn to toggle the background color using the right-click in jQuery.

Approach 1: The approach is by using the contextmenu event. The contextmenu() method is used to bind the contextmenu event to the element being used. This can be used to perform the color toggling action on the element being used. We return false from the binding function to prevent the context menu from opening.

The two background colors can be defined in two classes that can be kept track of using a boolean variable. This variable is toggled when the click is detected. The addClass() and removeClass() methods are used on the element to add or remove the class according to this element.

jQuery Code:

let isRedBackground = true;    let box = $(".box");    box.contextmenu(function () {      // Add and remove the background classes    if (isRedBackground) {      box.removeClass("redbg");      box.addClass("greenbg");    }    else {      box.removeClass("greenbg");      box.addClass("redbg");    }      // Toggle the background color variable    isRedBackground = !isRedBackground;      return false;  });

Example: The below example illustrates the above approach.

HTML
<!DOCTYPE html> <html>  <head>     <script src= "https://code.jquery.com/jquery-3.3.1.min.js">     </script>      <style>         .redbg {             background-color: red;         }          .greenbg {             background-color: green;         }          .box {             height: 250px;             width: 250px;         }     </style> </head>  <body>     <h1 style="color: green">         GeeksforGeeks     </h1>      <b>         How to toggle background color         using right click in jQuery?     </b>      <p>         Right click on the div to toggle         the color of the division     </p>      <div class="box redbg"></div>     <br>      <script>              // Variable for storing the current         // background color         let isRedBackground = true;          // Get the div that has to be         // toggled         let box = $(".box");          box.contextmenu(function () {              // Add and remove class depending             // on the variable             if (isRedBackground) {                 box.removeClass("redbg");                 box.addClass("greenbg");             }             else {                 box.removeClass("greenbg");                 box.addClass("redbg");             }              // Toggle the background color variable             isRedBackground = !isRedBackground;              return false;         });     </script> </body>  </html> 

Output:

Approach 2: The second approach is using the mousedown() event to get the right-click. The mousedown() method is used to bind the mousedown event to the element being used. This can be used to get the right click of the mouse by checking the which property of the event to be equal to "3" which denotes the right click.

Instead of defining the background colors in classes, the two background colors can be defined as two variables and the css() method can be used to set the background color of the division. A separate boolean variable can be used to track the current background color and set the color of the division automatically, similar to the above approach.

jQuery code:

  let isBackgroundOne = true;  let backgroundOne = "red";  let backgroundTwo = "blue";  let box = $(".box");    // Bind the mousedown event  box.mousedown(function (event) {        // Disable the context menu      box.contextmenu(false);        // Check if right mouse button      if (event.which == 3) {            // Toggle the color based on the           // variable          if (isBackgroundOne) {              box.css({                  backgroundColor: backgroundTwo          );          }          else {              box.css({                  backgroundColor: backgroundOne              });          }            // Toggle the variable itself          isBackgroundOne = !isBackgroundOne;      }  });

Example: The below example illustrates the above approach.

HTML
<!DOCTYPE html> <html>  <head>     <script src= "https://code.jquery.com/jquery-3.3.1.min.js">     </script>          <style>         .box {             height: 250px;             width: 250px;              /* Initial background color */             background-color: red;         }     </style> </head>  <body>     <h1 style="color: green">         GeeksforGeeks     </h1>      <b>         How to toggle background color         using right click in jQuery?     </b>      <p>         Right click on the div to         toggle the color of the division     </p>      <div class="box"></div>     <br>      <script>              // Variable for storing the current         // background color         let isBackgroundOne = true;          // Defining both the background colors         let backgroundOne = "red";         let backgroundTwo = "blue";          let box = $(".box");          // Bind the mousedown event         box.mousedown(function (event) {              // Disable the context menu             box.contextmenu(false);              // Check if the right mouse button             // is pressed             if (event.which == 3) {                  // Toggle the color based on the                  // variable                 if (isBackgroundOne) {                     box.css({                         backgroundColor: backgroundTwo                     });                 }                 else {                     box.css({                         backgroundColor: backgroundOne                     });                 }                  // Toggle the variable itself                 isBackgroundOne = !isBackgroundOne;             }         });     </script> </body>  </html> 

Output:

toggle background

Next Article
How to get the background color of a clicked division using jQuery ?
author
sayantanm19
Improve
Article Tags :
  • Web Technologies
  • JQuery
  • jQuery-Methods
  • HTML-Questions
  • jQuery-Questions

Similar Reads

  • How to Double click on a div element to toggle background color in jQuery ?
    In this article, we will see how to make a double click event on a paragraph element to toggle background color in jQuery. To toggle the background color of a div element on double-click, toggleClass() method is used. The toggleClass() method is used to toggle or change the class which attached with
    1 min read
  • How to get the background color of a clicked division using jQuery ?
    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 curr
    2 min read
  • How to change background color of paragraph on double click using jQuery ?
    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 c
    2 min read
  • How to Set background Image using jQuery css() Method ?
    This article will show you how to set the background image using jQuery. To set the background image, we are using the jQuery css() method. jQuery css() MethodThis method sets/returns one or more style properties for the specified elements. Syntax: Return a CSS property:$(selector).css("propertyname
    2 min read
  • How to change the color of an icon using jQuery ?
    In this article, we will see how to change the color of the icon using jQuery. To change the color of the icon, we will use a jquery method. jQuery css() method this method is used to change the styling of a particular selector. This method is also can be used for changing the color of the icon. Fir
    2 min read
  • How to change the background image using jQuery ?
    To change the background image using jQuery, you can use the jQuery CSS() method. For this, the whole property value is specified using the url() functional notation. Approach: Suppose we have an image URL stored in a variable and then use css() method to change the value of background image. Below
    1 min read
  • How to set background color for an elements using jQuery ?
    In this article, we will set the background color for an element using jQuery. To add the background color, we use css() method. The css() method in JQuery is used to change style property of the selected element. The css() in JQuery can be used in different ways. The css() method can be used to che
    1 min read
  • How to add dbclick() on right click in jQuery?
    The jQuery dblclick() method is used to detect whenever a particular element is double-clicked. This method only detects left mouse button double clicks and not the right mouse button double clicks. In this article, we will see how to simulate the double right mouse click in jQuery. Approach: There
    3 min read
  • How to change the position of background image using jQuery ?
    In this article, we will see how to change the position of the background image using jQuery. To change the position of the background image, we will use css() method with float property.  The css() method is used to change the style property of the selected element. The float property is used to ch
    2 min read
  • How to create slide left and right toggle effect using jQuery?
    The task here is to create a slide left and right toggle effect in the JQuery, you can use the jQuery animate() method. .animate() method: It is used to change the CSS property to create the animated effect for the selected element. Syntax: (selector).animate({styles}, para1, para2, para3); Approach
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences