Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Only target parent with event.target?

HTML:

<div onclick="doSomething()" id="parent">
    <div id="child"></div>
</div>

CSS:

#parent {
    background-color: blue;
    width: 100%;
    height: 100px;
}

#child {
    background-color: green;
    width: 50%;
    height: inherit;
}

.myClass {
    background-color: red !important;
}

JS:

function doSomething() {
    event.target.className = ('myClass');
}

As you can see in this JSFIDDLE, upon clicking the child, instead of applying the class to the parent which triggers the function, it applies it to the child. I want to know how to avoid this and apply it to the parent no matter where I click inside of it. I am trying to avoid using the document.getElement(s)ByClass/Id method.
Any help?

like image 849
Austin Griner Avatar asked Aug 19 '15 21:08

Austin Griner


1 Answers

You can refer to the element that handles the event with currentTarget.

Identifies the current target for the event, as the event traverses the DOM. It always refers to the element the event handler has been attached to as opposed to event.target which identifies the element on which the event occurred.


However, instead of relying on the browser to provide a global event object, I would pass it to the function:

onclick="doSomething(event)"

You can also refer to the element the handler is bound to with this:

onclick="doSomething(event, this)"

Of course please consider to not use inline event handlers.

like image 86
Felix Kling Avatar answered Oct 03 '22 08:10

Felix Kling