1

I have a three button navigation panel, comprising of three divs and an anchor. On mouse over, myFunction() assigns a class to the three divs and anchor tag, for styling purposes.

<nav>
    <div id="btn1" class="button" onMouseOver="myFunction();">
    <div id="btn_bdr1">
    <div id="btn_bdr2">
        <a href="#"></a>
    </div>
    </div>
    </div>

    <div id="btn3" class="button" onMouseOver="myFunction();">
    <div id="btn_bdr1">
    <div id="btn_bdr2">
        <a href="#"></a>
    </div>
    </div>
   </div>

    <div id="btn2" class="button"  onMouseOver="myFunction();">
    <div id="btn_bdr1">
    <div id="btn_bdr2">
        <a href="#"></a>
    </div>
    </div>
    </div>
</nav>

What I need to do is find the ID of the div which called myFunction(), so I can make a change within the function to only the calling div, not all three.

Using JavaScript only, how can I go about doing this.

Thanks in advance.

3 Answers 3

5

There is two ways you can do is

1) Send an argument to the method with the div's name

Example

<div id="btn1" class="button" onMouseOver="myFunction('btn1')">

2) Send the element this

Example

<div id="btn1" class="button" onMouseOver="myFunction(this)">

In the javascript you can then do

myFunction(element) {
    //element is now the element you clicked on
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Fyllekanin, your answer is the closest to what I am after, though I've gone with myFunction(this.id) as I need the id, not the element. I'll update the post with the actual code block used.
0

You can use the event object and look at the target (e.target). This is a reference to the element itself so to get the ID you would simply access the element's id property. (e.target.id)

document.querySelectorAll('.a').forEach(function(ele, ind) {
  ele.addEventListener("mouseover", function(e) {
    console.log(e.target, e.target.id);
  })
});
.a {
  height: 40px;
  width: 40px;
  border: solid black 3px;
  margin-top: 5px;
}
<div class="a" id="one"></div>
<div class="a" id="two"></div>
<div class="a" id="three"></div>

Comments

0

You can call this.event.target from myFunction() to determine which element generated the event.

For example:

myFunction() {
   console.log("I was called by: ", this.event.target);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.