I have used bootstrap to create circular button with glyphicons and i want to change color of the button including glyphicon color as well. but when i click on glyphicon, onlclick event works for glyphicon only and not button. http://embed.plnkr.co/E1dUnkW1tmOCWqYkRaG5/
function setColor(e) {
var target = e.target,
status = e.target.classList.contains('btn-success');
e.target.classList.add(status ? 'btn-default' : 'btn-success');
e.target.classList.remove(status ? 'btn-success' : 'btn-default');
}
my bootstrap button
<button onclick="setColor(event)" type="button" class="btn btn-circle btn-lg"><span class="glyphicon glyphicon-search" style="margin: 0 0px;"></span></button>
Well it works, but Event.target is the element that fired/dispatched the event, and not the element you attached the listener to.
You are looking for Event.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.
So change your code to:
function setColor(e) {
var currentTarget = e.currentTarget,
status = e.currentTarget.classList.contains('btn-success');
e.currentTarget.classList.add(status ? 'btn-default' : 'btn-success');
e.currentTarget.classList.remove(status ? 'btn-success' : 'btn-default');
}
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