Tutorial :Replace text in div when image is clicked


I'm trying to replace certain text inside the div "info" when an image (which serve as links) is clicked. I'm just unsure of what methods could do this. I would prefer this be jquery.

My code so far looks like:

<div class="info">  <p>I would like this text replaced</p>  <script>  </script>  </div><!--end info-->      <li><a href="1.jpg"><img src="1-s.png" width="55" height="55" alt="" class="latest_img" /></a><p>Replace the div "info" text with the text here when clicked on</p></li>  


I think this is what you're after:

$(function() {    $("li a").click(function() {      $("div.info p").text($(this).next().text());      return false;    });  });  

This allows a bit more flexibility in the clicking, also note you need to wrap the click handler in a document.ready function like I have above...this way it waits until the DOM is ready to bind, once the elements it should bind to are there and ready.


Something like this should do the job:

$(function() {    $("a:has(img.latest_img)").click(function() {      $("div.info p").text($(this).next().text());      return false;    });  });  

Let me explain how it works.

The anchor has no class or ID unfortunately but you can still find it with a:has(img.latest_img), meaning all anchors that have a descendant image wit a class of "latest_img".

The relevant paragraph can be found and its text replaced with $("div.info p").text().

The text to replace it with can be found in any number of ways. I've simplest chosen $(this).next() to get a reference to it. You could just as easily do $(this).closest("li").children("p") or any number of other selectors. Note: this in an event handler refers to the source of the event.

Lastly, the click handler returns false to stop event propagation. Otherwise the anchor will navigate the browser to 1.jpg (it's href attribute).

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »