Activate context menu with a button press - jQuery

My jQuery code is mostly working fine, but I'm having an issue with the first click not disabling the right-click as expected. After the initial click, everything works as intended. Can someone help me figure out what's going wrong?

Here's the jQuery Code:

let $document = $(document);
    $document.ready(() => {
        let toggleValue = true;
        $('.btn-toggle').on('click', () => {
            $document.on('contextmenu', (e) => {
                if(toggleValue) {
                    e.preventDefault();
                }
            });
        toggleValue = !toggleValue;
    })
})

And here's the corresponding HTML code:

<h3>Toggle right-click menu on button click</h3>

<button class="btn-toggle">Toggle Right Click</button>

You can check out the JSFIDDLE for reference: https://jsfiddle.net/mLm096o4/

Answer №1

Revise the code within the event listener for the Toggle Right Click button to exclude handling right clicks.

const $document = $(document);

$document.ready(() => {
  let toggleValue;

  $('.btn-toggle').on('click', () => {
    toggleValue = !toggleValue;
  });

  $document.on('contextmenu', (e) => {
    if (toggleValue) {
      e.preventDefault();
    }
  });
});

Additionally, you should update let $document = $(document); to const $document = $(document); since there is no need to reassign a different value to this variable.

Edit: adjusted based on feedback.

Answer №2

To improve performance, consider assigning the click handler only once instead of repeatedly reassigning it.

let $doc = $(document);        
    $doc.ready(() => {
        let toggleActive = true;
        $doc.on('contextmenu', (e) => {
                if(toggleActive) {
                    e.preventDefault();
                }
            });

        $('.btn-toggle').on('click', () => {            
            toggleActive = !toggleActive;
        })
    })

Answer №3

try using if(toggleValue === false) instead of if(toggleValue)

let $document = $(document);
$document.ready(() => {
  let toggleValue = true;
  $('.btn-toggle').on('click', () => {
    $document.on('contextmenu', (e) => {
      if(toggleValue === false) {
        e.preventDefault();
      }
    });
    toggleValue = !toggleValue;
  })
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3>Toggle right click menu on button click</h3>

<button class="btn-toggle">Toggle Right Click</button>

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

Ajax long-polling - Timeout triggering unexpectedly

I am having an issue with my Ajax code polling my IIS/ASP server. After calling msgPoll("") once, the function seems to be invoked repeatedly instead of every 30 seconds. Can you help me identify what mistake I might be making? var msgTimOut; f ...

Is there a way for me to access the user's gender and birthday following their login using their Google account details?

I have successfully implemented a Google sign-in button in my Angular application following the example provided in Display the Sign In With Google button: <div id="g_id_onload" class="mt-3" data-client_id="XXXXXXXXXXXX-XX ...

Android experiencing issues with dynamically loading Border XML

I am having trouble setting a border dynamically for a RelativeLayout. Oddly enough, when I manually add the border in the activity XML file, it displays perfectly. However, when I try to generate the border dynamically, it doesn't appear. border.xml ...

How can Three JS and an image be combined to make a custom 3D cookie cutter?

I am currently working on a project that involves extracting the edges of a black and white image. My goal is to then generate a 3D model that highlights the edges of the black shape, extrudes the edges for depth, adds thickness to the walls, and creates ...

Deletion request using Ajax in Java Spring is being denied

I am facing an issue with sending a delete request to Java Spring. The problem is that I constantly receive a 403 forbidden response message. Below is the client-side JavaScript code: $(".deleteList").click(function(){ var url = "boodschappenlijs ...

consolidating express routes in one consolidated file

I am attempting to consolidate routes into a single file using app.use app.js import express from 'express' import testRouter from 'testRouter' const app = express() app.use('/testRouter', testRouter) app.listen(3000) tes ...

What is the best way to access the values associated with the keys in an array of objects?

I have an array of objects that has the following structure: import icon1 from '!!raw-loader!../../../icon1.svg'; import icon2 from '!!raw-loader!../../../icon2.svg'; import icon3 from '!!raw-loader!../../../icon3.svg'; import ...

Using CSS animations to animate a div while creating a subtle pause between the two

I am working on creating a notification bar that will be displayed and hidden using CSS animation. My challenge is finding the right delay between the two animations. HTML <div id="notification" class="alert" role="alert"></div> JS $(' ...

Can the active link color be modified in Bootstrap 5 without the use of CSS?

It's been a while since I've worked with HTML, and this is only my second attempt at creating tabs, so I might be approaching this the wrong way. Currently, the link text in the tabs is in the primary bootstrap color (blue) by default and change ...

Angular: Updating image tag to display asynchronous data

Utilizing Angular to retrieve user profile pictures from the backend, specifically Node.js/Express, has been mostly successful. However, there is one issue that I have encountered. The HTML displaying the profile picture does not re-render when the user up ...

What causes the vertical scroll bar to shift on its own?

I'm puzzled by the behavior of the vertical scroll bar when clicking on "Line 9" - it automatically moves to the top position and subsequent clicks don't affect it. Can someone shed light on why this happens and how to resolve it? I am using Fire ...

Tips on showcasing offspring of a particular guardian when the dropdown is altered from a json file using angularjs

Implementing a dropdown menu with mock JSON data containing an array of objects and children as arrays. When changing the dropdown selection, specific children/sublinks should be displayed within a paragraph tag based on the selected project name. For ex ...

How to turn off JavaScript using Selenium WebDriver?

Recently, I encountered a problem with my program that tests some of our sites with javascript disabled. Everything was working perfectly until we upgraded from WebDriver 2.4.5 to the latest version. Now, I'm faced with this error message: java.lang. ...

Combining NPM Dependencies in a VUE.js JavaScript Project

For a unique situation in a Vue.js and JavaScript project, there is a need to integrate an NPM package dependency into the current JavaScript code base. In this particular case, the NPM package should no longer be part of the nodes_modules folder but rath ...

What are some ways to keep text within the boundaries of a div element?

I have tried multiple solutions for this issue, but none seem to be working for me. When I append a paragraph to a div, the text extends beyond the element. Below is the code I am using. Any assistance would be greatly appreciated. CSS: .chat-h { margi ...

Tips for Addressing Angular Scope Variable Within a Div's Class

<div class="progressMain"> <div class="stocking progressWrap progress" data-progress-percent="33"> <div class="progressBar progress stocking"></div> <div class="progressText">In Progress 3 of 7 steps</div& ...

The Film Repository: Retrieve Movie Synopsis JSON

Exploring the process of connecting to The Movie Database API with JSON and retrieving specific movie information. Currently, I can successfully retrieve "poster_path", "original_title", and "release_date" but am struggling to access the movie overview. De ...

displaying and concealing elements with jquery

Is there a way to hide a div if the screen size exceeds 700px, and only show it when the screen size is less than 700px? Below is the jQuery code I'm attempting to use: jQuery(document).ready(function() { if ((screen.width>701)) { $(" ...

Identifying the specific random image that has been clicked on in an ASP.NET application

I have 12 unique images randomly selected from 2 different folders. Whenever an image is clicked, I want to change the border color of that image and also save which image was clicked in a database. Below is the code I am currently using to display the ran ...

Swapping out the identifier 'datepicker' with the model attribute 'due_date' when integrating a datepicker within a Rails form

In my form, I have the following code snippet: <div class="row"> <%= t.label :name, 'Due Date' %><br> <%= t.text_field :due_date, id: 'datepicker' %> </div> The id attribute is necessary for ...