newstudent
newstudent

Reputation: 31

Onclick Event on Text to Reveal Image

I am new to coding but I have lots of basic knowledge about HTML, CSS, Javascript, and jQuery. I want one of my images to appear when I click on text but am having trouble executing it properly.

I'm creating a restaurant site where you click the text and the image of food appears below. I made the text be class="item" in my css. I just want to click on it and have an image appear.

Is it possible to achieve all this with just html and css or should I use a plugin.

HTML:

<p><strong><span class="item">text</span></strong></p> 

<img src="images/sample.png">

CSS for "item":

.item { color: #B24005;
    font-size: 20px;
    text-align: left
}
.item:hover { color: #00B295;
          font-size: 20px;
          text-align: left
}

Upvotes: 1

Views: 4096

Answers (2)

Calo
Calo

Reputation: 36

you could do this in just one line:

<p onclick="window.location.href='pathToYourImage'">text</p>

Upvotes: 0

Gildas.Tambo
Gildas.Tambo

Reputation: 22643

You can use jquery, just add class myImg to your image with display:none;

$(".item").on("click", function(){
   $(".myImg").fadeIn("slow"); //$(".myImg").show();
});

LIVE DEMO

Pure javascript would be:

function showImage() {
  var image = document.querySelector(".myImg");
  image.style["display"] = "block";
}

// add event listener to text
var el = document.querySelector(".item");
el.addEventListener("click", showImage, false);

CSS:

.myImg{
   display:none;
}

LIVE DEMO

Upvotes: 1

Related Questions