Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery tooltip + ajax content

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.

like image 937
givp Avatar asked Feb 27 '09 14:02

givp


1 Answers

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.

like image 120
Eli Courtwright Avatar answered Sep 20 '22 14:09

Eli Courtwright