Search code examples
javascriptjqueryjquery-eventsevent-propagation

Jquery - fix hyperlinks inside of a toggled element


I am having an issue with some Jquery script that I have and I hope that someone can point me in the right direction.

I have a region that is initially hidden but upon being clicked it displays it's contents, clicked again it hides it's contents. Within this region are a series of hyperlinks. The trouble I am facing is that, when these links are clicked, instead of redirecting elsewhere the container is closing again. I can see why this is occurring but I am unsure how to fix it.

The Function:-

function toggleDisplay(itemToToggle, itemHeightOpen, itemHeightClosed) {
$(itemToToggle).toggle(
  function () {
    $(this).animate({ 'height': itemHeightClosed }).addClass('minus');
    },
      function () {
    $(this).animate({ 'height': itemHeightOpen }).removeClass('minus');
    });
 };

The Call:-

var heighttomatch = $('#inlineSummaryWrapper').height() + 28;
toggleDisplay('#inlineSummary', '1.2em', heighttomatch);

The html:-

<div id="inlineSummary" class="displayToggle">
  <h2>Summary</h2>
  <div id="inlineSummaryWrapper">
   <a href="/mylink">the link</a>
  </div>
</div>

I did try to wrap "The call" inside of a click action targeted at the H2 but that had a weird effect with the container opening and closing by itself, so I'm not sure what to do.


Solution

  • This happens because the click event on the link propagates. You can stop it with event.stopPropagation().

    function toggleDisplay(itemToToggle, itemHeightOpen, itemHeightClosed) {
        $(itemToToggle).find('a').click(function (e) {
            e.stopPropagation();
        });
        ...
    }