My dom looks like this:

<div class="profile">
       <a href="#"><img src="/img1.gif" /></a> <b>100</b>
       <a href="#"><img src="/img2.gif" /></a>

Ok so I have many of these elements on my page, so using jQuery I bind all the events like this:

$(".profile").live('click', myCallback);

var myCallback = function(event) {
         // ??

Now, when someone clicks on the 1st hyperlink, I want to change the image to "/img1_on.gif", then make a ajax call to a webpage and replace the value between the with the value returned.

The same thing happends when the other image is clicked, except the image changes to "/img2_on.gif" and it goes to another URL.

Would it be easier if I converted the into a div and add some css?

No correct solution


$(".profile a").live("click", function(e) {
  var temp = $("img", this);
  var temp2 = temp.attr("src").split('.');

  temp.attr("src", temp2[0] + "_on" + temp2[1]);

  // Ajax goes here.


You had it so that the div was the one being clicked, and not the links inside of the div. This function should work for you, assuming you fill in the ajax part.

I'm not entirely sure what you're asking, but if you want to find the element that caused the click event, you can use, and then $( from there. Something like this.

$(".profile").live('click', function(e){

For example, select sub-links only (this will be the link):

$(".profile > a")

For images (this will be the image to manipulate):

$(".profile > a > img").live("click", function(event) {
    var src = $(this).attr("src");
    $(this).attr("src", src.replace(".gif", "_on.gif"));
    // ajax call in any way you prefer
    // in callback you can switch button state back

You'll find this post exactly explaining what the event order is and what does it mean to listen to an event during the capturing or bubbling phase and when to cancel out further event propagation.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top