6

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.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
theonlygusti
  • 11,032
  • 11
  • 64
  • 119

3 Answers3

20

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);
Tibos
  • 27,507
  • 4
  • 50
  • 64
  • 1
    Wow! This is just the type of answer I needed, but is there no way in which it can be possible for the function to execute the instant the element is clicked, rather than waiting some time and re-checking whether the element has been clicked? – theonlygusti Feb 25 '14 at 15:42
  • 1
    There is code that is executed as soon as the element is clicked, that is the `clickHandler` function. The `setInterval` part was just to help you notice that the elementIsClicked variable changes at some point in time. – Tibos Feb 25 '14 at 15:46
  • 1
    Oh, awesome. So if I include the code I want executed within the `clickHandler` function it will execute instantaneously, rather than waiting two seconds? – theonlygusti Feb 25 '14 at 15:59
  • 1
    @user3310334 Exactly. – Tibos Feb 25 '14 at 16:12
  • 1
    @Tibos what if I need to check the status on multiple elements? Say in a for loop? – CodeConnoisseur Jan 25 '21 at 15:59
2
target.addEventListener(type, listener[, useCapture]);

https://developer.mozilla.org/en-US/docs/Web/API/EventTarget.addEventListener

From the docs here is your example:

html:

<table id="outside">
    <tr><td id="t1">one</td></tr>
    <tr><td id="t2">two</td></tr>
</table>

javascript:

// some user defined function
// to change the content of t2
function modifyText(new_text) {
  var t2 = document.getElementById("t2");
  t2.firstChild.nodeValue = new_text;    
}

// get reference to the DOM element with id = "outside" 
// so that we can add whatever listeners: click, change etc.
// Note: not all DOM elements can handle all listeners.    
var el = document.getElementById("outside");

// attach event types to that reference and let it know how
// to handle that event via callback or a function.
// this could be inline function (as in my example below)
// or you could define a function outside and pass its name
// function add(a,b){ return a + b;}
// el.addEventListener("click", add, false);
el.addEventListener("click", function(){
                                modifyText("four")
                             }, false);
Vikram
  • 4,162
  • 8
  • 43
  • 65
1

This will alert "clicked" when a button with id my-button is clicked:

HTML

<button id="my-button">Click me</button>

JavaScript

var el = document.getElementById("my-button");

if (el.addEventListener) {
    el.addEventListener("click", function() {
        alert("clicked");
    }, false);
} else { //IE8 support
    el.attachEvent("onclick", function() { 
        alert("clicked");
    });
}

http://jsbin.com/jayutuze/1/edit

Now, from your question I gather that you want some sort of negative feedback if the button is not pressed, but that's a bit complicated: should it be not pressed for a period of time? Or should it not be pressed when hovering over it? Please explain what you're trying to achieve.

Phortuin
  • 770
  • 4
  • 20