What is a straightforward method to display one Div while concealing all others?

Is there a simpler method to display one div and hide all others, with the first one shown by default?

My current solution using jQuery works, but it feels lengthy. I believe there might be a more efficient way to achieve this.

Here is the code snippet:


      $(".link-one").click(function() {
        $(".div-one").show();
        $(".div-two,.div-three,.div-four,.div-five").hide(); 
      });
  
      // Other click functions for link-two, link-three, ..., link-five
      
    

      .div-two,
      .div-three,
      .div-four,
      .div-five {
        display: none
      }
  
      a {
        display: inline-block;
        margin-right: 10px;
        padding: 5px 0;
      }
      
    

      <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      <a href="#" class="link-one">Link One</a> <a href="#" class="link-two">Link Two</a> <a href="#" class="link-three">Link Three</a> <a href="#" class="link-four">Link Four</a> <a href="#" class="link-five">Link Five</a>

      <div class="div-one">
        Div #1
      </div>

      // Other divs with different content
      
    

To see a demonstration of this functionality, you can check out this JSfiddle: https://jsfiddle.net/z58ayhtw/6/

Answer №1

Utilize common classes to target both elements. By incorporating a basic data attribute on the links, you can segregate the corresponding content.

$('.tab-link').click(function(){
   var contClass = $(this).data('div');
   $('.content').hide().filter('.' + contClass).show()
})
.content {
  display: none
}
.content:first-of-type {display:block}

a {
  display: inline-block;
  margin-right: 10px;
  padding: 5px 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="#" class="tab-link" data-div="div-one">Link One</a> 
<a href="#" class="tab-link" data-div="div-two">Link Two</a> 
<a href="#" class="tab-link" data-div="div-three">Link Three</a> 
<a href="#" class="tab-link" data-div="div-four">Link Four</a> 
<a href="#" class="tab-link" data-div="div-five">Link Five</a>

<div class="div-one content">
  Div #1
</div>

<div class="div-two  content">
  Div #2
</div>

<div class="div-three content">
  Div #3
</div>

<div class="div-four content">
  Div #4
</div>

<div class="div-five content">
  Div #5
</div>

Answer №2

Yes, there is definitely a way to achieve this.

One method involves capturing the event.target and then comparing it while iterating through all the elements. The comparison can be based on various criteria such as class, id, attribute, or index.

I will demonstrate how to do this using pure JavaScript, but it can easily be adapted to jQuery.

window.onload = function(){
  const links = document.querySelectorAll('.link-item');
  const divs = document.querySelectorAll('.div-item');

  const hide = function(evt){
    divs.forEach(function(d){
       if(evt.target.getAttribute('itemNo') != d.getAttribute('itemNo')) d.classList.add('display-none');
       else d.classList.remove('display-none');
    });
  }

  links.forEach(function(d){ d.onclick = hide; })
}
.display-none{
   display: none;
}
<div class="link-item" itemNo="1">link 1</div>
<div class="link-item" itemNo="2">link 2</div>
<div class="link-item" itemNo="3">link 3</div>
<div class="link-item" itemNo="4">link 4</div>
<div class="link-item" itemNo="5">link 5</div>
<br/><br/>
<div class="div-item" itemNo="1">div 1</div>
<div class="div-item display-none" itemNo="2">div 2</div>
<div class="div-item display-none" itemNo="3">div 3</div>
<div class="div-item display-none" itemNo="4">div 4</div>
<div class="div-item display-none" itemNo="5">div 5</div>

Answer №3

Apply CSS Styling

<style>
    #divs>div{
        visibility: hidden;
    }
    #divs>div.visible{
        visibility: visible;
    }
</style>

Next, assign the div reference to the click function

<div id="divs">
    <div>1</div>
    <div>2</div>
    <div>3</div>
    <div>4</div>
    <div>5</div>
</div>

<a href="javascript:showDiv(1)">Show 1</a>
<a href="javascript:showDiv(2)">Show 2</a>
<a href="javascript:showDiv(3)">Show 3</a>
<a href="javascript:showDiv(4)">Show 4</a>
<a href="javascript:showDiv(5)">Show 5</a>

This JavaScript code uses vanilla JS

<script>

    function showDiv(n) {
        const divs = document.querySelectorAll("#divs>div")
        divs.forEach(d => {
            d.classList.remove("visible")
        })
        divs.item(n-1).classList.add("visible")
    }

</script>

Answer №4

Here is a simple way to achieve this:

  • Start by adding a click event to all a elements with a class starting with link. Utilize Attribute Selectors for this purpose, such as $('a[class^=link]') to target all <a> elements with classes beginning with link.
  • Next, extract the class of the element that starts with link.
  • Hide all divs initially, then display the desired one.

$('a[class^=link]').click(function(e){
  let c = this.className.split(' ').find(x => x.startsWith('link'));      
  $('div[class^=div]').hide();   
  $(`.div-${c.split('-')[1]}`).show();
})
.div-two,.div-three,.div-four,.div-five {
  display:none
}

