Conceal and reveal text with a simple user click

Currently, I am working on a website project that utilizes bootstrap. However, I am facing some uncertainty regarding how to effectively hide and display text:

<nav class="navbar navbar-light" style="background-color: #e3f2fd;">
            <a class="navbar-brand" href="#">Navigate:</a>
            <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav">
                    <li class="nav-item active">
                        <a class="nav-link" href="index.html">Home <span class="sr-only">(current)</span></a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="price.html">Pricing</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="contact.html">Contact Us</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link disabled" href="#" tabindex="-1" aria-disabled="true">Disabled</a>
                    </li>
                </ul>
              </div>
        </nav>

I am specifically focused on the

<a class="navbar-brand" href="#">Navigate:</a>
element, where I want it to only be visible when users click the button to toggle the menu dropdown. Once they close the menu, this text should disappear. In essence, Navigate: should only show up when the menu is dropped down.

Despite my attempts, I have not been successful in achieving this functionality:

<script>
        function display(){
            if(document.getElementById("navbar-brand").style.display == "none"){
                document.getElementById("navbar-brand").style.display = "inline"
            }
            if(document.getElementById("navbar-brand").style.display == "inline"){
                document.getElementById("navbar-brand").style.display = "none"
            }
        }
        </script>

    <a class="navbar-brand" href="#">Navigate:</a>
        <button class="navbar-toggler" on-click="display()" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle 
navigation">

Answer №1

Check out this code snippet below:

https://jsfiddle.net/moti013/rfk69w7n/4/

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<script>
    function display(){
        if(document.getElementById("navbar-brand").style.display == "none"){
            document.getElementById("navbar-brand").style.display = "inline"
        }
        if(document.getElementById("navbar-brand").style.display == "inline"){
            document.getElementById("navbar-brand").style.display = "none"
        }
    }
    </script>
<nav class="navbar navbar-light" style="background-color: #e3f2fd;">
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">Navigate</button>
        <span class="navbar-toggler-icon"></span>
    </button>
    <div class="collapse navbar-collapse" id="navbarNav">
        <ul class="navbar-nav">
            <li class="nav-item active">
                <a class="nav-link" href="index.html">Home <span class="sr-only">(current)</span></a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="price.html">Pricing</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="contact.html">Contact Us</a>
            </li>
            <li class="nav-item">
                <a class="nav-link disabled" href="#" tabindex="-1" aria-disabled="true">Disabled</a>
            </li>
        </ul>
      </div>
</nav>

Answer №2

Here are two simple adjustments you can make:

1 - Insert the provided script into your code

2 - Update the button tag by including onclick="toggle()"

function toggle() {
  if (document.getElementsByClassName('navbar-toggler')[0].getAttribute('aria-expanded') !== 'true') {
    document.getElementsByClassName('navbar-brand')[0].style.visibility = 'visible';
    console.log(false)
  } else {
    console.log(true)
    document.getElementsByClassName('navbar-brand')[0].style.visibility = 'hidden'
  }
}

window.onload = () => {
  if (document.getElementsByClassName('navbar-toggler')[0].getAttribute('aria-expanded') === 'true') {
    document.getElementsByClassName('navbar-brand')[0].style.visibility = 'visible';
    console.log(false)
  } else {
    console.log(true)
    document.getElementsByClassName('navbar-brand')[0].style.visibility = 'hidden'
  }
}
<button onclick="toggle()" class="navbar-toggler" type="button" data-toggle="collapse"
  data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false"
  aria-label="Toggle navigation">
  <span class="navbar-toggler-icon"></span>
</button>

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 there a way to implement a scrollbar within a DIV element?

I'm working on a webpage that includes several customized buttons within multiple DIVs. Take a look at this example on the fiddle. Since I have a lot of buttons, I need to find a way to add a scrollbar so users can easily navigate to the desired butt ...

The variable referencing an unidentified function has not been defined

I've created an anonymous function assigned to a variable in order to reduce the use of global variables. This function contains nested functions for preloading and resizing images, as well as navigation (next and previous). However, when I try to run ...

The latest pathway fails to refresh in NextJs

I've implemented a search bar at the top of my app which directs to /search/[searchId].js page: <Link href={`/search/${search}`}> <button type='submit' className='btn-cta btn-3'>SEARCH</button> < ...

