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.

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

perfect! why didn't I think of that? :) Thank you.
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.
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.
i recommend to use "|" (pipe) instead of period or colon as a separator.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.