简体   繁体   中英

jQuery mouseclick counter - How to reset?

I am trying to make a site that counts each time the user has clicked their mouse. I have that part down, but I also need to include a reset button that, after the user clicks it, starts the mouse click counter back from 0.

I cannot figure it out - if I move the var = 0 about the doc ready, it resets, but after the button is clicked, the counter never goes past 1. I am not sure what to do.

My script -

$(document).ready(function(){
    console.log("Here");


    $(document).click(function(e) {
        $('#location').append("("+e.clientX+", "+e.clientY+")<br>");
    });

    var counter = 0;
    $(document).click(function(e) {
        counter++;
        $("#mouseclick").text("Total mouse clicks: " + counter);
    });

    $('button').click(function(e) {
        e.stopPropagation();  // stop the event from propagating up the visual tree
        $('#location').text("");
        $("#mouseclick").text("Total mouse clicks: 0");
    });

    $('button')
});

I need them to be able to click 'button' and the count will reset. Any advice?

You're not resetting the counter. See this fiddle

$(document).ready(function(){
  console.log("Here");


$(document).click(function(e) {
  $('#location').append("("+e.clientX+", "+e.clientY+")<br>");
});

var counter = 0;
$(document).click(function(e) {
  counter++;
  $("#mouseclick").text("Total mouse clicks: " + counter);
});

$('button').click(function(e) {
  e.stopPropagation();  // stop the event from propagating up the visual tree
  $('#location').text("");
  counter = 0;
  $("#mouseclick").text("Total mouse clicks: 0");
});

Just add counter=0 in $('button').click() event.

$('button').click(function(e) {
   counter=0;
   e.stopPropagation();  // stop the event from propagating up the visual tree
   $('#location').text("");
   $("#mouseclick").text("Total mouse clicks: 0");
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM