Intrinza Intrinza - 7 months ago 19
HTML Question

Get this function to work when I left mouse click?

I'm creating an extension and going to use tampermonkey to run it and I want this to work when I left mouse click and hold it'll still run.

// @run-at document-end

(function() {
var amount = 6;
var duration = 50; //ms

var overwriting = function(evt) {
if (evt.keyCode === 0) { // Left mouse click?
for (var i = 0; i < amount; ++i) {
setTimeout(function() {
window.onkeydown({keyCode: 87}); // KEY_W
window.onkeyup({keyCode: 87});
}, i * duration);
}
}
};

window.addEventListener('keydown', overwriting);
})();

Answer

Try using "mousedown" instead:

(function() {
var amount = 6;
var duration = 50; //ms

var overwriting = function(evt) {
    for (var i = 0; i < amount; ++i) {
        setTimeout(function() {
            window.onkeydown({keyCode: 87}); // KEY_W
            window.onkeyup({keyCode: 87});
        }, i * duration);
    }
};

window.addEventListener('mousedown', overwriting);
})();