Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

onclick event work for only buttons and not for glyphicon used with button

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>
like image 935
ch3t Avatar asked Nov 29 '25 05:11

ch3t


1 Answers

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');
}
like image 65
t.niese Avatar answered Dec 01 '25 18:12

t.niese