jQuery: Make div clickable

ยท

1 min read

This jQuery snippet makes a div clickable.

HTML mocup

<div class="tile tile-clickable">
  <h2>Tile Title HERE</h2>
  <p>Duis Lorem mollit voluptate cillum velit est veniam mollit ex nulla et sunt.</p>
  <a href="https://hashnode.com/">Read More</a>
</div>

jQuery Snippet

(function ($) {

  $(document).ready(function() {

      if($('.tile-clickable').length){ //Check if tile-clickable class exist
        $('.tile-clickable').click(function() {
          window.location = $(this).find("a").attr("href");
          return false;
        });
      }

  });

})(jQuery);

jQuery Snippet with open new window target="_blank"

(function ($) {

  $(document).ready(function() {

      if($('.tile-clickable').length){ //Check if tile-clickable class exist
        $('.tile-clickable').click(function() {
          var link_url = $(this).find('a').attr('href');
          var target_attr = $(this).find('a').attr('target');
          if (target_attr == '_blank') {
              window.open(link_url);
          } else {
              window.location.href = link_url;
          }
          return false;
        });
      }

  });

})(jQuery);

This simple code makes the UI lot more functional. You can add a drop shadow or animation on hover to show the tile is clickable. This works on mobile/touch screen as well.

CSS Example

.tile-clickable {
    position: relative;
    top: 0;
    transition: 0.3s;
}
.tile-clickable:hover {
    top: -5px; //on hover tile move up
    box-shadow: 30px 40px 99px 0px rgb(76 90 128 / 31%); //on hover add drop shadow
}

Have fun ๐Ÿ™Œ

ย