views:

219

answers:

3

I have an <a> inside a <TD>, and I'm trying to have clicks on the <TD>, but outside the <A>, act like they were clicks on the <a>. I'm almost there:

HTML:

<TD class="somethingPretty">
    <a href="someURL" class="anchor">Text</a>
</td>

JS:

$('.anchor').click(function(ev){return confirm("go ahead?");});
$('somethingPretty').click(function(ev){
    if($('.anchor').click()){
        document.location = $('.anchor').attr('href');
    }
}

The problem with this is that jQuery.click returns undefined, and I can't see how to get at the event object that's passed to the click handlers so I can interrogate it with isPropagationStopped and isDefaultPrevented. What's the right way to solve this problem?

A: 

How about this?


var a = $('.somethingPretty .anchor');
var td = $('.somethingPretty');

a.click( function(ev) { return confirm("go ahead?"); } );
td.click( function() { a.click(); } );
jsumners
This doesn't cause document.location to change.
DDaviesBrackett
No, I didn't write all of the code for you. But I did give you what should be a functional base you could understand and adapt.
jsumners
This answer's code was already in the example. =)
DDaviesBrackett
+1  A: 

Sometimes asking the question clearly is the best way to find an answer. Some strategic poking around the jQuery source led me to the following solution(using the markup above):

$('.somethingPretty').click(function(ev){
    var syntheticClick = new $.Event("click");
    syntheticClick.stopPropagation();
    $('.anchor').trigger(syntheticClick);
    if(syntheticClick.isDefaultPrevented()) return;
    document.location = $('.anchor').attr('href');
}

This works for all event handlers except live-bound ones (those don't execute; my users will have to learn to click the anchor itself for them!). The tricky part here is that trigger takes a jQuery.Event in addition to the documented string.

DDaviesBrackett
A: 

Did you try something like:

$("td.outer").add("td.outer a").click(function() { 
   // do stuff
});

You're going to want to find some way to ensure that whatever is in the function runs only once, since a click on the <a> will count both as a click on the <td> and the <a>.

Plan B