-1

I want to set up a page that has the following:

Bob
Mary
Sue
Jane

<img src="none.jpg">
<img src="Bob.jpg">
<img src="Mary.jpg">
<img src="Sue.jpg">
<img src="Jane.jpg">

All of the images are initially invisible (display: none;), except none.jpg. When Bob is clicked on, none should disappear, and Bob should become visible. What's the easiest way to go about this?

JavaScript/JQuery are what I'm trying to use. I've found methods that can toggle the display attribute, but it is clunky in that it requires me sending commands regarding ALL of the associated images.

I know the solution involves loading all of the images and then just changing their visibility, but changing the source will solve the problem stated above.

Anders
  • 8,307
  • 9
  • 56
  • 88
paperfairy
  • 57
  • 6

1 Answers1

1

First of all, give all the images a class (lets call it picture) and all the name links another one (lets call that one name).

//When a name is clicked.
$(".name").click(function() {
    //Hide all the pictures.
    $(".picture").hide();
    //Get the name from the text of the link.
    var name = $(this).text();
    //Show the one with the right name.
    $(".picture[src=" + name + ".jpg]").show();
}

If you don't want to rely on the link text and the file names (for instance, if they do not always match), you can use a custom attribute like data-name that you can access in jQuery with .attr("data-name").

As pointed out in comments, you could also have just one image (lets give it the id picture this time), and change its src attribute:

$(".name").click(function() {
    //Get the name from the text of the link.
    var name = $(this).text();
    //Change the src attribute.
    $("#picture").attr("src", name + ".png");
});

Please note that this second approach will not load all the images when the page loads. Instead they will only load when the link is clicked. This can be good (if there are many and all of them might not be needed), or bad (if the user having to wait for them is a problem). You can get around it by preloading.

Also, if you want to set other attributes than src as well (like alt) it might be easier with the first approach.

Disclaimar: I have not tested the code.

Community
  • 1
  • 1
Anders
  • 8,307
  • 9
  • 56
  • 88
  • This would work, however, I think it would be more straight forward to use just one `img` tag and change the `src` property – Wesley Smith Oct 08 '15 at 21:13
  • The advantage of this one is that it loads all the images when the page loads, not when they are shown (you could force that with JS using the src method as well, though). Also if the images have other attributes that differ (like `alt`) they will be swapped automatically as well. – Anders Oct 08 '15 at 21:15