Conceal and reveal div elements using hyperlinks

Hey everyone, I've been working on some code that allows me to show and hide divs by clicking on links. The issue I'm facing is that when I try to view a specific div (like the third one), it appears below the invisible divs instead of at the top of the page. Does anyone have any suggestions on how to ensure that the selected div always appears at the top?

<body>
       <div class="col-md-2">
        <ul class="nav nav-pills nav-stacked" id="menu">
            <li><a href="javascript:show('link1')" id="link1">Wheels</a></li>
            <li><a href="javascript:show('link2')" id="link2">Tires</a></li>
            <li><a href="javascript:show('link3')" id="link3">Bumpers</a></li>
            <li><a href="javascript:show('link4')" id="link4">Headlights</a></li>
        </ul>
    </div>

    <div class="col-md-3">
        <div class="div" id="content1">
            <p>BBS</p>
            <p>ENKEI</p>
            <p>KONIG</p>
        </div>

        <div class="div" id="content2">
                <p>Michelin</p>
                <p>Hankook</p>
                <p>Sava</p>
        </div>

        <div class="div" id="content3">
            <p>AMG</p>
            <p>Brabus</p>
            <p>Original</p>
        </div>

        <div class="div" id="content4">
            <p>Angel Eyes</p>
            <p>Devil Eyes</p>
            <p>Original</p>
        </div>
    </div>

`<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>

function show(id) {

    if (id == 'link1') {
        document.getElementById("content1").style.visibility = 'visible';
        document.getElementById("content2").style.visibility = 'hidden';
        document.getElementById("content3").style.visibility = 'hidden';
        document.getElementById("content4").style.visibility = 'hidden';
    }
    else if (id == 'link2') {
        document.getElementById("content1").style.visibility = 'hidden';
        document.getElementById("content2").style.visibility = 'visible';
        document.getElementById("content3").style.visibility = 'hidden';
        document.getElementById("content4").style.visibility = 'hidden';
    }
    else if (id == 'link3') {
        document.getElementById("content1").style.visibility = 'hidden';
        document.getElementById("content2").style.visibility = 'hidden';
        document.getElementById("content3").style.visibility = 'visible';
        document.getElementById("content4").style.visibility = 'hidden';
    }
    else if (id == 'link4') {
        document.getElementById("content1").style.visibility = 'hidden';
        document.getElementById("content2").style.visibility = 'hidden';
        document.getElementById("content3").style.visibility = 'hidden';
        document.getElementById("content4").style.visibility = 'visible';
    }
}

function init() {

    var divs = document.getElementsByTagName("div");
    for (i = 0; i < divs.length; i++) {
        if (divs[i].className == "div") {
            divs[i].style.visibility = 'hidden';
        }
    }
    var a = document.getElementsByTagName("a");
    a.onclick = show;
}

window.onload = init;

`

Check out my code on jsfiddle!

Answer №1

visibility: hidden conceals the element while maintaining its occupied space. To completely hide the element, utilize display: none:

document.getElementById("sectionA").style.display = 'block';
document.getElementById("sectionB").style.display = 'none';
document.getElementById("sectionC").style.display = 'none';
document.getElementById("sectionD").style.display = 'none';

You can also streamline your code for efficiency. Consider this approach:

function displaySection(id) {
    var num = id.replace('btn', '');
    var sections = document.querySelectorAll("[id^=section");
    for (var j = 0; j < sections.length; j++) {
        sections[j].style.display = 'none';
    }
    document.querySelector('#section' + num).style.display = 'block';
}

Check out the demonstration: https://jsfiddle.net/4qq6xnfr/7/

Answer №2

Ways to utilize:

element.style.display = 'none'; // Conceal
element.style.display = 'block'; // Reveal

Answer №3

To make this process more efficient, follow these steps:

  1. Replace all instances of javascript:show('link1'), javascript:show('link2'), with just #content1, #content2, and so on.
  2. You can now eliminate all of the javascript code.
  3. Generate a new CSS stylesheet (or utilize the <style> tags), and add the following code -

    .div {
      display:none;
    }
    
    .div:target {
      display:block;
    }
    

This should simplify the process greatly for you.

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

Combining 2 dates into a single cell format

I'm struggling to change the date format of two dates displayed in one cell using ag-grid. I have tried creating a new function called dateFormatterr with two parameters, but it doesn't seem to work. Below is a snippet of my code and a screenshot ...

Capturing dynamic text from a URL using Protractor and Node.js

How can I extract the 'PR001-CC001234' segment from a URL using Protractor in Node.js? While I am able to retrieve the current URL and save it as a variable, I am seeking assistance in extracting the dynamic text at the end of the URL. http://exa ...

Defining the TypeScript interface for the onClick event in ReactJS

