Search code examples
jqueryonclickhref

How to make Onclick code to not execute when a link is clicked


Not sure how to get this code to not fire if a hyperlink was clicked

$(document).ready(function () {

  $('.accordion-list > li > .answer').hide();

  $('.accordion-list > li').click(function () {
    if ($(this).hasClass("active")) {
          
      ////if link is clicked then exit this function////
       
      $(this).removeClass("active").find(".answer").slideUp();
      
    } else {
        
      $(".accordion-list > li.active .answer").slideUp();
      $(".accordion-list > li.active").removeClass("active");
      $(this).addClass("active").find(".answer").slideDown();
    }
    return false;
  });

Solution

  • Check the event target to get the clicked element (which could be a descendent of the <li>). If the target has any ancestors that are <a>s, stop the function.

    $('.accordion-list > li').click(function (event) {
        if ($(this).hasClass("active")) {
            if (event.target.closest('a')) {
                // an <a> was clicked
                return;
            }