I have a slider that should activate the JS function. The user can move the cursor from the slider itself, but continue dragging the slider by holding the left mouse button, but when the slider is moved to the right place, the user releases the left mouse button not at the slider, but somewhere at a random point on the screen, the function will not work, this options with $(document).click disappear.

I wrote the following version, perhaps some kind of collective farm, but still for an example:

 $(document).on('mousedown', '#id', function (){ $(window).click(function (){ // Код всей функции } } 

Now I ran into the problem that when you first load the page everything is fine, the code works as it should, but when you re-act, the function starts to work when you click at any point on the screen, ignoring it $(document).on('mousedown', '#id', function () How to make these 2 events work according to the principle

 if(условия1 && условие2){ //Выполняю } 

PS $(window).click(function () used it specifically to pick up a click even if the user moved the cursor off the slider.

  • in fact, you do not have two conditions here, when you click on a button, an event is assigned to the entire document. - teran
  • If the slider has only two positions (such as on / off), I would just give the slider the opportunity to change by clicking, and not by dragging. - Nikolai Gabaraev
  • @NikolaGabaraev, the slider selects the value, from 1 to N-th - Slam Streetwear

1 answer 1

This happens because you assign a handler to the click of the entire window at the first 'mousedown' event. Use the 'mouseup' event, pre-remembering which element was 'mousedown'

Moving the slider is not adding, but an example should display the main idea:

 $(function() { var isMousDownOnSlider = false; $('.slider').on('mousedown', function(event) { isMousDownOnSlider = true; }); $(document).on('mouseup', function(event) { if (isMousDownOnSlider) { console.log('Slider mouse up'); isMousDownOnSlider = false; } }) }) 
 .slider { width: 25px; height: 25px; background-color: green } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="slider"></div> 

  • Can you give an example? I will be very grateful. - Slam Streetwear
  • Added an example. - Ofer
  • In my version, it’s better than $(document).on('mouseup', function(event) this $(window).click . - Slam Streetwear