Utilizing the componentDidUpdate method to update the state within the component

I have a scenario where two components are enclosed in a container. One component is retrieving the Id of a publication, while the other is fetching the issue date related to that specific publicationId. When I retrieve an Id, let’s say 100, it successf ...

node-gallery reports: "No albums were discovered"

I am exploring the use of node-gallery in my Node js/Express/Jade project. After following the guidelines provided at https://github.com/cianclarke/node-gallery, I encountered an issue when attempting to access the page localhost:3000/gallery: {"message" ...

Is it possible to determine if a window was opened using window.showModalDialog()?

Is there a way to determine if a window was triggered by window.showModalDialog()? I've noticed that when a new window is opened using window.open(), window.opener correctly returns the parent window. However, when using window.showModalDialog(), wind ...

I'm running into an issue with my React component where it is rendering before the state is set, causing it to fail. Is there a

Is it possible for me to achieve what I've been attempting for the past week? I feel like I'm so close, yet still can't quite reach my goal. Could it be that what I'm trying to do is impossible? I am using reactjs and next js (although ...

What is the best way to save a current HTML element for later use?

Here is a simple HTML code that I would like to save the entire div with the class test_area and then replicate it when needed. Currently, my goal is to duplicate this div and place the clone underneath the original element. How can I achieve this? Unfortu ...

Content positioned beside an image with the help of Bootstrap 4 framework

How can I align text to the right of an image, like a table layout? I experimented with grid layout using <div class="span2"> and <div class="span10"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bo ...

Extracting web search result URLs using Puppeteer

I'm currently facing an issue with the code I've written for web scraping Google. Despite passing in a specific request, it is not returning the list of links as expected. I am unsure about what might be causing this problem. Could someone kindly ...

The Unit Test for Angular NgRx is not passing as expected

I'm facing difficulties with my unit tests failing. How can I verify that my asynchronous condition is met after a store dispatch? There are 3 specific checks I want to perform: 1/ Ensure that my component is truthy after the dispatch (when the cond ...

What is the best way to eliminate a count from an array when a button is deselected using JavaScript?

Whenever a button is selected, the value appears on the console.log as expected when using an array. To enhance this functionality, I also need to find a way to remove the value from the console when the button is deselected. var totalWishlist = []; $( ...

Create a typescript class object

My journey with Typescript is just beginning as I delve into using it alongside Ionic. Coming from a background in Java, I'm finding the syntax and approach quite different and challenging. One area that's giving me trouble is creating new object ...

Create eye-catching banners, images, iframes, and more!

I am the owner of a PHP MySQL website and I'm looking to offer users banners and images that they can display on their own websites or forums. Similar to Facebook's feature, I want to allow users to use dynamic banners with links. This means the ...

React hook form submit not being triggered

import React, { useState } from "react"; import FileBase64 from "react-file-base64"; import { useDispatch } from "react-redux"; import { makeStyles } from "@material-ui/core/styles"; import { TextField, Select, Input ...

Text box is not automatically filling up when selecting from dropdown menu

I am currently facing an issue with a dropdown box that offers three different selections. I want the Group ID associated with the selected group to automatically populate in the textbox below. How can I achieve this functionality? Whenever I make a selec ...

ClassSerializerInterceptor in NestJS does not show the _id field

I am encountering an issue with properly exposing the _id when using the Serializer. Here is my current setup: @UseInterceptors(ClassSerializerInterceptor) @SerializeOptions({ strategy: 'excludeAll' }) This is how I defined the Class: export cl ...

Struggling to display a function's output on a separate web page within a flask application

After spending close to 10 hours on this, I find myself stuck. My restaurant search app is functioning perfectly when I print the output to the terminal. However, I can't seem to figure out how to display it on a new page. Here's a snippet of my ...

Unlock the power of dynamic routes in Reactjs with this comprehensive guide

Currently, I am delving into the world of Reactjs and Nextjs, specifically working on dynamic routes. To elaborate, I have a list of blogs that I would like to showcase in detail. For this purpose, I created a folder named "blogs" and nested a file called ...

What is the proper way to link an image in a nuxt project?

I am working on a modal in the app.html file of my Nuxt project that prompts Internet Explorer users to switch to another browser. The modal includes links to three different browsers for download. Although the modal is displaying correctly, I keep encount ...