Tips for implementing jquery to add a class to a div element when right-clicking

Click Actions

$(document).ready(function(){
    $( "div" ).click(function() {
      $( this ).toggleClass( "class-one" );
     //alert('left click');
    });
});

Mouse Clicks

$(document).ready(function(){
    $( "div" ).click(function() {
      $( this ).toggleClass( "class-two" );
     //alert('Right Click');
    });
});

My goal is to use Jquery to add a class on left click and another class on right click. The left click functionality is working, but the right click class addition is not functioning properly.

Is it possible to add a class on right click using Jquery?

Answer №1

When you want to trigger an action on right-click, you should use the event name contextmenu:

$("div").on("contextmenu", function() {
    $(this).toggleClass("class-two");
});

Answer №2

Follow these steps:

HTML --

<div id="demo">
    demo demo
</div>

CSS --

div {
    width: 300px;
    height: 200px;
    background-color: #99EAEA;
}

.class-primary {
    background-color: #EAEAEA;
}

.class-secondary {
    background-color: #EA3355;
}

JQUERY --

$(document).ready(function(){ 
    document.oncontextmenu = function() { return false; };

    $("#demo").click(function() {
      $( this ).removeClass("class-secondary").addClass("class-primary");
    });

    $(document).mousedown(function(e){ 
        if( e.button == 2 ) { 
            $("#demo").removeClass("class-primary").addClass("class-secondary");
            return false; 
        } 
        return true; 
    });  
});

That's all! Check out the demo: http://jsfiddle.net/ag62dyry/1/

Answer №3

If you want to experiment with a different approach, consider the following suggestion:

$(document).ready(function () {
    $("div").mousedown(function (e) {
        $(this).toggleClass("class-two");
        if (e.button == 2) {
            alert('Right mouse!');
            //feel free to insert your custom code for right mouse click actions here
        }
    });
});
div {
    height:100px;
    width: 100px;
    background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div></div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What could be the reason for the lower section of my website not being displayed?

I'm having an issue with a new div I added to the bottom half of my website - it's not showing up. Oddly enough, when I test the same code on a separate web page, it works fine. Can someone please take a look at the code and help me out? Thank yo ...

How to retrieve and delete a row based on the search criteria in an HTML table using jQuery

Here is the HTML code snippet: <table class="table" id="myTable"> <tr> <th>Type</th> <th>Counter</th> <th>Remove</th> <th style="display:none;">TypeDistribution</t ...

Loading SVG images in advance

I am in possession of around one hundred simple SVG images, distributed among five different image folders. These images are currently retrieved on demand when they need to be displayed, which generally works well but occasionally results in flickering tha ...

The URL in an AJAX request includes a repeating fragment due to a variable being passed within it

const templatePath = envVars.rootTemplateFolder + $(this).attr('link'); console.log("templatePath : ", templatePath); $.ajax({ method: "GET", url: templatePath, context: this, success : function(result){ ...

Transfer the cropped image to the database through AJAX on the client side and PHP on the server side

I am attempting to upload an image to a Database using JavaScript on the client-side and PHP on the server-side. The first step is selecting an image from the gallery. After zooming and cropping the image, it should be passed to the database. The issue ...

Update the text on a button using a different button

function modify_button_text(){ //update the word from cat to dog. } <button id="button_1_id" >Cat</button> <br><br><br><br> <button id="modify_button_text_btn" >Change the Text of Above Button</button> ...

Error: Label out of place in Material-UI Select

Can anyone help me understand why the Select label is misplaced in MUI5? https://i.sstatic.net/gvqff.png This is the Textfield label: https://i.sstatic.net/zrgqF.png This is the Select label: https://i.sstatic.net/GspRC.png Here is the code snippet: ...

Switching the loading order of jQuery and AngularJS to load jQuery after AngularJS

If you want angular.element to reference jQuery instead of jQLite, make sure to load jQuery before Angular in the page head. On mobile devices, performance is key. It would be great if jQuery could be loaded after AngularJS for better overall performance, ...

When utilizing *NgIf, the button will be shown without the accompanying text being displayed

When trying to display either a confirm or cancel button based on a boolean set in my component.ts, I implemented the following code in my HTML: <mat-dialog-actions class="dialog-actions"> <button class="cancel-btn" ...

minimize the size of the image within a popup window

I encountered an issue with the react-popup component I am using. When I add an image to the popup, it stretches to full width and length. How can I resize the image? export default () => ( <Popup trigger={<Button className="button" ...

Utilizing objects from a JSON file within an HTML document

I'm currently in the process of creating a comprehensive to-do list, and I want to establish a JSON file that will link all the items on the list together. Despite my efforts, I find myself uncertain about the exact steps I need to take and the speci ...

Arrange radio buttons vertically in a table

I am attempting to display a vertical list of radio buttons within a table cell. Is this achievable? Here is the code snippet I am currently working with: <table> <tr> <td> First Name </td> ...

The changes made to jqGrid select editOptions may not reflect immediately

I am facing an issue with dynamically loading values into a select in a jqGrid. The challenge I am encountering is that the returned values from the server are not displayed until the user changes the row. Even though I can see the correct values being s ...

Creating an autocomplete feature with just one input field to display information for two to three additional input fields

I'm working on implementing an autocomplete feature similar to this example: . Feel free to test it out with the code snippets provided: 1000, 1001. I've successfully implemented the autocomplete functionality where typing in Pa suggests Paris. ...

Changing the background color of required inputs that are empty using jQuery

I need help customizing the background color of required input fields that are left empty when a user submits a form. Some of the fields are optional, but I want only the required ones to be highlighted in red. Specifically, the required fields have been ...

Tips for eliminating delays in removing CSS transitions

Is there a way to smoothly transition a CSS property, make an immediate change in the CSS property value, and then reattach the transition without any delay? To better understand, consider the following example: if ($(".marquee").height() < $(".marqu ...

Customizing the layout of div elements with Twitter Bootstrap for a responsive design

Utilizing Bootstrap's responsive style sheet, I have organized 4 squares in divs that span 12 columns - |3|3|3|3|. However, when I access this layout on a mobile browser, it displays as: |12| |12| |12| |12| My desired display format is: |6 ...

Using jQuery to dynamically add a class to elements that have tab focus

I want to apply a css class to elements that are focused by the tab key, without adding the class when focused by a mouse click. I have managed to achieve this using jQuery with the focusin and focusout events. Here is the code that I currently have: $( ...

Use jQuery to dynamically capture and store the value of data-rowindex into an array

Is there a way to dynamically store the data-rowindex value into an array? <tr class="ewTableRow" data-rowindex="1" id="r1_assessment_training" data-rowtype="2"> Below is the code I've attempted. Not entirely sure if it is the correct approach ...

The autocomplete attribute is not compatible with GroceryCrud functionality

I attempted to implement the autocomplete feature using an example from w3schools. https://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_form_autocomplete Although I used jQuery to modify the form and add autocomplete="on" to both the form and input ...