Mike Mike - 2 months ago 7
HTML Question

Click event on <a> element not firing

My HTML is structured as below. I would like to give the clicked

<a>
element the class "active".

Although the debugger stops on the
click()
line, the code within the function is not being triggered.



$('#dropdownRow > div > a').on('click', function(e) {
$('#dropdownRow a.active').removeClass('active');
var $this = $(this);
if (!$this.hasClass('active')) {
$this.addClass('active');
}
e.preventDefault();
})

.active { color: red; }

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row" id="dropdownRow">
<div class="col-xs-3">
<a href="/xxx/">XXX</a>
</div>
<div class="col-xs-3">
<a href="/yyy/">YYY</a>
</div>
<div class="col-xs-3">
<a href="/zzz/">ZZZ</a>
</div>
</div>




Answer

It's possible you do not have the jQuery firing at the right time. I suggest wrapping it in a $(document).ready

https://learn.jquery.com/using-jquery-core/document-ready/

$( document ).ready(function() {
  // Add your code
  $('#dropdownRow > div > a').on('click', function(e) {
    $('#dropdownRow a.active').removeClass('active');
    var $this = $(this);
    if (!$this.hasClass('active')) {
      $this.addClass('active');
    }
    e.preventDefault();
  });
  // End code 
});