If you're looking to dive into React development, the tutorial on reactjs.org is a great place to start. While the tutorial code is in JavaScript, I've been working on converting it to TypeScript. I've successfully translated most of the c ...

Angular 10 Reactive Form - Controlling character limit in user input field

I'm currently developing an Angular 10 reactive form and I am looking for a way to restrict the maximum number of characters that a user can input into a specific field. Using the maxLength Validator doesn't prevent users from entering more chara ...

"Enhance your website with a dynamic Jssor slider featuring nested slides and vertical

Exploring the idea of merging the nested slider feature with a vertical thumbnail display. Reviewing the source code for examples image-gallery-with-vertical-thumbnail.source.html and nested-slider.source.html, I am wondering how to effectively combine t ...

Double MySQL Inserts happening with a single submission

My PHP file manages user signups using MySQL, but there's a recurring issue where users' input gets duplicated. https://i.sstatic.net/A8n6X.png The form below shows part of the code that handles the signup process... if ($_SERVER["REQUEST_MET ...

Tips for utilizing the npm jQuery module effectively

What is the best way to import jquery into multiple modules in node? Should I make it a global variable, or should I use require('jquery') in each module that needs it? I encountered an error while attempting to utilize the package. TypeError: ...

What steps can I take to improve my routing structure in nodejs and express?

My current WebAPI code is pretty modular, but I want to make it even more so. Right now, all the routes are in my server.js file and I would like to separate them into individual controllers. Any suggestions on how to achieve that? Here's an example: ...

Remove any overlapping datetime values from a JavaScript array of objects

Is there a way to efficiently remove any overlaps between the start and end times (moment.js) in a given array of objects? [{ start: moment("2019-03-23T15:55:00.000"), end: moment("2019-03-23T16:55:00.000")}, { start: moment("2019-03-23T14:40:00.000"), e ...

Using jQuery to add an element at the current caret position

Within my contentEditable div, there is a table nested. Here is an example of the HTML structure: <div id="divId" contenteditable="true"> <table> <tbody> <tr> <td><br></td> ...

Failed to establish Modbus TCP connection

Currently, I am utilizing the "Panasonic FP7" master PLC along with their official software "FPWIN GR7" to monitor data flow on my PC. However, since the software lacks certain functions, I have decided to develop a solution using nodeJS. Below is the code ...

What is the best way to create a JavaScript "input" field that only accepts vowel letters?

Is there a way to create an "input" field that only accepts vowel letters? Additionally, I want to ensure that copying and dragging text into the input field will also be filtered out. <div class="field"> <input class="fie ...

What could be causing my CSS code to not function properly within Vue.js?

Having trouble with css in VueJs. I can't seem to figure out what I'm doing wrong. Generally, my scoped style css works fine in vuejs, I can target ids and classes without any issues. The problem arises when trying to change the internal css va ...

Verify the existence of the email address, and if it is valid, redirect the user to the dashboard page

Here is the code snippet from my dashboard's page.jsx 'use client' import { useSession } from 'next-auth/react' import { redirect } from 'next/navigation' import { getUserByEmail } from '@/utils/user' export d ...

What is the best method for displaying file size in a user-friendly format using Angular 6?

Imagine having this snippet in an HTML file: *ngFor="let cell of dateFormat(row)">{{cell | filesize}}</td>, where the dateFormat function looks like this: dateFormat(row:string){ var today = new Date(row[4]); let latest_date = this.date ...

Is Socket.io combined with Redis the best architecture for an interactive gaming experience?

My current setup involves a NodeJS scaling architecture with Redis, specifically designed for a real-time multiplayer game. However, I'm facing challenges in configuring separate lobbies for players, as the load balancer assigns users to different ser ...

Similar to jQuery's ajaxStart event handler, AngularJS provides an equivalent event handler for handling Ajax requests

Seeking a way to detect Ajax start and end events in an AngularJS application. In JQuery, one can utilize the ajaxStart, ajaxComplete functions to capture start, complete, end, and fail events on a global or local level. How can I globally monitor Ajax ev ...

The maximum property in a Mongoose schema does not have any impact or

const mongoose = require("mongoose"); const PostSchema = new mongoose.Schema( { user_id: { type: String, required: true, }, content: { type: String, max: 150, required: true, }, }, { timest ...

Sort out the table using Javascript and then choose all the checkboxes

I'm struggling with a function in Javascript that will only check checkboxes on visible rows of an HTML table. The table has a checkbox on each row and is filtered based on a textbox above the table. The checkboxes in the table are named chkbuild, an ...

What could be causing my page width to only expand to 100% when using "fit-content"?

After searching extensively, I'm unable to find a solution that fits my current issue. My goal is to construct a practice ecommerce website using React. One of the components I have is a header which I'd like to occupy 100% of the screen width, c ...