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?

Ryan M
  • 18,333
  • 31
  • 67
  • 74
Slava32768
  • 49
  • 1
  • 6
  • Might help if you tell us what result you are actually getting. – Lochemage Nov 27 '14 at 00:33
  • 3
    Please don't make more work for others by vandalizing your posts. By posting on the Stack Exchange (SE) network, you've granted a non-revocable right, under the [CC BY-SA license](https://creativecommons.org/licenses/by-sa/4.0), for SE to distribute the content (regardless of your future choices). By SE policy, the non-vandalized version is distributed. Thus, any such destructive edits will be reverted. Please see [I've thought better of my question; can I delete it?](https://meta.stackexchange.com/q/5221) for alternatives. – Ryan M Apr 11 '23 at 06:24

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
  • 741,623
  • 53
  • 500
  • 612