NoWeDoR NoWeDoR - 3 months ago 6
HTML Question

how to find click amount?

I want to print click amount to console, but it must be for all empty areas. Is it possible?

I've tried with button, but couldn't do what I want.

HTML:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="myScript3.js"></script>
</head>

<body>
<button onclick="tiklama()">Tıkla!</button>
</body>
</html>


JS:

var x = 0;
function tiklama() {
console.log(++x);
}

Answer

Listen to click event at a higher level, e.g. on <html> element and check whether the event's target property suites your definition of an "empty area".

var counter = 0;
document.documentElement.addEventListener('click',
    function(e) {
        // counting all clicks except on the interactive elements
        if (!e.target.matches('button,input,textarea,select')) {
            console.log(++counter);
        }
    },
    false);
<p>Some text -- considered non-interactive area.</p>
<button>An interactive button</button>