Reputation: 3080
I have alot of:
<li><a href="google.com">LINKY</a></li>
type links on my site and much prefere the whole Li to be clickable instead of just the text. So was thinking of applying some nice jquery that will hunt any $('li a') down and make it so when you click the <li>
it will trigger the click on a <a>
$('li a').each(function(index) {
$(this).parent().bind('click', function() {
$(this).children().click();
});
});
This fails to work but im not sure why? any ideas?
Upvotes: 1
Views: 306
Reputation: 322502
It is much simpler if you just bind the click event to the <li>
element.
Event bubbling will ensure that it is triggered when you click the <a>
as well.
Here's an example: http://jsfiddle.net/MB9Fm/
$('li:has( > a)').click(function() {
alert('I was clicked');
return false;
});
EDIT:
I may have misunderstood the intention for the click
handler. If all you wanted to do was visit the href location, I'd agree with the CSS solutions of possible. Otherwise, using js, do something like this:
$('li:has( > a)').click(function() {
window.location = $(this).children('a').attr('href');
});
The way you were calling .click()
in your comment would cause an infinite loop, an I'm not sure that it would actually take you to the href location anyway.
Upvotes: 2
Reputation: 34168
Look into the .delegate()
functionality added in 1.4.2, this is more suited to your desires.
$("li").delegate("a", "click", function(event){
//do what you want here
return false; //prevent default action and prevent bubbling up
});
Upvotes: 0
Reputation: 465
Try this:
$('li:has(a)').each(function() {
$(this).bind('click', function(index){
$(this).find('a').trigger('click');
});
});
Upvotes: -1
Reputation: 18522
Wouldn't it be better to stretch the anchor to the size of LI?
li > a {
display: block;
width: 100%;
/* optionally height: some height */
}
Upvotes: 3
Reputation: 284826
Calling click() on a link doesn't perform the default action (going to the address). You could manually make a click handler:
$('li a').each(function(index) {
$(this).parent().bind('click', function() {
window.location = $(this).children().attr('href');
});
});
Upvotes: 1