Question

Objective

Two categories (i.e. dog and cat) of images, image and image caption. I want to click on that image and have it change to a picture of the second category, if you click again it changes to the other category. So somehow i need to define the images within one of two categories then alternate them on click.


HTML

<img src="img/dogImg.jpg" alt="" id="imgClickAndChange">
<h1 id="title">Dog Title</h1>
<p id="caption">caption for dog.</p>

Javascript

function changeImage() {

    if (document.getElementById("imgClickAndChange").src = "img/dogImg.jpg") 
    {
        document.getElementById("imgClickAndChange").src = "img/catImg.jpg";
        document.getElementById("title").innerHTML = "Cat Title";
        document.getElementById("caption").innerHTML = "caption for cat.";

    }
    else
    {
        document.getElementById("imgClickAndChange").src = "img/dogImg.jpg";
        document.getElementById("title").innerHTML = "Dog Title";
        document.getElementById("caption").innerHTML = "caption for dog.";
    }
}

var el = document.getElementById("imgClickAndChange");
el.addEventListener("click", changeImage, false);

Right now it seems to be changing to the cat info okay, but I can't figure out how to make it go back to dog. Having the caption for the dog in both the HTML and Javascript seem redundant. Is there a simpler way to do this whole thing? Thanks!

Was it helpful?

Solution

You've got an tiny mistake in your code.

Instead of

if (document.getElementById("imgClickAndChange").src = "img/dogImg.jpg")

do

if (document.getElementById("imgClickAndChange").src === "img/dogImg.jpg")

OTHER TIPS

With .src you get absolute path to the image. Use getAttribute instead

Try this code:

if (document.getElementById("imgClickAndChange").getAttribute("src") === "img/dogImg.jpg") {
    document.getElementById("imgClickAndChange").setAttribute("src", "img/dogImg.jpg")
    ...
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top