Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I detect if something is being clicked in JavaScript? (without using jQuery) [duplicate]

I would like to create a boolean function that can detect whether a certain element is being clicked and then output true or false. I want to do this in pure JavaScript with no jQuery, and my idea looks something like this:

function clicked(whatever-element-I-want) {

  if(whatever-element-I-want==clicked) {
    return true;
  } else {
    return false;
  }
}

I know this question probably seems really stupid, but I have been confused by everything I have come across so far and would really like a nice, simple explained answer.

like image 359
theonlygusti Avatar asked Feb 25 '14 15:02

theonlygusti


1 Answers

Usually HTML elements don't track the state, whether they are clicked or not. Instead, when an element is clicked it will fire a click event. To keep track of the clicks on an element you can store the state in a variable and update it when the click event is fired by that element:

HTML:

<div id="myElement">Click me!</div>

JS:

var elementIsClicked = false; // declare the variable that tracks the state
function clickHandler(){ // declare a function that updates the state
  elementIsClicked = true;
}

var element = document.getElementById('myElement'); // grab a reference to your element
element.addEventListener('click', clickHandler); // associate the function above with the click event

Note that by the time you click the element all other code on the page will have been executed already. Generally with event based programming you want to do things when stuff happens. Here is how you can check from time to time if the element has been clicked:

// check if the element has been clicked every 2 seconds:
function isElementClicked (){
  console.log(elementIsClicked ? 'CLICKED' : 'NOT');
}
setInterval(isElementClicked, 2000);
like image 141
Tibos Avatar answered Nov 11 '22 03:11

Tibos