Populating a Div with Information

I'm currently working on a project where I have a div with predefined dimensions, but the content inside is set to not display initially.

Above this div, there are several p tags that act as clickable links to reveal different content within the div when clicked. However, I'm having trouble getting this functionality to work properly.

HTML

<p id="link1">Content 1</p>
<p id="link2">Content 2</p>
<p id="link3">Content 3</p>

<div class="subcontent">
<div class="hide cont1">
<p>Title</p>
<p>Content 1</p>
</div>
<div class="hide cont2">
<p>Title</p>
<p>Content 2</p>
</div>
<div class="hide cont3">
<p>Title</p>
<p>Content 3</p>
</div>
</div>

CSS

.subcontent{
    box-sizing: border-box;
    border: solid 1px #DDD;
    height:300px;
    width: 70%;
    padding: 0px 15px;
    margin-left: 22%;
    margin-bottom: 10px;
    font-size: 90%;
}
.hide {
    display: none;

Can anyone provide suggestions on how to make Content 1 visible when #link1 is clicked?

Additionally, how can I ensure that any previously displayed content is hidden before revealing new content?

I apologize if my explanation is unclear - I am still learning and appreciate any guidance provided.

Answer №1

Here are a couple of important steps:

1) Ensure that you have the click event handler set up for p elements.

2) Next, make sure to retrieve the number from the id of the clicked element.

3) Use this extracted number to generate a selector for targeting the specific div you want.

 $("p[id^=link]").click(function(){
  var currentDivId = this.id.replace( /[^\d.]/g, '' );
  $('.hide').not(".cont"+currentDivId).hide();
  $(".cont"+currentDivId ).toggle();
 });

See Working Demo Here

Answer №2

If you're working with JavaScript and/or JQuery, leveraging EventHandlers for onclick events can be quite powerful. By assigning event handlers to the onclick events of specific HTML elements identified by their ID's, you can create interactive functionalities. The function triggered by these event handlers can dynamically alter the display of associated divs.

It would be beneficial to explore more about event handlers beyond just onclick. There are various triggers such as mouseover that can enhance the interactivity of your web pages.

Answer №3

Just for kicks, I decided to tackle the entire thing using vanilla Javascript. I made some tweaks to the html handlers. :)

<style>
#subcontent{
    box-sizing: border-box;
    border: solid 1px #DDD;
    height:300px;
    width: 70%;
    padding: 0px 15px;
    margin-left: 22%;
    margin-bottom: 10px;
    font-size: 90%;
}
.hide{
    display: none;
}
</style>
</head>
<body>

<a href="#" id="link1">Section 1</a>
<a href="#" id="link2">Section 2</a>
<a href="#" id="link3">Section 3</a>

<div id="subcontent">
    <div id="cont1" class="hide">
        <p>Header</p>
        <p>Content 1</p>
    </div>
    <div id="cont2" class="hide">
        <p>Header</p>
        <p>Content 2</p>
    </div>
    <div id="cont3" class="hide">
        <p>Header</p>
        <p>Content 3</p>
    </div>
</div>
<script>

//retrieve document elements
var link1 = document.getElementById('link1');
var link2 = document.getElementById('link2');
var link3 = document.getElementById('link3');

link1.addEventListener('click', function(){
    showContent('cont1');
});

link2.addEventListener('click', function(){
    showContent('cont2');
});   

link3.addEventListener('click', function(){
    showContent('cont3');
});     

function showContent(idName) {
    var children = document.getElementById('subcontent').childNodes;

    for(var i = 0; i < children.length; i++) {
        if(children[i].nodeName == "DIV") {
            children[i].style.display = "none";
        };
    };
    document.getElementById(idName).style.display = "block";
};
</script>

Answer №4

If you're looking for a solution using JQuery, the following code might be helpful. While there may be more elegant options available, this code should get the job done. Check out the JSFiddle demo for a live example.

$("#link1").click(function(){
    $(".cont1").removeClass("hide");
    $(".cont2").addClass("hide");
    $(".cont3").addClass("hide");
});
$("#link2").click(function(){
    $(".cont2").removeClass("hide");
    $(".cont1").addClass("hide");
    $(".cont3").addClass("hide");
});
$("#link3").click(function(){
    $(".cont3").removeClass("hide");
    $(".cont2").addClass("hide");
    $(".cont1").addClass("hide");
});

Answer №5

I made a small modification to your HTML code to implement event delegation. This adjustment will enhance the maintainability of your code, especially if you plan to add more DIVs and links in the future.

<div id="links">
  <p id="link1">Content 1</p>
  <p id="link2">Content 2</p>
  <p id="link3">Content 3</p>
</div>

Below is the script:

document.getElementById('links').addEventListener('click', function(e) {
    var index = e.target.id.slice(4);
    var showing = document.querySelector('.subcontent > div:not(.hide)');
    if(showing) {
        showing.classList.add('hide');
    }
    document.querySelector('.subcontent > div.cont' + index).classList.remove('hide');
}, false);

Explanation:

  1. Extract the index of the clicked link by retrieving the number from its ID
  2. Determine the currently visible div that does not have the class 'hide'
  3. If there is a visible div, hide it by adding the class 'hide'
  4. Identify the div you intend to display and remove the class 'hide' from it

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

