0
Catch an link with jQuery and prevent the href attr. to be followed
Ok this is part French, part english, because I’ve bee, search for hours on how to do this. Then I finally found the solution in the jQ documentation (yes RTFM!!) so I assume many people are looking for how to do that.
Markup
<a href="https://www.italic.fr">Ajouter au panier</a>
Purpose
Say you want to do something BEFORE the user reaches the « href » destination. Like pop-up an alert, animate something on the page, etc.
Usually this is not possible because a’s href attribute is immediately catched by the browser.
However jQuery (another) interesting function called preventDefault. Here we are going to abuse it 🙂
Sample
// ADD TO CART ACTION $('.addtocart').click(function(ev){ // prevent browser from following the href param ev.preventDefault(); // catch the href value var redirect = $(this).attr('href'); // make some animation of whatever $('#cart .count a:eq(1)').mouseover(function(){ if (!is_shown_cart) { $('#pop-in-cart').stop(true,true).hide().css('zIndex',999).slideDown(); is_shown_cart = true } }); // another annoying stuff alert('coucou'); // finally relocate the user to where the href says so. return $(location).attr('href',redirect); });
DATE 02 Déc 2010