views:

81

answers:

2

I've been looking for a solution the last few days, I didn't really found exactly what I'm looking for.

I have something like this:

<ul>
   <li>
      <a href="http://www.link.com" class="li-url"></a>
      <h1>Title</h1>
      Lorem ipsum dolor <a href="http://www.something.com"&gt;Something&lt;/a&gt;. Etc, blah blah.
   </li>
</ul>

What I need:

  • Click on the LI element: Go to www.link.com
  • Click on "Something" inside the LI: Go to www.something.com (And DON'T go to www.link.com)

(And I don't know if it's possible, but it would be great if I could click on the LI element and if I'm holding my "alt" key on my keyboard, the link would open in a new tab... like any other link. But I don't know if that's possible)

+1  A: 

Here's one way. Tested on jsfiddle.net and it worked for me.

$('li').click(function() {
    window.location = $(this).find(':first-child').attr('href');
});​​​​​​​​​

As far as the alt key goes, I'm not sure that's possible. I'd let the user decide if they want to open a link in a new tab/window anyway.

Gregg
If you post the link to jsFiddle it tends to be considered a good thing. +1
David Thomas
Thanks Gregg. That work's just fine, except that when I click in "something", it also goes to link.com. (you can see that if you alt+click, the new tab would go to your click something.com, but the current tab goes to link.com)
Santiago
+1  A: 

You may also be interested in event.stopPropagation(). Which will allow you to prevent the event from bubbling up (aka notifying the li of the click).

$('ul > li').click(function(e) {
    // Go to link.com
}).children('a').click(function(e) {
    e.stopPropagation();
    // Go to something.com
});

​http://jsfiddle.net/erF3S/

Robert
It seems it's not working. When I click on the "li" it doesn't goes to link.com
Santiago
Sorry, I assumed you knew a little Javascript. Add `window.location = "ADDRESSHERE";` in place of my comments. Replace ADDRESSHERE with the website URL you want it ot go to.
Robert