0

I have the following HTML

<a onclick="hi('#i_15', 'second_img.jpg'); return false;" href="http://google.com">
<img id="i_15" src="first_img.jpg" />
</a>

So, I don't want it to follow to google.com when it's clicked, but instead just call the hi function:

function hi(id, file){
$(id).attr("src", file);
}

This is supposed to enlarge the image (by swapping first_img.jpg to second_img.jpg.) What can I do if I want to swap it back again? As in, click on the swapped image (second_img.jpg) and have it changed back to first_img.jpg; a reversal of what the hi function does.

2
  • Are you first_img and second_img named in similar way? like 'image1_small' and 'image1_large' for example? Commented Feb 15, 2012 at 14:34
  • No, they're not. In fact, they're generated with PHP, but I'm just using HTML here to keep it simple. Commented Feb 15, 2012 at 14:36

2 Answers 2

2

As for not navigating to google.com when clicked, you can just change the href to be: href="#".

For the image swap, why not make your hi function work both ways, as a toggle? You could do this:

<a onclick="swapImage('#i_15', 'first_img.jpg', 'second_img.jpg');" href="#" >
    <img id="i_15" src="first_img.jpg" />
</a>

function swapImage(id, firstImage, secondImage) {
    var imageToLoad = $(id).attr("src") == firstImage ? secondImage : firstImage;

    $(id).attr("src", imageToLoad);
}
Sign up to request clarification or add additional context in comments.

6 Comments

I would take this further by passing "this" rather than an ID.
@Diodeus: this would reference the anchor element, but I do agree that changing the argument to something like "element" and passing in $('#i_15') (and changing the references appropriately) would probably be better.
You still have to deal with the page refreshing if you use this code. I think you need to add something to keep that from happening.
@Alex: Despite fragment identifiers causing history, they do not cause a page reload. See this article, item number 4. If the OP doesn't want this link to cause history, then he would indeed have to make a change to prevent that.
Interesting, then what exactly does cause the page to refresh when you click on a link? I need to look into this a bit more. Thanks for the info.
|
0

Something like this in your hi() function should work.

function hi(id, file){
    var $id = $(id);
    if($id.attr("src") == file)
    {
        $id.attr("src", $.data($id, "orig"));
    }
    else
    {
        $.data($id, "orig", $id.attr("src"));
        $id.attr("src", file);
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.