0

If I have multiple div boxes lined up (not overlapping), how can I detect which box is clicked?

For example, here is pseudocode:

HTML:

<div id="box1" onClick="clicked()">Box 1</div>
<div id="box2" onClick="clicked()">Box 2</div>
<div id="box3" onclick="clicked()">Box 3</div>

JS:

function clicked(){
    var first="box1";
    var second="box2";
    var third="box3";

    if (the div id of what you clicked is equal to first)
       /*do something here*/
    if (the div id of what you clicked is equal to second)
       /*do something here*/
    etc
    etc
}

My main problem is that I don't know how to properly write the if statement. I'm not sure how to get the div's id that you clicked in JavaScript. I'm thinking of something like this:

if (document.getElementById() = first)
     /*do stuff*/

I'm aware that I can solve this problem by having three different functions such as clicked1(), clicked2(), and clicked3(), but I would prefer not to have so many functions.

Any help is appreciated, thank you.

David Archibald
  • 1,431
  • 14
  • 27
Cait
  • 61
  • 6
  • are you using jQuery? – Moose Jan 13 '17 at 21:31
  • 3
    `event.target.id`? – putvande Jan 13 '17 at 21:31
  • 2
    Hint: the handler can take arguments. Inside the very first argument you will find what you need. – Wiktor Zychla Jan 13 '17 at 21:31
  • 2
    Change `onclick="clicked()"` to `onclick="clicked(this)"`. Then, add the parameter to your function: `function clicked(e) {...`. Finally, you can get the id by doing `var myId = e.id` inside the function. – Tyler Roper Jan 13 '17 at 21:32
  • I'm not using jQuery right now, but I can learn to implement it if that's the best way to go. – Cait Jan 13 '17 at 21:33
  • Unless you cannot use jQuery in your project I recommend you to use it always! Simplifies a lot your Javascript code. – Fernando Fradegrada Jan 13 '17 at 21:34
  • 5
    @FernandoFradegrada - That is, I'm afraid, a terrible piece of advice. – allnodcoms Jan 13 '17 at 21:35
  • I will use Santi's method for now and I will look into jQuery too. You guys are the best, thanks again! – Cait Jan 13 '17 at 21:36
  • Just as a scale of what you know, is this pseudo code because you're learning the basics such as [comparison operators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators), or is this pseudo code for a different reason? – David Archibald Jan 13 '17 at 21:57
  • I called it pseudo code because I thought that word means "here's code that doesn't actually work because it's just for summing up the general functions". Sorry if I'm using the word wrong! And yes, I am learning the basics right now. – Cait Jan 13 '17 at 22:26
  • Another idea; use different event handlers for each `div`. Unless you have shared code that all boxes share (which perhaps could be refactored to a separate function), there's no reason to use the same function for all of them... – Heretic Monkey Jan 13 '17 at 22:38
  • Possible duplicate of [Getting the ID of the element that fired an event](http://stackoverflow.com/questions/48239/getting-the-id-of-the-element-that-fired-an-event) – Heretic Monkey Jan 13 '17 at 22:38
  • You're totally right @Cait, just wanted to see how much I needed to explain in my question. If you're confused about anything in my answer, just tell me. Also, have any of the answers worked yet? – David Archibald Jan 14 '17 at 19:08

3 Answers3

3

Pure Javascript has a built in target in the event object. This is basically the opposite of getElementById, its basically getIdByElement(though this method doesn't exist). To access it all you need to do is edit your HTML from onClick="clicked()" to onClick="clicked(event)" and change your clicked function into code similar to this:

function clicked(event) {
  var id = event.target.id,
      first = 'box1',
      second = 'box2',
      third = 'box3';
  if(id === first) {
    ...
  } else if(id === second) {
    ...
  } else if(id === third) {
    ...
  }
}

To explain why this works, when a JavaScript event is fired you get an object about it, it looks like this: mousevent picture

This is so that you can get certain details about what happened. In this case, you wanted the target id. This works by selecting all divs on the page. Also to shorten the code if you want, you can pass in this instead and do this.id. Such as:

function clicked(reference) { //pass in this instead of event
  let id = reference.id;
  ...
}

Here is an example of it in work:

function clicked(event) {
  let p = document.getElementById('clicked-item')
  p.textContent = event.target.id + ' clicked';
}
<div id="box1" onClick="clicked(event)">Box 1</div>
<div id="box2" onClick="clicked(event)">Box 2</div>
<div id="box3" onclick="clicked(event)">Box 3</div>
<p id="clicked-item">none clicked</p>

It is a good idea to separate HTML and JS(though not 100% necessary). So to remove the onClick attribute on each element do something like this:

let selector = document.getElementsByTagName('div')
for(let element of selector) {
  element.addEventListener('click', function(event) {
    clicked(event);
  });
}

The code starts by getting all elements that are a div with getElementsByTagName, though you can use other selectors too. Then using a for loop we loop through all the divs and add an onClick event running clicked.

David Archibald
  • 1,431
  • 14
  • 27
1

You could make this work using inline event handlers but it'd be better to move your binding code to your actual scripts. You can still use one function, just apply it to each element.

The click handler will receive an event object which gives information about the click. Part of that is the .target property which will give you the source of the click event i.e, the element you clicked on.

function clicked(e) {
  var target = e.target;
  console.log(target.id);
}

document.querySelector('#box1').addEventListener('click', clicked);
document.querySelector('#box2').addEventListener('click', clicked);
document.querySelector('#box3').addEventListener('click', clicked);
.box {
  float: left;
  width: 100px;
  height: 100px;
  margin-right: 2px;
  background-color: #000;
  color: #EEE;
}
<div id="box1" class="box">Box 1</div>
<div id="box2" class="box">Box 2</div>
<div id="box3" class="box">Box 3</div>

If you're hellbent on using inline bindings, the simplest way to do this would be to pass this into your function call. That will pass the element directly.

function clicked(target) {
  console.log(target.id);
}
.box {
  float: left;
  width: 100px;
  height: 100px;
  margin-right: 2px;
  background-color: #000;
  color: #EEE;
}
<div id="box1" class="box" onclick="clicked(this)">Box 1</div>
<div id="box2" class="box" onclick="clicked(this)">Box 2</div>
<div id="box3" class="box" onclick="clicked(this)">Box 3</div>
Mike Cluck
  • 31,869
  • 13
  • 80
  • 91
0

By adding clicked(this) it selects the div you click on and returns that specific div's data.

<div id="box1" onClick="clicked(this)">Box 1</div>
<div id="box2" onClick="clicked(this)">Box 2</div>
<div id="box3" onclick="clicked(this)">Box 3</div>

By adding the div as a parameter it specifies the div you clicked on's internal data, and adding a switch statement to trigger a specific response to each div.

function clicked(div) {
  if(div.id = 'box1') { 
    console.log('1');
  } else if(div.id = 'box2') {
    console.log('2');
  } else if(div.id = 'box3') {
    console.log('3');
  }
}