tags:

views:

308

answers:

4

Hi,

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>
</div>

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?

+4  A: 
$(".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.

  e.preventDefault();
});

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.

instead of $(this).find('img') you can also do: $('img', this)
Pim Jager
I think $(this).find('img') is easier to read, though.
Paolo Bergantino
+1  A: 

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 e.target, and then $(e.target) from there. Something like this.

$(".profile").live('click', function(e){
  if($(e.target).is("a"))
     $(e.target).find("img").attr("src","/new/url.jpg");
});
Mark
A: 

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
});
Sergii
A: 

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.

kRON