"Utilizing Javascript Toggling for Displaying and Concealing Content

I'm relatively new to JavaScript and struggling to make my code work as desired. Check out my JSFiddle example here.

I have 3 images and I want to be able to click on each image to reveal a hidden div. When the next image is clicked, I want it to hide the previous div and show the next one.

(Click Image 1 to see HiddenContent1, Click Image2 to hide HiddenContent1 and show HiddenContent2, and so forth.)

Here's My Code:

(I didn't include any JS because I honestly don't know where to begin.)

Thank you in advance!

#ImgContainer{
    text-align:center;
}

.Hidden{
    display:none;
}

.image:hover{
    border: 1px solid purple;
}

#HiddenContentContainer{
    text-align: center;
    min-height:50px;
    min-width:100%;
    border: 1px solid teal;
}
<div id="MainContainer">
    <div id="ImgContainer">
        <a href="#"><img id="image1" class="image" src="http://placehold.it/150" onmouseover="this.src='http://placehold.it/150?text=Image+1';" onmouseout="this.src='http://placehold.it/150';" /></a>
        <a href="#"><img id="image2" class="image" src="http://placehold.it/150" onmouseover="this.src='http://placehold.it/150?text=Image+2';" onmouseout="this.src='http://placehold.it/150';" /></a>
        <a href="#"><img id="image3" class="image" src="http://placehold.it/150" onmouseover="this.src='http://placehold.it/150?text=Image+3';" onmouseout="this.src='http://placehold.it/150';" /></a>
    </div>
    <div id="HiddenContentContainer">
    <h3>HIDDEN CONTENT SHOULD APPEAR HERE</h3>
        <div id="Hidden1" class="Hidden">This is My Hidden Content for Image 1</div>
        <div id="Hidden2" class="Hidden">This is My Hidden Content for Image 2</div>
        <div id="Hidden3" class="Hidden">This is My Hidden Content for Image 3</div>
    </div>
</div>

Answer №1

Look no further, this solution might just do the trick. Give it a shot

XHTML

<div id="MainContainer">
<div id="ImgContainer">
    <a href="#"><img id="image1" class="image" data-target="#Hidden1" src="http://placehold.it/150" onmouseover="this.src='http://placehold.it/150?text=Image+1';" onmouseout="this.src='http://placehold.it/150';" /></a>
    <a href="#"><img id="image2" class="image" data-target="#Hidden2" src="http://placehold.it/150" onmouseover="this.src='http://placehold.it/150?text=Image+2';" onmouseout="this.src='http://placehold.it/150';" /></a>
    <a href="#"><img id="image3" class="image" data-target="#Hidden3" src="http://placehold.it/150" onmouseover="this.src='http://placehold.it/150?text=Image+3';" onmouseout="this.src='http://placehold.it/150';" /></a>
</div>
<div id="HiddenContentContainer">
    <h3>REVEALING THE HIDDEN CONTENT HERE</h3>
    <div id="Hidden1" class="Hidden">This is My Secret Message for Image 1</div>
    <div id="Hidden2" class="Hidden">This is My Secret Message for Image 2</div>
    <div id="Hidden3" class="Hidden">This is My Secret Message for Image 3</div>
</div>

JavaScript:

//Basic show-hide functionality
$(".image").click(function(){
$(".Hidden").hide();
    $($(this).attr("data-target")).show();
});

//Toggle feature with similar code
$(".image").click(function(){
$(".Hidden").hide();
    if(!$($(this).attr("data-target")).hasClass("current")){
    $($(this).attr("data-target")).show().addClass("current");
  }
  else{
    $($(this).attr("data-target")).removeClass("current");
  }

});

Answer №2

Here is a code snippet to handle click events on links:

// handle click events on links in the ImgContainer
$( '#ImgContainer a' ).on( 'click', function( e ) {
    e.preventDefault(); // prevent default link behavior

    var clickedLink = $( this ); // store the clicked link element
    var linkIndex = clickedLink.index(); // determine index position of the clicked link

    // Hide all elements in HiddenContentContainer and show the one associated with the clicked link
    $( '#HiddenContentContainer div' ).addClass( 'Hidden' );
    $( '#Hidden' + ( linkIndex + 1 ) ).removeClass( 'Hidden' );
});

The comments provide insights into the functionality of each line.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Why does node.js struggle to find other TypeScript React components?

Currently, I am in the process of converting some react server-side rendering files to typescript. However, I have encountered an issue with locating my custom components. The file path structure is as follows: node_modules/ src/ page/Homepage.tsx ...

VueJS Hotel Reservation Datepicker: Trouble retrieving selected check-in date using event listener

I am new to VueJS and currently working on integrating the vue-hotel-datepicker into my project. I am having trouble figuring out how to utilize the checkInChanged event listener. This is the code snippet from my template: <datepicker :startDate ...

What is the best way to invoke JavaScript from C# code in Ext.NET?

Within my project, I encountered a situation where the displayed time in Chrome is incorrect while it appears correctly in Explorer. To address this issue, I wrote a JavaScript code, but unfortunately, it did not resolve the problem. Below is the JavaScrip ...

Is it possible for the code to display the value from the previous refresh rather than the most recent value added?

In my project, there is a functionality where a column of buttons in a table triggers a script to read the data associated with the clicked button and send it to another PHP file: <!-- Script that retrieves lecturer details for SHOW functionality - ...

Avoid displaying the value of ModelAttribute in the JSP by utilizing form:input in Spring MVC

Upon clicking a button, I want to retrieve data from a table and populate it into a form. Please refer to the image below for illustration: https://i.sstatic.net/KHSKM.png I have successfully retrieved the data from the table row. The issue lies in rende ...

Solve inconsistent divs using HTML and Bootstrap styling techniques

I'm currently working on a .cshtml page where I display database objects in a card format using HTML and Bootstrap. However, the cards are appearing unevenly as shown below: https://i.sstatic.net/LbrrH.png Here is the code snippet I am using: @model ...

Enhancing a variable's value while simultaneously boosting its rate of increase through Javascript

Looking to adjust the timing on a number increase function using setInterval(Function, time). Initially set the variable for time as time = 1000, but now looking to dynamically change it by implementing a function triggered by a button click: function cha ...

The variable 'originalPrompt' has already been declared within the React TypeScript code

For the project I am working on, I do not have a variable named "originalPrompt," yet I keep seeing this error message. This problem seems to only occur for users who are using the "Selenium IDE" chrome extension. Is there a way to prevent this extension f ...

How to efficiently eliminate redundant entries from an object array using JavaScript or React

I've been struggling to implement the solutions provided in this thread on removing duplicates from an array of objects. Unfortunately, I haven't found a satisfactory way to do so. In my current approach (which involves adding new iconsProps to ...

Select more than one class within a div and keep track of how many times they have been clicked using pure JavaScript

This code snippet serves the purpose of tracking the number of clicks on buttons with either the testButton or incButton class, and displaying an overlay after two clicks. However, two main issues have been identified: 1: Difficulty in selecting buttons wi ...

Solving regex issues within PHP

<div class="start">...</div> Is there a way to extract the content within <div class="start"> using PHP? I am looking for a regular expression solution that is capable of handling nested scenarios. ...

What is the best way to organize Node/Express routes based on their type into different files?

My /router/index.js file is becoming too cluttered, and I want to organize my routes by group (user routes, post routes, gear routes) into separate files within /router/routes/. Here's what I currently have set up: app.js var express = require(&apos ...

The data retrieved from the API call is outdated

I am struggling with a weather web API that is only showing old data when called in the code. However, when I enter the API URL directly into the browser, it displays the most up-to-date information for the current city. Can anyone help me troubleshoot why ...

Bing Translator and XMLHttpRequest are two powerful tools for translating and

When running the code snippet below, I encounter an issue where I am not receiving status 200 and responseText. However, when using the following URL: http://api.microsofttranslator.com/V2/Http.svc/GetLanguagesForTranslate?appId=F1B50AB0743B541AA8C070890 ...

jQuery UI's $(...).sortable function is throwing an error when being used with WebPack

After setting up everything correctly, I encountered an unusual issue with Webpack. Let's take a look at this simple app.ts file: 'use strict'; import $ = require('jquery'); import 'jquery-ui'; $(function() { $( " ...

The 'log' property cannot be found on the type '{ new (): Console; prototype: Console; }' - error code TS2339

class welcome { constructor(public msg: string){} } var greeting = new welcome('hello Vishal'); Console.log(greeting.msg); I encountered an error at the Console.log statement. The details of the error can be seen in the image attached below. ...

Issues with receiving data on $.ajax POST request

If you'd like to check out my website Please use the following login details (case sensitive): Username: stack Password: stack Click on the tab labeled "yourhours." The main goal is to send all input box data to a database. At the moment, I am fo ...

nodejs - csvtojson returning incorrectly formatted JSON keys in output

I've been utilizing the csvtojson package in my nodejs project. Despite writing the code below to convert my csv file, I'm facing an issue where the keys in the generated json do not have double brackets. Consequently, I am unable to retrieve val ...

What purpose does the typeof window check serve in the Nextjs Image component?

As I work on creating a placeholder image/svg for the Next.js image component, I found some code on their GitHub repository that helped guide me. Because my experience lies more in frontend development rather than backend, I had to do some research on conc ...

Rotating Image Sub Menu Using HTML, CSS, and jQuery

I'm currently working on a project that involves creating a sub menu with interactive image displays. The goal is to have an image appear when hovering over an li tag. Here is an example of what I'm aiming for: If you'd like to see it in a ...