I have a side menu that when clicked slides out to reveal a content panel. Based on the menu item clicked I obviously need different stuff to populate in the panel.
I wrote a function to operate the menu/panel and it partially works. However, I am trying to determine what to load based on event.target.id
(as the function takes event
) but it only has a value when I click very close to the edges of the linked square. When I click near the actual text which are h1
and h6
and have no id
's it doesn't work.
Live demo (click near the edges of the 'Styles' square and then in the middle): http://jsfiddle.net/mANuD/
<div id="application-frame">
<div class="panel"></div>
<ul id="slide-out-menu">
<li>
<a href="#" class="item" id="styles-menu">
<h1>S</h1>
<h6>Styles</h6>
</a>
</li>
<li>
<a href="#" class="item" id="designers-menu">
<h1>D</h1>
<h6>Designers</h6>
</a>
</li>
<li>
<a href="#" class="item" id="code-menu">
<h1>C</h1>
<h6>Code</h6>
</a>
</li>
<li>
<a href="#" class="item" id="help-menu">
<h1>?</h1>
<h6>Help</h6>
</a>
</li>
</ul>
</div>
How can I fix/improve this so that it doesn't matter where in the linked area I click?
To get the attribute of a target element in JavaScript you would simply use: e. target. getAttribute('id');
target are obsolete, not that Event. target itself is obsolete. The DOM (Living Standard) specification is not marked as obsolete and you should use that definition.
target in JavaScript? When an event is fired, the element that fires the event is known as the emitter. This element is what we call the target.
Change event.target.id
to event.currentTarget.id
or this.id
.
The event.target
is always the deepest element clicked, while event.currentTarget
or this
will point to the element to which the handler is bound, or to the element that the delegate selector matched.
It sounds like there's a border or padding on some of the descendant elements, and so event.target
is a descendant of the element on which the handler is (effectively) hooked up.
Two options:
Use this.id
to get the id
of the element the handler was (effectively) bound to. This usually does what you want. Updated Fiddle
I don't think you need it in this situation, but the other handy tool in the toolkit for this is closest
, which finds the first element matching a selector by looking at the element you give it, then its parent, then its parent, etc. So for instance, $(this).closest(".item").attr("id")
or $(event.target).closest(".item").attr("id")
(since the items you want have class item
). Updated Fiddle But again, I believe #1 is what you want in this case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With