1

I'm making a website. I want to have a table and when I click on a cell, a "window" will appear right below the cell. As I have it now, I pass the ID of the cell as an argument to myFunction(). Which is then searched for so that I can use the element and find its position. I feel that this is a pretty bad way of doing this. I get the result I want, but having to pass the ID as a hard coded argument seem fragile.

<td id="player 1" onclick="myFunction('player 1')">

function myFunction(id_name) {
    var element = document.getElementById(id_name);
    var tmp = element.getBoundingClientRect();

    x_pos = tmp['x'];
    y_pos = tmp['y'];
    height = tmp['height']

    var dr = document.getElementById("myDropdown");
    dr.style.position = "absolute";
    dr.style.left = x_pos+'px'
    dr.style.top = y_pos+height+'px'

    dr.classList.toggle("show");
}

lissettdm
  • 12,267
  • 1
  • 18
  • 39
  • 1
    Does this answer your question? [How to get the element clicked (for the whole document)?](https://stackoverflow.com/questions/9012537/how-to-get-the-element-clicked-for-the-whole-document) Research how to use event target : https://www.w3schools.com/jsref/event_target.asp – ikiK Oct 13 '20 at 19:47

1 Answers1

1

You can pass the event to your function instead of a hard coded string id.

onclick="myFunction(event)"

Change the definition of your function to accept the event

function myFunction(e)

The event object will contain information about the element that raised the event (target).

Event.target A reference to the target to which the event was originally dispatched.

hijinxbassist
  • 3,667
  • 1
  • 18
  • 23