Display or conceal various content within div elements using multiple buttons

I have a set of 5 image buttons, each meant to trigger different content within a div. When the page loads, there should be default content displayed in the div that gets replaced by the content of the button clicked. The previously displayed content should be replaced when another button is clicked.

This is my current setup:

HTML:

 $('.section-link').click(function() {
        var cur = $('.section-link').index($(this));
        $('.section-display').removeClass('active');
        $('.section-display').eq(cur).addClass('active');
      });
.section-display:not(.active) {
      display: none;
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<a href="#"><img class="button1 section-link" src="button1.jpg" alt=""></a>
    <a href="#"><img class="button2 section-link" src="button2.jpg" alt=""></a>
    <a href="#"><img class="button3 section-link" src="button3.jpg" alt=""></a>
    <a href="#"><img class="button4 section-link" src="button4.jpg" alt=""></a>
    <a href="#"><img class="button5 section-link" src="button5.jpg" alt=""></a>

    // Default CONTENT when page loaded
    <div class="section-display active">
      <h2 class="title">Default Ipsum</h2>
      <h2 class="text">"Lorem ipsum dolor sit amet, consectetur adipiscing elit."</h2>
    </div>
    <div class="section-display">
      <h2 class="title">First Ipsum</h2>
      <h2 class="text">"Lorem ipsum dolor sit amet, consectetur adipiscing elit."</h2>
    </div>
    <div class="section-display">
      <h2 class="title">Second Ipsum</h2>
      <h2 class="text">"Lorem ipsum dolor sit amet, consectetur adipiscing elit."</h2>
    </div>
    <div class="section-display">
      <h2 class="title">Third Ipsum</h2>
      <h2 class="text">"Lorem ipsum dolor sit amet, consectetur adipiscing elit."</h2>
    </div>
    <div class="section-display">
      <h2 class="title">Fourth Ipsum</h2>
      <h2 class="text">"Lorem ipsum dolor sit amet, consectetur adipiscing elit."</h2>
    </div>
    <div class="section-display">
      <h2 class="title">Fifth Ipsum</h2>
      <h2 class="text">"Lorem ipsum dolor sit amet, consectetur adipiscing elit."</h2>
    </div>

Answer №1

UPDATE: Upon closer inspection, I realized that the question had a JQuery tag. Therefore, I have revised my answer to incorporate that.

Avoid using hyperlinks when they do not lead anywhere. This practice is semantically incorrect and needlessly affects the browser history. Instead, consider placing your images inside a button element or adding click event handlers directly to the images, as demonstrated below.

If you store your content in an array of objects, you can streamline your code by eliminating the need for multiple div structures and updating just one:

// Store all images in a JavaScript array
var $imgs = $(".section-link");

// By storing content in an array of objects, you can avoid creating 
// multiple display divs. Simply fetch the content from the object within
// the array that corresponds to the clicked image's index
var data = [
  {
    title: "Default Ipsum 1",
    text: "1 Lorem ipsum dolor sit amet, consectetur adipiscing elit."
  },
  {
    title: "Default Ipsum 2",
    text: "2 Lorem ipsum dolor sit amet, consectetur adipiscing elit."
  },
  {
    title: "Default Ipsum 3",
    text: "3 Lorem ipsum dolor sit amet, consectetur adipiscing elit."
  },
  {
    title: "Default Ipsum 4",
    text: "4 Lorem ipsum dolor sit amet, consectetur adipiscing elit."
  },
  {
    title: "Default Ipsum 5",
    text: "5 Lorem ipsum dolor sit amet, consectetur adipiscing elit."
  },  
];

// Select the output area
var $outputDiv = $(".section-display");

// Attach a click event handler to each image
$imgs.on("click", function(){
  // Update the child elements within the output div by retrieving
  // content from the array of objects based on the index of the clicked image.
  $(".title", $outputDiv).text(data[$(this).index()-1].title);
  $(".text", $outputDiv).text(data[$(this).index()-1].text);    
});
/* This CSS snippet makes the images visible since they lack valid src paths */
img {
  display:inline-block;
  width:50px;
  height:50px;
  border:1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<!-- See how much cleaner the HTML looks now? -->
<img class="section-link" src="button1.jpg" alt="">
<img class="section-link" src="button2.jpg" alt="">
<img class="section-link" src="button3.jpg" alt="">
<img class="section-link" src="button4.jpg" alt="">
<img class="section-link" src="button5.jpg" alt="">

<div class="section-display active">
  <h2 class="title">Default Title</h2>
  <h2 class="text">Default Content</h2>
</div>

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

Identifying Elements Generated on-the-fly in JavaScript

Currently, I am tackling the challenge of creating a box that can expand and collapse using regular JavaScript (without relying on jQuery). My main roadblock lies in figuring out how to effectively detect dynamically added elements or classes to elements a ...

Is there a way to stylize the initial words of a brief text block by blending small caps with italics, all while avoiding the use of a span tag?

I have a series of images with numbered captions like "Fig. 1", "Fig. 2", "Fig. 3", followed by a brief description on the same line. Is there a way to programmatically style these strings (the “Fig. #” only) using CSS or Javascript to make them italic ...

Utilizing Node Js and Selenium webdriver, what is the process of dragging and dropping an element from its current position to a new position just below it?

After multiple attempts, I have come to realize that the following code is ineffective. driver.findElement(By.xpath(xpath)).then(function (element1) { driver.findElement(By.xpath(xpath)).then(function (element2) { ...

Using Conditional Rendering and ReactCSSTransitionGroup for Dynamic Animations

I have developed a small application that displays different components based on a Redux state. I am trying to add a "fade" animation when one of the components renders, but unfortunately, it is not working as expected. Here is my current setup: content.j ...

Selenium web driver showcases its capability by successfully launching the Firefox browser, yet encounters an issue with an invalid address

WebElement searchElement = driver.findElement(By.name("q")); searchElement.sendKeys("Selenium WebDriver"); searchElement.submit(); Displays "Search Results" public static void main(String[] args) { // TODO Auto-generated method st ...

Utilize CSS to style active buttons with JavaScript

In an HTML document, the dynamic generation of divs and buttons using JavaScript can be seen in the code snippet below. <div style="background: rgb(247, 247, 247);"> <button class ="xyz" disabled="disabled">Button1</button> </div> ...

What is the best way to implement a keypress event in this code?

As a JavaScript and jQuery newbie, I have a question regarding adding a simple key press action to this code. How can I implement functionality where pressing the Right Arrow key takes me to the next image, and pressing the Left Arrow key takes me to the p ...

Performing a search using Jquery Ajax when the return key is pressed on Internet Explorer

I have come across this code snippet for implementing a search feature on my website. It works perfectly fine, except for one issue - the search functionality doesn't work in Internet Explorer when users press the return key. Does anyone have any sug ...

I'm having trouble getting the second controller to function properly in my AngularJS application

I've been looking everywhere for a solution on how to implement two controllers, but I can't seem to get it working. Could there be something wrong with my HTML or could the issue lie in my script? Here is the JavaScript code: <script> v ...

Surprising results from implementing the useLocation() hook in a React application

Currently, I am embarking on a personal endeavor to create an online auction platform. One of the key functionalities I am working on is rendering detailed product information when a user clicks on a specific product for purchase. Initially, everything wor ...

Discovering the name, id, and class attributes of a RadioButtonList within a content placeholder using JavaScript

Working on a web forms project with a Master Page implementation, I have added the following code in my content place holder. <asp:RadioButtonList ID="ckbLstPartner" runat="server" name="ckbLstPartner" RepeatDirecti ...

Encountering NodeJs Error 401(Unauthorized) while implementing passport-jwt in my project

I am currently developing an authentication application using Node.js, MongoDB, and the Passport-JWT middleware. I have successfully implemented the login functionality and I am able to obtain a token. However, when trying to access the user profile after ...

"Upon refresh, the overflow property of the child element is being applied to the window position

In the React app I'm working on, there's a search results page where users can apply filters. These filter selections update the query params in the URL and trigger a re-mount in React. However, I've encountered an issue across different bro ...

If the user confirms it with a bootstrap dialog box, they will be redirected to the corresponding links

Firstly, I am not interested in using javascript confirm for this purpose. Please read on. For example, adding an onClick attribute to each link with a function that triggers a system dialog box is not what I want. Instead of the standard system dialog bo ...

Guide to retrieving table data using jQuery in a Vue.js function

I have a simple table set up in my Laravel blade file. When the edit button is clicked, it triggers a Vue method. <types-page inline-template> <div> <!-- table --> <table id="choose-address-tab ...

Ajax cannot seem to come to a resolution

After completing my learning on Ajax, I decided to work on a simple project - a port scanner. However, I am facing issues with it as it is not working properly. The only message that pops up is 'Scan started' and I can't figure out what the ...

Executing a function enclosed in parenthesis does not yield any output

My code is supposed to print the sender's name followed by "adopted" and then the first mentioned user. const { Client } = require('discord.js', 'async', 'discord-message-handler'); const bot = new Client(); const cfg = ...

A beginner's guide to crafting a knex query with MySQL language

Within MySQL Workbench, I currently have the following code: USE my_db; SELECT transactions.created_at, price FROM transactions JOIN transactions_items ON transactions.id = transactions_items.transaction_id JOIN store_items ...

Having trouble finding the correct output when searching in the table using regex

I am currently experiencing an issue with my code for searching. When I search the full text, it works fine but when I search for a middle character, it does not work as expected. For instance, searching for "apple" or "ap" works correctly, however, if I ...

Tips for sending information from a controller to jQuery (Ajax) in CodeIgniter

Code snippet in controller: $rates['poor'] = 10; $rates['fair'] = 20; $this->load->view('search_result2', $rates); //Although I have attempted different ways, the only successful method is using the code above. Other ...