简体   繁体   中英

Calling multiple functions on click event

I have two functions that are called when the user clicks a button; first is that a timer will go off, the second one starts recording the distance the mouse has traveled. When the user clicks on a second button, the timer and recording stops, and the data are added to arrays. Though it would seem my code does not work when attempting to call the two different functions during the click event. Also, how do I reset the distance the mouse traveled in pixels back to zero again? Any help would be much appreciated, thank you!

var c=0;
var t;
var timer_is_on=0;
var timers = new Array();
var count = 0;
var mouseclickPositionList = new Array();
var mouseDistance = new Array();
var totalTravelled = 0;
var xTravelled = 0;
var yTravelled = 0;
var prevX, prevY, count = 0
var select = false;

function printMousePos(e) {
    var cursorX = e.clientX;
    var cursorY = e.clientY;
    prevY && (yTravelled += Math.abs(e.pageY - prevY));
    prevX && (xTravelled += Math.abs(e.pageX - prevX));

    prevX = e.pageX;
    prevY = e.pageY;

    totalTravelled = yTravelled + xTravelled;
    mouseDistance.push(totalTravelled);
    prevX, prevY, totalTravelled = 0;
}

document.addEventListener("click", function() {
    printMousePos();
    doTimer();
} 

function timedCount() {
    t = setTimeout("timedCount()", 1000);
}

function doTimer() {
    if (!timer_is_on) {
        timer_is_on = 1;
        timedCount();
    }
}

function stopCount() {
    clearTimeout(t);
    timer_is_on = 0;
    timers.push(t);
}

Your function printMousePos(e) needs input data for processing of mouse position. So simply change listener registration to this form:

document.addEventListener("click", function(e) {
  //optionally put here code to stop bubbling the event
  printMousePos(e);
  doTimer();
}

If you have error in js file or script block the remaining code will not be processed. Your function printMousePos(e) does so, because it operating with input attribute 'e' which is not provided. Just check out browser console for problem identification.

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