views:

142

answers:

2

Hello,

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>
A: 

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).

cletus
+1  A: 

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.

Nick Craver
This is actually really what I had in mind. Works great so far. Thanks!
Adam
Nick, I've just realized this completely disables my navigation menu for the site. Any idea why those links no longer work when clicked?
Adam
@Adam - Is what you posted the navigation menu, or is it somewhere else entirely? If it's not...is **this** `<ul>` wrapped in an element with an ID or something?
Nick Craver
I might have corrected my own problem. My nav menu was also nested in ul/li...so i changed them to divs (sigh) and now it works.
Adam
@Adam - The alternative is to change the selector for this, if this menu is wrapped in say a `<div id="wrap"></div>` you could change the selector from `"li a"` to `"#wrap li a"` so it only handles clicks inside this, and not your nav menu.
Nick Craver
Perfect. Thanks man!
Adam