views:

1179

answers:

1

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.

+5  A: 

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
perfect! why didn't I think of that? :) Thank you.
givp
As an aside, you should probably do $("img.item_roll")...
cletus
good tip, cletus. Thanks
givp
id starting with an integer :o) ....not valid
redsquare
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
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
As for valid IDs, refer http://stackoverflow.com/questions/70579/what-is-a-valid-value-for-id-attributes-in-html
cletus