0

Result not like I'm expect

    var clicks = 0;
    $("*").click(function(event){
        if(clicks == 0){  // first click
            a=parseFloat(event.pageY-pageYOffset);
            ++clicks;
        }else{ // second clik
            b=parseFloat(event.pageY-pageYOffset);
            $("#lable7").text(b-a);  //heppen in first click, why?
            clicks=0;                          
        }
    } );

I want to count distance between first and second click, and do it many times on page.

I tried some tips but

$('*').one('click',function(){

}).click(function(){

   alert("heppen in first click"); 
});

What I'm doing wrong?

Slava32768
  • 49
  • 1
  • 5

1 Answers1

1

The event is bubbling, so the handler is being executed for all the nested elements on the page. You need to disable propagation.

var clicks = 0;
var pageYOffset = 500;
$("*").click(function(event) {
  if (clicks == 0) { // first click
    a = parseFloat(event.pageY - pageYOffset);
    ++clicks;
  } else { // second clik
    b = parseFloat(event.pageY - pageYOffset);
    $("#lable7").text(b - a); //heppen in first click, why?
    clicks = 0;
  }
  event.stopPropagation();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>Text
  <div>More text</div>
</div>
<div id="lable7"></div>
Barmar
  • 669,327
  • 51
  • 454
  • 560