Display or conceal a div depending on the value of an integer stored in the $scope variable

Consider the ng repeat pattern below: <div class="presentForm" id="presentForm{{$index}}" ng:repeat="slide in slides" style="display: block;"> <img id ="presentationSlide" ng-src='{{slide}}' style="height: 300px" width ...

When working with ReactJs, you may encounter a delay in adding a class to the li element upon click event

I am facing an issue where the first li element works perfectly when clicked, but for the rest of the elements, I have to click twice to apply the desired styling. Can anyone explain why this behavior is occurring? App.js import React, { Component } from ...

The two-dimensional array in JavaScript has not been defined

I've been trying to troubleshoot the error in my code with no success. I have a simple example of what I believe to be a two-dimensional array, but I keep getting an undefined error. var city = 'London', country = 'England'; ...

Issues with d3.js transition removal functionality not functioning as expected

Having an issue with a d3.js visualization that involves multiple small visualizations and a timeline. When the timeline changes, data points are supposed to be added or removed accordingly. Here is the code snippet responsible for updating: var channels ...

Regular expressions - Identifies a text string that doesn't contain <html> tags, including all possible scenarios

Can you identify the issue with this string: This is a bad string.It has <HTML> tags? It contains HTML tags that should not be matched. Can you help me find a good string without any HTML tags (including attributes)? There are many resources availab ...

Is there a way to horizontally align the content in my footer section?

I am currently exploring React Material UI for the first time. The table I am working with can be found here under the "Custom pagination actions" section. Within this section, there is footer content containing buttons for rows per page, next, previous, ...

Retrieve information and auto-fill text boxes based on the selected dropdown menu option

UPDATED QUESTION STATUS I'm currently working with Laravel 5.7 and VueJs 2.5.*. However, I am facing a challenge where I need to automatically populate form textboxes with data from the database when a dropdown option is selected. Despite my efforts ...

javascript has been overrunning with an abundance of attached comments loops

I've been encountering an issue where I am unable to properly link my comments to the message id. Below is what I have attempted: Routes file: router.get('/home', function(req, res){ if(req.cookies.user_id){ knex.raw(`SELECT * ...

Mastering the art of throwing and managing custom errors from the server to the client side within Next.js

I'm in the process of developing a Next.js application and I am faced with the challenge of transmitting customized error messages from the server to the client side while utilizing Next JS new server-side actions. Although my server-side code is func ...

Guide on automatically submitting the form within 2 seconds after the user has inputted the data without requiring them to click the submit button

I need to store form data in the database, but only 2 seconds after the user enters the information. To achieve this, I am utilizing an ajax function, however, the form is currently submitting each time a single key is pressed. $('#eid').bind(& ...

Auto submit the form on page reload in PHP

I'm currently experiencing an issue with a form on my website. Whenever the page is refreshed, the form automatically submits. I only want the form to be submitted when a user clicks on the button. If the button is not clicked, the form should not pos ...

Is there a way to configure nodemon to automatically monitor changes in dotenv-flow files?

Files in dotenv-flow can be named with prefixes like: .env, .env.development, .env.development.local, ... If you want your node server to automatically restart when any of these files are updated, you may encounter limitations. Currently, the custom confi ...

Steps for positioning a div beside a centered div

Is there a way to position a div next to another div that is centered on the page, like this: .firstDiv { margin-left: auto; margin-right: auto; padding: 0; } The above code centers the first div in the middle of the page. But how can I add a ...

How to style a date and time object using angularjs

What is the best way to convert a PHP datetime object to the format "May-27-1990"? ...

I am facing an issue with my Bootstrap 4 Navbar as it is not collapsing in the Mobile View

The issue I am facing is that the navbar options cannot be opened properly. When clicked, it appears as a solid button and forms a sort of ring around it. I have attempted various solutions such as adding and removing scripts, changing the navbar attribute ...

I am facing difficulty in accessing information from my API through Angular

I recently developed an API using NodeJS. While attempting to fetch data from the API using AngularJS, I encountered an issue where no data is being displayed. Take a look at my API, which contains data in JSON format. You can access the live link to ...

I'm just starting to delve into React and I am eager to transform my regular JavaScript code into a React format. However, I am not quite sure how to

In my React JavaScript, I am trying to insert some regular JavaScript code. I attempted to use the {} brackets, but it did not work as expected. import './App.css'; function App() { return ( <> <div className=" ...

Using JavaScript/jQuery to analyze POST values just before submission

Currently facing a dilemma as my company is in the process of redesigning its website. I find myself stuck trying to come up with a temporary fix for an issue on the existing site. The solution requires the use of JavaScript or jQuery. The problem arises ...

Using npm to install packages with multiple package.json files

My current project includes a submodule with another submodule, each having their own package.json file. This is how I set up my project: |root ----|node_modules ----|package.json ----|someFolder ----|submodule_1 -------- |package.json -------- |someFold ...

IntelliSense in VSCode is unable to recognize the `exports` property within the package.json file

Currently, I am utilizing a library named sinuous, which contains a submodule known as "sinuous/map". Interestingly, VSCode seems to lack knowledge about the type of 'map' when using import { map } from "sinuous/map", but it recognizes the type ...