Search code examples
javascripthtmljquerycssonclicklistener

Add external link to an <a> element inside a Click Event Listener Div


I'm having trouble adding a link to a button inside a card. the card is wrapped in a div element which when clicked automatically expands and closes.

Is there anyway to remove this functionality just when clicking on the details button? So it acts as a normal link?

Here is the code: https://codepen.io/candroo/pen/wKEwRL

Card HTML:

<div class="card">
  <div class="card__image-holder">
    <img
      class="card__image"
      src="https://source.unsplash.com/300x225/?wave"
      alt="wave"
    />
  </div>
  <div class="card-title">
    <a href="#" class="toggle-info btn">
      <span class="left"></span>
      <span class="right"></span>
    </a>
    <h2>
      Card title
      <small>Image from unsplash.com</small>
    </h2>
  </div>
  <div class="card-flap flap1">
    <div class="card-description">
      This grid is an attempt to make something nice that works on touch
      devices. Ignoring hover states when they're not available etc.
    </div>
    <div class="card-flap flap2">
      <div class="card-actions">
        <a href="#" class="btn">Read more</a>
      </div>
    </div>
  </div>
</div>

JS:

$(document).ready(function () {
  var zindex = 10;

  $("div.card").click(function (e) {
    e.preventDefault();

    var isShowing = false;

    if ($(this).hasClass("show")) {
      isShowing = true;
    }

    if ($("div.cards").hasClass("showing")) {
      // a card is already in view
      $("div.card.show").removeClass("show");

      if (isShowing) {
        // this card was showing - reset the grid
        $("div.cards").removeClass("showing");
      } else {
        // this card isn't showing - get in with it
        $(this).css({ zIndex: zindex }).addClass("show");
      }

      zindex++;
    } else {
      // no cards in view
      $("div.cards").addClass("showing");
      $(this).css({ zIndex: zindex }).addClass("show");

      zindex++;
    }
  });
});

Solution

  • You can check the target of the event and see if it is an <a> using is()

    Something like:

    $("div.card").click(function (e) {
    
        // only run when not an `<a>`
        if(!$(e.target).is('a')){
           e.preventDefault();
           //the rest of your code 
           ....
        }
    });