0


Here's my question: I want to see from javascript if an object is being clicked at the moment, Here is an example:

setInterval(function() {
    if (document.getElementByTagName('button')[0].isBeingClicked) { //I know this isn't right: This is where my question is about.
        console.log('Button being clicked');
        return;
    };
    console.log('Button not being clicked');
}, 1000);


With as simplified HTML ofcourse:

<html>
    <head></head>
    <body>
        <button>Click me</button>
    </body>
</html>

So all together: I want to be able to see whether a button or another object is being clicked at this time. Not if it has been clicked, but is being clicked.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
user274595
  • 418
  • 1
  • 5
  • 15

3 Answers3

2

I think this might be what you are looking for.

HTML

<button onmousedown="mouseDown()" onmouseup="mouseUp()">Click me</button>

Javascript

<script>
var click = false;
function mouseDown() {
    click = true;
    console.log('Button being clicked');
}
function mouseUp() {
    click = false;
    console.log('Button not being clicked');
}
setInterval(function(){
    if (click === false) {  
        console.log('Button not being clicked');
    } else if (click === true) {
        console.log('Button being clicked');
    }
}, 1000)
</script>

An alternative solution, and much more in depth answer can be found here.

Community
  • 1
  • 1
enolam
  • 221
  • 1
  • 6
0

As George stated, you are looking for the mousedown() event. It fires exactly when the click happens not after it's been clicked.

http://api.jquery.com/mousedown/

EricBellDesigns
  • 955
  • 1
  • 9
  • 33
0
  if (document.getElementsByTagName('button')[0].onmousedown)

You are missing the s after elements. It returns an array, Hence the [0]. If this isn't the first button on the page than this won't work, Use the code below if there's more than 1 button,

var buttons=document.getElementsByTagName('button');
for(var i=0;i > buttons.length; i++){
  buttons[i].addEventlistener("mousedown", MyFunction);
}

This will call a function called MyFunction on the press of any buttons

Billy
  • 2,448
  • 1
  • 10
  • 13
  • Yes I've tried this, but my aim is to check if a button is being clicked, and not have a function which is being called at a click. So it's kind of the other way around. Thanks anyway! – user274595 Nov 18 '14 at 15:36