views:

30927

answers:

6

To make click-able divs, I do:

<div class="clickable" url="http://google.com"&gt;
    blah blah
</div>

and then

$("div.clickable").click(
function()
{
    window.location = $(this).attr("url");
});

I don't know if this is the best way, but it works perfectly with me, except for one issue: If the div contains a click-able element, such as <a href="...">, and the user clicks on the hyperlink, both the hyperlink and div's-clickable are called

This is especially a problem when the anchor tag is referring to a javascript AJAX function, which executes the AJAX function AND follows the link in the 'url' attribute of the div.

Anyway around this?

+4  A: 

$("div.clickable").click( function(event) { window.location = $(this).attr("url"); event.preventDefault(); });

Sergey Ilinsky
+1  A: 

I know that if you were to change that to an href you'd do:

$("a#link1").click(function(event) {
  event.preventDefault();
  $('div.link1').show();
  //whatever else you want to do
});

so if you want to keep it with the div, I'd try

$("div.clickable").click(function(event) {
  event.preventDefault();
  window.location = $(this).attr("url");
});
Leanan
+13  A: 

If you return "false" from your function it'll stop the event bubbling, so only your first event handler will get triggered (ie. your anchor will not see the click).

$("div.clickable").click(
function()
{
    window.location = $(this).attr("url");
    return false;
});
Parand
Use preventDefault(), not return false!
Rosdi
ie6 gives js error
henrijs
+3  A: 
Sander Aarts
A: 

Do you mean pulling data from a database? I was in the middle of making that tutorial a few weeks ago but stopped, don’t know why. I would assume you are using MySQL?

alexa information
A: 

@parand: that works pretty fine

Erik