Ian Hoar – Passion for Technology – Geeking Out - Technology, Web, Toys, Games, Design, Entertainment, Gadgets, & Geeking Out

jQuery: How to get links to work in toggled or dynamic content

jQueryjQuery still never ceases to amaze me. The developers of this fantastic library seem to have thought of everything, and the only real challenge for us end users is hunting through the API. Recently I was tasked with creating slide out toggle boxes that had links embedded within them. The problem was that the animation would be triggered before the links, thus rending them useless. Luckily like many things with jQuery the fix is simple and I will demonstrate with two examples.

The problem


$jQuery('#toggle-test').toggle(function() {
  $jQuery(this).stop(true, true).animate({width : 500});
}, function() {
  $jQuery(this).stop(true, true).animate({width : 300});
});

Here is a block of content with an inline link that is a fully toggleable div element, but the link does not actually work.

As you can see in the example above, when clicking the link the toggle animation is triggered instead of the link destination.

The solution

$jQuery('#toggle-test2').toggle(function() {
  $jQuery("a").click(function(e) {
    e.stopPropagation();
  });
  $jQuery(this).stop(true, true).animate({width : 500});
}, function() {
  $jQuery(this).stop(true, true).animate({width : 300});
});
Here is a block of content with an inline link that is a fully toggleable div element and a working link.

The difference with the second example is that we have added a click event within the toggle and added the stopPropagation() method. This “Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event” thus allowing the link to take it’s normal course of action.

A more practical use of this would be clickable slide out boxes with links embedded or even a close button on a toggleable element. These are just some of the uses for stopPropagation(), so keep it handy in your arsenal of jQuery tools.

One Comment to “jQuery: How to get links to work in toggled or dynamic content”

Responses:

Your comments are important, join the conversation