a {
  display:inline-block;
  margin-right:10px;
  padding:5px 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="#" class="link-one">Link One</a> <a href="#" class="link-two">Link Two</a> <a href="#" class="link-three">Link Three</a> <a href="#" class="link-four">Link Four</a> <a href="#" class="link-five">Link Five</a>

<div class="div-one">
Div #1
</div>

<div class="div-two">
Div #2
</div>

<div class="div-three">
Div #3
</div>

<div class="div-four">
Div #4
</div>

<div class="div-five">
Div #5
</div>

Note: It is recommended to keep the class names consistent and use IDs like div-one,div-two...

Answer №5

If you want to utilize the .index() of the anchor element you clicked on, along with .eq() and .not(), you can follow this approach:

$('a[class^=link-]').click(function(){
  var position = $(this).index() - 1;
  $('[class^=div-]').eq(position).show();
  $('[class^=div-]').not(':eq('+position+')').hide();
});
.div-two,.div-three,.div-four,.div-five {
  display:none
}

a {
  display:inline-block;
  margin-right:10px;
  padding:5px 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<a href="#" class="link-one">Link One</a> <a href="#" class="link-two">Link Two</a> <a href="#" class="link-three">Link Three</a> <a href="#" class="link-four">Link Four</a> <a href="#" class="link-five">Link Five</a>

<div class="div-one">Div #1</div>
<div class="div-two">Div #2</div>
<div class="div-three">Div #3</div>
<div class="div-four">Div #4</div>
<div class="div-five">Div #5</div>

Answer №6

Utilize links to items on the page for a strategic advantage by assigning target Ids and setting the href of the links accordingly. This approach is more semantic and can potentially offer SEO benefits.

Another modification I implemented is enclosing the content divs within a container and styling them based on that.

$('.tab-link').click(function() {
  //Get our target from the link
  var contTarget = $(this).attr('href');
  //Hide all content
  $('.content > div').hide();
  //Show the target
  $(contTarget).show();
})
.content>div {
  display: none
}

.content>div:first-child {
  display: block
}

a {
  display: inline-block;
  margin-right: 10px;
  padding: 5px 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="#div-one" class="tab-link">Link One</a>
<a href="#div-two" class="tab-link">Link Two</a>
<a href="#div-three" class="tab-link">Link Three</a>
<a href="#div-four" class="tab-link">Link Four</a>
<a href="#div-five" class="tab-link">Link Five</a>

<div class="content">
  <div id="div-one">
    Div #1
  </div>

  <div id="div-two">
    Div #2
  </div>

  <div id="div-three">
    Div #3
  </div>

  <div id="div-four">
    Div #4
  </div>

  <div id="div-five">
    Div #5
  </div>
</div>

Pure CSS can also achieve this effect, however, it may not be as versatile as a JavaScript solution. It works best when the content area has a known size.

A basic outline on how to implement this using pure CSS is provided below.

.content { position: relative;}

.content>div {
  display: none;
  position:absolute;
  background-color:#FFF;
  z-index:10;
}

.content>div:first-child {
  display: block;
  z-index:1;
}

.content > div:target {
  display:block;
}

a {
  display: inline-block;
  margin-right: 10px;
  padding: 5px 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="#div-one" class="tab-link">Link One</a>
<a href="#div-two" class="tab-link">Link Two</a>
<a href="#div-three" class="tab-link">Link Three</a>
<a href="#div-four" class="tab-link">Link Four</a>
<a href="#div-five" class="tab-link">Link Five</a>

<div class="content">
  <div id="div-one">
    Div #1
  </div>

  <div id="div-two">
    Div #2
  </div>

  <div id="div-three">
    Div #3
  </div>

  <div id="div-four">
    Div #4
  </div>

  <div id="div-five">
    Div #5
  </div>
</div>

Answer №7

Javascript version

Apply the following styles

<style>
    #sections>section{
        display: none;
    }
</style>

Create your HTML structure

<div id="sections">
    <section>Section 1</section>
    <section>Section 2</section>
    <section>Section 3</section>
    <section>Section 4</section>
    <section>Section 5</section>
</div>
<div id="buttons">
    <button>Show Section 1</button>
    <button>Show Section 2</button>
    <button>Show Section 3</button>
    <button>Show Section 4</button>
    <button>Show Section 5</button>
</div>

Finally, add the JavaScript code

<script>
    const $buttons = $("#buttons>button");
    const $sections = $("#sections>section");

    $buttons.on("click", function(){
        const index = $buttons.index(this);
        $sections.hide();
        $($sections[index]).show();
    })
</script>

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

Is the size of the array significant in the context of JavaScript here?

Whenever a button is clicked on the page, I am dynamically creating an array in javascript using item id's fetched from the database. Each entry in the array will hold a custom object. The id's retrieved from the database can range from numbers ...

To enhance the menu's appearance, apply a bottom box shadow when scrolling both up and down

My menu has the following CSS properties: #header { width: 100%; position: fixed; z-index: 9000; overflow: auto; } With these CSS properties, the element #header will always stay on top, regardless of scrolling. My goal is to add a bottom box sha ...

Exploration of jQuery Dropdown Menus

Encountering a problem with my dropdown menu. Check out the code here: http://jsfiddle.net/xY2p6/1/ It seems like a simple issue that I can't figure out, but as shown in the link, the functionality is not working properly. I need help linking the hid ...

Issue with resetting the state of a react-select component remains unresolved

I'm currently facing two issues with my react-select component: Firstly, once I select an option, I am unable to change it afterwards. Second, when my form is reset, the react-select component does not reset along with the other fields. For simplici ...

What is the best way to transfer data from a div tag to an li tag using JavaScript?

https://i.stack.imgur.com/se2qk.pngI am attempting to change the div tag content to li tag. Here is a snippet of the code from inspect for reference. I need to remove the div tag with the "domTitle" class. <li style="display: inline;" id="list_name"> ...

Obtaining information from a intricate string input

{JSON.stringify(walletData.transactions, null, 2)} My goal is to extract backend data and display it as a table. The response has been converted into an array as shown below. [ { "date": "Nov 07, 2023", "description" ...

Top technique for extracting json files from post requests using nodejs

Situation: I'm running a Node.js REST server that receives JSON files, parses them, and inserts them into a database. With an anticipated influx of hundreds of requests per second. Need: The requirement is to only perform insertions by parsing the JS ...

Steps to retrieve an incorrect fruit when it is located as the initial item within the array

Currently tackling the precourse material for a coding bootcamp and hitting a roadblock with this particular question. Despite my best efforts, I just can't seem to meet one of the 7 conditions required. Let me outline the question, my attempted solut ...

AngularJS - Not binding $scope to the DOM

Recently starting out with Angular, I decided to practice by creating a simple website. One of the features I want to include is displaying the number of times a button has been clicked through data binding. Here's the controller code I've writte ...

Issues with TypeScript arise when transferring arguments between functions

Encountering a TypeScript error due to this pattern: Error message: 'Argument of type '(string | number)[]' is not assignable to parameter of type 'string[] | number[]' function foo(value: string | number) { return bar([va ...

How to identify the position of an element while scrolling using JavaScript/jQuery

Trying to determine the distance between an element and the top of the window document. After initial value is retrieved during scroll event, it remains unchanged. How can this value be continuously tracked as the page scrolls? JS: $(function() { $(wi ...

TS1057: It is required that an async function or method has a return type that can be awaited

There was a recent Github issue reported on March 28th regarding async arrow functions generating faulty code when targeting ES5, resulting in the error message: TS1057: An async function or method must have a valid awaitable return type You can find t ...

Transforming a single object into several arrays

I have a JSON file called "icon.json" that contains the following data: [ { "name": "happy", "url": "1.gif" }, { "name": "excited", "url": "2.gif" }, { "name": "surprised", "url": "3.gif" ...

HTML: adjust the landing position of the page your users reach

I am trying to customize my WordPress website so that when a user lands on the page, they are positioned in the center of the page rather than at the top. If this is unclear, feel free to ask for clarification. My WordPress site includes PHP code and an e ...

How can I retrieve data from the Hasura hook "useQuery"?

As a newcomer to web development, I am attempting a simple 'GET' request using the "useQuery" hook from Hasura. However, I am encountering difficulties accessing my data. Strangely, the query has been successfully tested on the Hasura console wit ...

The pie chart generated by Google may be small in size, but it certainly packs

Below, you will find my page layout created using Bootstrap 4 and Google Charts. The layout consists of three black boxes, with the one on the right displaying a Google pie chart. However, I'm facing an issue where the area allocated for the chart is ...

The function you are trying to call in Javascript is currently unavailable

I encountered an issue with a JavaScript script. I have an object that contains some functions and variables. Within one of these functions, I make an Ajax request. However, in the error handler, when trying to call a function defined within the same objec ...

Utilize the function of express

The following code is not behaving as expected: var express = require('express'); var app = express(); app.use(function(req, res, next) { console.log('first statement'); next(); }, function (req, res, next) { console.log('se ...

Searching for an item in an array within MongoDB: Tips and techniques

I am attempting to locate the object containing a specific element within an array: Here is my query: router.get('/', function(req, res) { var userSubscribed = req.user.email; db.posts.find({ "SubscriberList": { $elemMatch: userSubscrib ...

Use jQuery to remove an element if the image source of the nth-child is empty

Can someone help me with removing back and next arrows from a slideshow if the slideshow only has one image? The slideshow always adds <img src />, regardless of whether there are images there or not. It just leaves the src as empty if there is only ...