Ways to prevent the mousedown event from firing when reaching a particular number during incrementation

Is there a way to disable the mousedown event once a specific condition is met?

For instance, in the code below, how can I prevent the Key and event from functioning when the temp reaches 30

$(document).ready(function() {
  var temp = 0;
  var to = null;
  var iv = null;

  $("#ClickMe").on("mousedown", function() {
    temp++;
    $("#Temp").html(temp);
    to = setTimeout(function() {
      iv = setInterval(function() {
        temp++;
        $("#Temp").html(temp);
      }, 75);
    }, 500);
  }).on("mouseup mouseleave", function() {
    clearTimeout(to);
    clearInterval(iv);
  });
});
div {
  margin: 10px;
  padding: 26px;
  background-color: yellow;
  text-align: center;
  border-radius: 10px;
  max-width: 40px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="ClickMe">CLICK ME</button>
<div id="Temp">0</div>

Answer №1

This is a comprehensive answer, complete with code snippets...

$(document).ready(function() {
  var count = 0;
  var timeout = null;
  var interval = null;

  $("#ClickMe")
  .on("mousedown", function() {
    count++;
    $("#Temp").html(count);
    timeout = setTimeout(function() {
      interval = setInterval(moreClick, 75);
    }, 500);
  })
  .on("mouseup mouseleave", function() {
    clearTimeout(timeout);
    clearInterval(interval);
    stopClick();
  });

  function moreClick() {
    $("#Temp").html(++count);
    stopClick();
  }

  function stopClick() {
    if (count >= 30 ) {
      clearTimeout(timeout);
      clearInterval(interval);
      $("#ClickMe")
      .off("mousedown mouseup mouseleave")
      .prop('disabled', true);
    }
  }
});
div {
  margin: 10px;
  padding: 26px;
  background-color: yellow;
  text-align: center;
  border-radius: 10px;
  max-width: 40px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button id="ClickMe">CLICK ME</button>
<div id="Temp">0</div>

Answer №2

Implement an if condition and utilize jQuery's .off() method:

$(document).ready(function() {
  var counter = 0;
  var timeout = null;
  var interval = null;

  $("#ClickMe").on("mousedown", function() {
    if (counter < 30) {
      counter++;
      $("#CounterDisplay").html(counter);
      timeout = setTimeout(function() {
        interval = setInterval(function() {
          counter++;
          $("#CounterDisplay").html(counter);
        }, 75);
      }, 500);
    } else {
      $("#ClickMe").off("mousedown");
    }
  }).on("mouseup mouseleave", function() {
    clearTimeout(timeout);
    clearInterval(interval);
  });
});
div {
  margin: 10px;
  padding: 26px;
  background-color: yellow;
  text-align: center;
  border-radius: 10px;
  max-width: 40px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="ClickMe">CLICK ME</button>
<div id="CounterDisplay">0</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

achieving bidirectional binding within a directive without using an isolated scope

One of my directives is set up like this: angular.module('somemodule').directive('tooltipText', function ($timeout, $compile, $document, config, $filter) { return { restrict: 'A', scope:{ tooltip: '=&ap ...

CSS - Ensuring the second line of text in ul/ol li does not extend further left than the first line

My website features several lists that have this format: > lorem ipsum I am trying to style them like this: > lorem ipsum If anyone can provide guidance on how to rephrase the question I am asking, I would greatly ap ...

Is there a way for me to initiate another joyride adventure?

Encountering a challenge with my joyride tour - after completing one tour, I aim to commence a second. Despite attempting to trigger the second tour in the postRideCallback function, I find myself stuck in a loop with the first tour. Seeking guidance on re ...

Angular.js filter issue: "Error: textProvider is not recognized provider"

I implemented a custom filter for my AngularJS project that is similar to the one in this fiddle http://jsfiddle.net/tUyyx/. myapp.filter('truncate',function(text,length){ var end = "..." text = text.replace(/\w\S*/g, function( ...

the angular-ui-tinymce directive allows for seamless image uploads using a file browser

Utilizing jQuery, we have the ability to incorporate local images into the tinymce editor similar to what is demonstrated in this jsfiddle, by following the guidelines provided in the documentation. The Angular module for tinymce can be found at angular-u ...

Having excessive space within an H1 heading

Having an issue with a PHP file on my test server that is displaying extra white space, which is highlighted by a red box. This whitespace is also shown in the developer tools view. When the file is outputted, all of the content appears on one line. Code: ...

Handling overflow and z-index of tabs in Vuetify Drawer

Struggling to create an expandable sidebar menu using Vuetify2, following the documentation, but unable to prevent the expanded menu from overlapping other elements on the page. The current behavior causes items to be pushed away and wrap onto the next ro ...

Navigating through cpanel to interact with a Button using Selenium in Python

Unable to select the new folder option. Here is what I have attempted: driver.find_element_by_id("li.action-newfolder") driver.find_element_by_xpath("//[a(text(), 'New Folder')]").click() Unfortunately, neither of these methods are successful. ...

Issues with Javascript positioning in Chrome and Safari are causing some functionality to malfunction

My Javascript script is designed to keep an image centered in the window even when the window is smaller than the image. It achieves this by adjusting the left offset of the image so that its center aligns with the center of the screen. If the window is la ...

What is the best way to start the server when the files are located in separate directories?

I have organized my project into two separate folders, one for the client and one for the server Is there a way to use npm start to simultaneously run both the frontend and backend scripts? Check out the screenshot below: View of Two Folders in my Projec ...

Turn off Chrome's new tab preview thumbnails

Is there a method to prevent Google Chrome from displaying certain pages as thumbnails? I am inquiring because I am developing a website that contains confidential information. As it stands now, the sensitive data can be viewed in the thumbnail preview. ...

Retrieve the chosen item along with its quantity

I'm currently working on building a shopping cart application similar to this example using React.js. index.js: (Sending each product to the product component) {products.length > 0 ? products.map((product) => ( <Produ ...

Can you modify the value of the link identified as "#showCities" based on the city that is clicked on?

There is a link called "All Country" that, when clicked, opens a modal displaying a list of cities: <a class="city" id="showCities" data-toggle="modal" data-target="#modal2" href="">All Country</a> The modal lists all the cities associated wi ...

Has Next.js incorporated a maximum cache size feature along with an invalidation algorithm like LRU?

Currently, I have a Next.js site that utilizes getServerSideProps for data fetching. However, I am interested in switching to getStaticProps and implementing incremental static regeneration (ISR) for improved performance. Currently, my memory usage is ap ...

Surprising results when a class is applied using jQuery

Exploring the differences between two fiddles (make sure to run the code on the jsfiddle pages to see the differences clearly). First Fiddle Simple demonstration: $("body").addClass("noScroll"); alert($("body").hasClass("noScroll")); $("body").removeCla ...

What is the best way to position a div next to a form field?

My current HTML code is shown below. <div class="field"> <label>E-mail address: </label> <input type="text" id="email" name='email' style="width:200px;"></input> < ...

Tips for clearing out text in a <p> tag with javascript when it exceeds a specific length of 100 characters

Is there a way to automatically truncate text to (...) when it exceeds 100 characters inside a paragraph with the class .class? For instance, if I have a long paragraph like this: <div class='classname'> <p>Lorem ipsum dolor sit ame ...

Is it possible to turn off the fallback color for bourbon radial gradients?

Is there a way to prevent the fallback from being applied when using the radial gradient mixin in Bourbon? I've consulted the documentation at , which states that the fallback is optional. However, no matter what I attempt, it seems that the primary ...

Is it possible to integrate Wavify with React for a seamless user experience?

For my website designs, I have been experimenting with a JavaScript library known as Wavify (https://github.com/peacepostman/wavify) to incorporate wave animations. Recently delving into the world of React, I pondered whether I could integrate Wavify into ...

Retrieve information from the API prior to rendering the controller components

Hello there! I am looking to retrieve data from a factory before any of my controllers are loaded. After some research, I discovered that it can be achieved using the resolve function in AngularJS: angular.module('agent', ['ngRoute',&a ...