views:

43

answers:

1

So, I have this <ol> with some events attached with the help of jQuery (1.4.2). All is done in the $(document).ready()-call.

The weird thing is that the click on the <li> does generate a click on the correnct <a> (I can see this by uncommenting the console.log()-part) but it does not navigate the UA. Why is this? Does event.stopPropagation() call event.preventDefault() internally or what?

I know I can do window.location.href = $('h3 a', this).eq(0).attr('href'); in the click event of the <li> but I really would like to know why it´s not working with the click-call.

Thanks in advance fellow SOers!

Teh codez:

HTML:

<ol class="news">
    <li>
        <img src="http://dummyimage.com/325x325/000/fff.jpg"&gt;
        <span class="date">12th of May</span>
        <h3><a href="http://example.com/lorem-ipsum"&gt;Lorem Ipsum</a></h3>
        <p>Nullam rhoncus, massa nec posuere rutrum, mauris metus ornare lacus, facilisis. Rhoncus purus dui vel lectus.</p>
    </li>
    <li>
        <span class="date">3rd of May</span>
        <h3><a href="http://example.com/lam-sum-idum"&gt;Lam sum idum</a></h3>
        <p>Mauris volutpat enim nec turpis pharetra consectetur. Cras faucibus mattis dignissim.</p>
    </li>
    <!-- many more LIs here... -->
</ol>

(and yes. The HTML 4.01 has been validated.)

JavaScript:

$('.news li').click(function () {
    $('h3 a', this).eq(0).click();
}).hover(function () {
    $(this).toggleClass('hover');
}).find('h3 a').click(function (e) {
    e.stopPropagation();// prevent recursion
    //console.log(this);
});
+2  A: 

This is normal, manually firing a click on an anchor does not follow the link, firing the "default event" is often not the case when simulating the action. Setting the location.href is the way to go here, like this:

$('.news li').click(function () {
    window.location.href = $(this).find('h3 a').attr('href');
}).hover(function () {
    $(this).toggleClass('hover');
}).find('h3 a').click(function (e) {
    e.stopPropagation(); //so ctrl+click works on the link, etc
});

As an aside, there's no need for the .eq(0), .attr('href') will get the href from the first element in the matched set.

Nick Craver
+1, with a friendly reminder - this will not work for links that have the target attribute set :-)
Andy E
Thanks for the clarification Nick.
anddoutoi