views:

351

answers:

2

I would like to replace a image with another image when a link is clicked. I have three images that each go to a specific link. So for instance, link one needs image 1, link 2 image two. etc... I've figured out how to do the replacement:

  $(function() {
  $("a#t2").click(function() {
        $("#floatleft img").replaceWith('<img src="images/image1.jpg" />');
        });
  });

<div id="floatleft">
    <img src="images/about.jpg" />
</div>
<div id="content">
    <ul id="abouttabs">
    <li><a id="t1" href="#tab1"><img src="images/menu1.png" alt"menu1" /></a></li>
    <li><a id="t2" href="#tab2"><img src="images/menu2.png" alt"menu2" /></a></li>
    <li><a id="t3" href="#tab3"><img src="images/menu3.png" alt"menu3" /></a></li>
</ul>

So as you can see I have three tabs with ids of t1,t2 and t3. I'd like to replace t1 with image1, t2 with image2, and t3 with image3 when the respective links are clicked. I can obviously do this by making three functions of the above code, but I was wondering if there is an easier way to do this with a each function or something.

Obviously the best way would be to have the image inside the div tab, but I can't do that because it scrolls and having the image in the tab makes it scroll as well. I suppose I could have it scroll with the page, but I don't like how that looks. So I figured I'd try a simple jQuery solution...

+2  A: 

Try this:

<script type="text/javascript">
$(function() {
  $("#abouttabs li a").click(function() {
    var newImgSrc = "images/image_" + this.id + ".jpg";
    $("#floatleft img").attr("src", newImgSrc);
   });
});
 </script>

Inside a jQuery handler, this is a reference to the DOM element (not the jQuery object!) that 'triggered' the event - so it'll let you work out which tab was clicked, and you can then extract that tab's element ID and replace the image source accordingly.

If you need to, you can isolate the numeric part of the element ID by doing some string/regex replacement in the first line of the handler (where we assign newImgSrc) - but it's much easier to just rename your images as image_t1.jpg, image_t2.jpg, image_t3.jpg.

Dylan Beattie
Awesome, this worked perfectly! Thanks for the help.Just a question though, is something like this relatively quick and CPU light? It seems like a simple enough process that it wouldn't cause any slowdown... But I'm just wondering.
Nori
Eh, NM. It seems negligible.
Nori
A: 

Give this a shot.

$('#abouttabs').find('a').click(function()
{
    var item = this.parentNode;
    var index = 0;

    do
    {
        item = item.previousSibling;
        index++;
    }
    while (item != null);

    $("#floatleft img").replaceWith('<img src="images/image' + index + '.jpg" />');
});
ChaosPandion
wow , why are you using plain js and jQuery combined ? settle for one of them and use it.
xxxxxxx
It is actually better to combine them. In general, jQuery is considerably slower.
ChaosPandion