Is it possible to show one element while hiding others upon clicking using JavaScript?

Concept

My idea is to create a website with a navigation menu where only one section is visible at a time. Each section would become visible upon clicking a specific button in the navigation bar.

Challenge

I attempted to achieve this using the following code:

$(document).ready(function show(){
  document.getElementById(#showElement).style.display= "block";
})

The issue I am facing with this code is that I am unable to determine which button was clicked and subsequently identify the sections that should have display:none; applied to them.

Given my limited experience with JavaScript, I am unsure if this task is feasible and how I would go about implementing it.

As someone new to JavaScript, any guidance you can provide would be greatly appreciated. Thank you in advance.

Answer №1

Indeed, you have the ability to accomplish this task by concealing all sections except for the one that corresponds with your navigation link. Take a look at this sample code snippet.

const links = document.querySelectorAll("nav a");

for (let link of links) {
    link.addEventListener('click', function(e) {
        const sections = document.getElementsByTagName("section");
        for (let section of sections) {
            if ("#" + section.id === link.getAttribute("href")) {
                section.style.display = "block";
            } else {
                section.style.display = "none";
            }
        }
    });
}
body {margin: 0}
section {
    height: 500px;
    width: 100%;
}
nav {
    position: fixed;
    top:10px;
    left: 20px
}
<nav>
  <a href="#one">one</a> |
  <a href="#two">two</a> |
  <a href="#three">three</a> |
  <a href="#four">four</a>
</nav>
<section id="one" style="background-color: coral"></section>
<section id="two" style="background-color: cyan; display: none"></section>
<section id="three" style="background-color: mediumspringgreen; display: none"></section>
<section id="four" style="background-color: moccasin; display: none"></section>

Answer №2

Let me illustrate a method to display and conceal elements with a button click. In this scenario, I am alternating between revealing and hiding two elements:

document.getElementById('toggleBtn').addEventListener('click', toggleDivs);

function toggleDivs() {
  var div1 = document.getElementById('div1');
  var div2 = document.getElementById('div2');

  if (div1.style.display != 'none') {
    div1.style.display = 'none';
    div2.style.display = 'inline';
  } else {
    div1.style.display = 'inline';
    div2.style.display = 'none';
  }
}
<div id="div1">
  <p>There is some content in div 1</p>
</div>
<div id="div2">
  <p>Here you will find content in div 2</p>
</div>
<input id="toggleBtn" type="button" value="Toggle Divs" />

Answer №3

check out this example of bootstrap

Are you familiar with bootstrap?

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>

Check out this link for more information on using Bootstrap for tabs and dropdowns it can help you achieve what you are looking for.

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

Developing an npm console application that is "installable" similar to tools like yeoman, gulp, or grunt

Recently dipping my toes into the world of NPM, I've been itching to create a package that functions as a console app (think gulp and grunt). My goal is simple: I want users to be able to run npm install -g mypackage followed by mypackage This sh ...

Disregarding boundaries set by divisions

Trying to keep things concise here. I have a division called "the box" with a fixed width of 1200px that contains various other divisions. One of these divisions is a links bar, known as the "pink bar", which has a width of 100% and a height of 25px. My is ...

Error: Attempting to modify a constant value for property 'amount' within object '#<Object>'

After fetching data from an API, I stored an array in a state. Upon trying to update a specific field within an object inside the array using user input, I encountered the error message: 'Uncaught TypeError: Cannot assign to read only property 'a ...

Check the validity of the data by logging into another website

I've run into a bit of a problem while working on my website. Here's a brief explanation (using fake addresses), I have a website, www.website1.com, with lots of well-coded elements. You can log in to this website using www.website2.com. So whe ...

Instructions for importing a CSV file into PostgreSQL with Node.js

Just dipping my toes into the world of node js. I've got a csv file sitting on my local system that I'm eager to upload to my local PostgreSQL Database using node js. Here's what I've been experimenting with: var csv = require(' ...

Having trouble showing the material-ui icon on my navigation menu

How can I use Material-UI icons like <AddOutlinedIcon /> in my nav menu without displaying the actual code before the menu name? Do I need to escape the icon code somehow to make it appear correctly? The intended result is to have a + icon displaye ...

Printing a specific column of a particular row in an HTML table to the printer: Tips and tricks

How can I print a specific column from a particular row in an HTML table? I've attempted various CSS and jQuery methods I found online, but none of them seem to be effective. ...

Bootstrap is designed to dynamically adjust to the size of the browser window, ensuring a smooth

After completing the construction of a new website, I encountered an issue where the styles and layouts are responsive when adjusting the browser window size. However, upon opening responsive inspect tool, no changes occur - columns refuse to break and t ...

``After initialization, the service is unable to retrieve the object as

I have a special service that stores specific objects to be shared among different controllers. Here is an example of the code I am using: $rootScope.$on('controller.event', function(event, arg){ self.backendConnectorService.getBac ...

Web application using HTML5, AJAX, and a manifest file for offline usage

Looking for help with an issue on my website: Currently trying to put it offline. Using the manifest file: Encountering an issue with the left and right arrow navigation while offline. The browser shows an xmlhttprequest error, similar to the one found ...

Display your StencilJs component in a separate browser window

Looking for a solution to render a chat widget created with stenciljs in a new window using window.open. When the widget icon is clicked, a new window should open displaying the current state while navigating on the website, retaining the styles and functi ...

Error: The function 'document.getsElementsByClassName()' is not defined when evaluating 'undefined'

Actual Error TypeError: undefined is not a function (evaluating 'ActiveElem[i].hasClass('active'); HTML <div class = 'Carousel-Inner'> <div class="morningSlide active"> <img src="/Users/KO527/Sites/TarasDeli ...

Steps for creating a PDF file from an HTML page using JavaScript coding

I'm developing an HTML5 hybrid iPad app and need to create a PDF file of a report generated on one of the pages. I would like to save this PDF on the iPad. Can you provide assistance with achieving this task? I am utilizing JavaScript and mobile jQuer ...

Retrieve the value of a PHP array within a for loop and transfer it to JQuery

*edited format I came across a PHP code for a calendar on the internet and I am currently working on implementing an onclick event that captures the date selected by a user as a variable (which will be used later in a database query). At this point, my g ...

Managing data in React and JavaScript: Clearing fields upon successful sign up and redirecting to login page after receiving a 200 status code

Here is the code for my SignUp react function. After receiving a response of 200 upon clicking the Sign up button, I want to clear the text in all three fields and redirect the user back to the login page. I'm new to web development so any assistance ...

Extracting information from JSON using jQuery

this is a sample json object: { "box 1": [{ "difficulty_grade": "5a+" }, { "gym": "New_gym" }, { "route_author": "some author" },]} https://i.sstatic.net/UJodJ.png Here is the code snippet: variable groups contains JSON data as shown in the ...

Using Vuejs to display errors with alerts

Is there a way to display errors using alerts in bootstrap when working with vuejs? This is an example of the code: <div v-if="this.getError"> <div v-for="(_errors, key) in this.getError"> <p>{{key.repla ...

Intelligent programming and innovative thinking to streamline template diversity

My goal is to create multiple child websites using a base HTML/CSS template. Each child website will have unique color schemes and image variations for elements like <h> tags and background colors. I am searching for ways to easily modify the base th ...

Dealing with the problem of delayed image loading in AngularJS due to a setTimeout conflict

The issue: Upon page load, some images are still processing and not displaying (even though the image URLs are known). The resolution: To address this problem, a customized directive was developed to showcase a loading spinner as a placeholder until the i ...

What is the reason behind Google Closure Compiler appending a variable to the global namespace when the original namespace was blank?

My long script is neatly enclosed within a (function() {/.../})() to prevent any name pollution. It has been typed with complete accuracy and zero warnings. I recently discovered that Google Closure compiler initially redefines i and j in the global names ...