7

I'm trying to implement a simple rollover tooltip for images on a page where when you roll over an image, you get a little tooltip window and have the contents loaded from a database via AJAX.

I can hack this together quickly but I wanted an elegant way of doing this without using any inline JS.

So my question is: If I capture the rollover event inside my external .js file, how do I pass it the database ID?

I'm using jQuery so I would do something like this:

$('.item_roll').mouseover(function() {
  //show tooltip and load ajax content
}

and my HTML would be something like this:

<img src="thumb.png" class="item_roll" />

Without calling a function from the img tag, how do I send the JS call above the database id? I hope that makes sense.

Thanks.

givp
  • 2,494
  • 6
  • 31
  • 30

1 Answers1

7

I recommend having both a class and an id in the image tag:

<img src="thumb.png" id="id_28436379" class="item_roll" />

Then in your jQuery event, you can access that like so:

$(".item_roll").mouseover(function(event){
    alert( event.target.id.split("_")[1] );  // displays 28436379
});

This should let you access the database id by making it the id of the image tag.

EDIT: After reading some helpful comments, I've changed my answer so that the id does not start with an integer, since this is nonstandard and might not work in all browsers. As you can see, the split/[] code extracts the id number from the id string.

Eli Courtwright
  • 186,300
  • 67
  • 213
  • 256
  • perfect! why didn't I think of that? :) Thank you. – givp Feb 27 '09 at 14:20
  • Interesting; I actually tested this in Firefox and it worked, but if you're saying that it's invalid then maybe that's just Firefox trying to do the right thing even though I've used an invalid id. – Eli Courtwright Feb 27 '09 at 15:27
  • hmm, works for me in Safari too. But you could just add something like this: id="myid-1234" then strip it out before querying your db. – givp Feb 27 '09 at 16:51
  • 1
    As for valid IDs, refer http://stackoverflow.com/questions/70579/what-is-a-valid-value-for-id-attributes-in-html – cletus Feb 27 '09 at 21:49
  • i recommend to use "|" (pipe) instead of period or colon as a separator. – Adam Right Jun 05 '11 at 10:35