Conceal a particular object from view by selecting it from the menu

I want to hide a specific element when the burger button is clicked. (See CaptureElementNoDisplay.PNG for the element to hide)

When I click the burger button again to close the menu, I want the hidden item to be displayed once more.

I've successfully hidden the introduction element with the logo when displaying the menu. (Refer to CaptureElementNoDisplay.PNG)

However, I'm struggling to display the div containing the intro and logo in the center again. (See CaptureElementNoMoreDisplay.PNG)

Visit the website:

Here is the source code:

Source Code HTML :

<nav class="navbar navbar-dark justify-content-end" style="background-color: #0145FF;">
           
<button id="home" class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarToggleExternalContent" aria-controls="navbarToggleExternalContent" aria-expanded="false" aria-label="Toggle navigation"> <span class=" navbar-toggler-icon "></span>
</button></nav>

<section id="intro1" style="height: 652px;background-color: #0145FF; ">

<div class="center logo-intro-1">
<img src="./assets/images/logo_adding.png " alt=" " width="450 ">
</div>

<ul class="nav flex-column text-right pr-5">
<li class="nav-item">
<a class="nav-link2 text-white" href="">Black</a></li>
<li class="nav-item"><a class="nav-link2 text-white" href="#">Red</a></li>
<li class="nav-item"><a class="nav-link2 text-white" href="#">Violet</a></li>
<li class="nav-item"><a class="nav-link2 text-white" href="#">Blue</a></li>
<li class="nav-item"><a class="nav-link2 text-white" href="#">Green</a></li></ul>
</section>

Source Code JavaScript :

$('.navbar-toggler').click(function() {
var booleanNoDisplay = true;
var intro1 = document.getElementById("intro1");
intro1.classList.add("NoDisplay");


    if (booleanNoDisplay) {
        console.log('ok TRUE');
        $('#intro1').show(); // This line is not useful because the element is already displayed by default
        booleanNoDisplay = false; //I don't know when to set the value to false...
    }


    if (!booleanNoDisplay) {
        console.log('ok false');
        $('#intro1').hide();
        intro1.classList.add("display-block");

        booleanNoDisplay = true;
    }
});

Can you help identify where the issue might be coming from?

Thank you for your assistance in advance.https://i.sstatic.net/G70xU.png

https://i.sstatic.net/pZukM.png

https://i.sstatic.net/yIFvW.png

Answer №1

Make sure to move the variable var booleanNoDisplay outside of your click statement. Additionally, consider converting if (!booleanNoDisplay) { into an else if statement, like else if (!booleanNoDisplay) {

Demo

var booleanNoDisplay = true;
$('.navbar-toggler').click(function() {
  var intro1 = document.getElementById("intro1");
  intro1.classList.add("NoDisplay");

  if (booleanNoDisplay) {
    console.log('ok TRUE');
    $('#intro1').show(); // This line is not useful because the element is already displayed by default
    booleanNoDisplay = false; //I don't know when to set the value to false...
  } else if (!booleanNoDisplay) {
    console.log('ok false');
    $('#intro1').hide();
    intro1.classList.add("display-block");

    booleanNoDisplay = true;
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<nav class="navbar navbar-dark justify-content-end" style="background-color: #0145FF;">

  <button id="home" class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarToggleExternalContent" aria-controls="navbarToggleExternalContent" aria-expanded="false" aria-label="Toggle navigation"> <span class=" navbar-toggler-icon "></span>
</button></nav>

<section id="intro1" style="height: 652px;background-color: #0145FF; ">

  <div class="center logo-intro-1">
    <img src="./assets/images/logo_adding.png " alt=" " width="450 ">
  </div>

  <ul class="nav flex-column text-right pr-5">
    <li class="nav-item">
      <a class="nav-link2 text-white" href="">Black</a></li>
    <li class="nav-item"><a class="nav-link2 text-white" href="#">Red</a></li>
    <li class="nav-item"><a class="nav-link2 text-white" href="#">Violet</a></li>
    <li class="nav-item"><a class="nav-link2 text-white" href="#">Blue</a></li>
    <li class="nav-item"><a class="nav-link2 text-white" href="#">Green</a></li>
  </ul>
</section>

Answer №2

Important points to note

  • When the boolean is placed within the click event handler, clicking on the button will result in the variable being true every time because it is constantly initialized.

  • Avoid complicating things by adding a class NoDisplay to intro1 every time the method runs; this step is unnecessary.

  • The variable name for the Boolean was confusing, so I changed it to IsDisplayed.

  • Since there are only two scenarios, using else if is not required.

Give this code a try

var IsDisplayed = true;

$('.navbar-toggler').click(function() {
  
  var intro1 = document.getElementById("intro1");

  if(IsDisplayed){
     $('#intro1').hide();
     IsDisplayed = false;
  } else {
     $('#intro1').show();
     IsDisplayed = true;
  }
 
});

Answer №3

I modified my code to mirror the structure of your code with some adjustments. Now, I am utilizing the .toggle() method and it seems to be working fine. The only change I made was adding certain properties to my style.css file.

Below is the JavaScript code I'm using:

var isVisible = true;

$('.navbar-toggler').click(function() {

    var introduction = document.getElementById("intro1");

    if (isVisible) {
        console.log('ok TRUE');
        //$('#intro1').hide(); 
        introduction.classList.toggle("noDisplayElement");
        isVisible = false;
    } else if (!isVisible) {
        console.log('ok false');
        //$('#intro1').hide();
        introduction.classList.toggle("displayElement");
        isVisible = true;
    }
});

And here is the CSS code I've added:

.noDisplayElement {
        display: none!important;
    }
    
    .displayElement {
        display: block!important;
    }

It's almost achieving the behavior I desire.

Upon clicking the navigation menu on the top left thrice, both the menu and the div containing intro1 are displayed. However, I believe there might be an issue with the condition. Any suggestions on what I should do differently?

You can view the outcome by visiting this link:

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

Creating custom designs for Material UI components

Although not a major issue, there is something that bothers me. I am currently using react, typescript, and css modules along with . The problem arises when styling material ui components as I find myself needing to use !important quite frequently. Is th ...

Exploring the potential of Python loops within Selenium capabilities

My latest project involves scraping data from a search page. Specifically, I need to extract the title, price, and link for each of the 25 results on the page. To achieve this, I'm working with Xpath and utilizing an incremental div number associated ...

Sorting buttons using JQuery UI Buttonset

Experimenting with combining jQuery sortable interaction and the buttonset widget to create a unique sortable button set has led me to this jfiddle: http://jsfiddle.net/HK7rX/3/. The initial approach involved applying both buttonset and sortable to the sa ...

Issue with PrimeNG Carousel width on mobile devices

Currently, I am in the process of developing a system interface with Angular and PrimeNG specifically for mobile devices. The main requirement is to have a carousel to display a set of cards. After evaluating different options, I decided to utilize the ngP ...

"Troubleshooting a 400 Bad Request Error in Node.js and Express for a

It seems like I must be making a silly mistake, because this should be a simple task. All I want to do is send a POST request in an Express route. This is my app.js: var express = require('express'); var path = require('path'); var f ...

Ways to analyze users who have clicked a button

After a user registers, they are automatically taken to /proto where they can view a list of animals available for adoption. However, the challenge lies in identifying the specific user who clicked the button (as this information must be associated with th ...

What could be causing my website to extend beyond 100% width?

I've been working tirelessly on solving this issue for the past week, but unfortunately, I haven't had any luck finding a solution. The problem arose as I was designing a launch page for a program that my friend is developing. Despite setting the ...

Accessing and displaying all states in $stateProvider using AngularJS and ui-router

Here's a simple question: how can I find all instances of $stateProvider.state in my app.js, which is my AngularJS config file? In the past with ngRoute, I could achieve this by using a similar approach in my .run() block: .run(function ($route) { ...

Expand a div without causing any displacement to surrounding elements

If you have 4 colored divs (red, yellow, green, blue), with 2 per row, and need to expand the second (yellow) without creating a gap under the red, check out this solution. The blue will be positioned underneath the expanded yellow. For a live example, vi ...

Placing a pair of labels onto a bootstrap form while ensuring column alignment

I'm trying to format a form according to my UI/UX specifications, where there is a parent label and two sub-labels. Can this be achieved using Bootstrap? https://i.stack.imgur.com/J8wJZ.png However, I'm struggling to align the columns and rows ...

rearrange results in ng-repeat based on specified array in AngularJS

Currently delving into Angularjs and have a quick query: I recently received an array from a user which looks like this: userPreferences = [7,5,4] Additionally, I am working with an object that uses ng-repeat to showcase various news items. The object s ...

Blend field and JavaScript functions while retrieving data from MongoDB

Take a look at this information: { "creation_date" : ISODate("2015-02-10T03:00:00.000Z"), "days_of_validity": 10 } I need to find all documents where "creation_date" is less than today - "days_of_validity" This is what I have come up with so far: doc ...

Encountered an issue when attempting to establish a connection with the REST

I am encountering an issue with connecting to a web service deployed on an Apache server using Jersey. The error message I receive is: Failed to load http://192.168.1.200:8199/CheckinnWeb/webapi/myresource/query: No 'Access-Control-Allow-Origin' ...

Discovering the process of retrieving API data upon a button click within Next.js using server-side rendering

Hi there, I'm fairly new to working with next.js and would greatly appreciate some assistance. I am trying to figure out how to fetch data from an API upon clicking a button in next.js on the server side. I understand that using onClick directly is ...

Modify the appearance of the username in the header after logging in with Yii

As a fellow coder using Yii, I'm seeking assistance in changing the style of my username displayed in the header upon login. Currently, it's appearing in black color and I desire it to be italicized-white. The code snippet below shows my header s ...

Using JavaScript within Razor C#

I am attempting to invoke a JavaScript function from within a helper method in Razor. Here is a snippet of my code: @helper MyMethod() { for (int i = 0; i < 5; i++) { drawMe(i) } } The drawMe function is defined in an externa ...

Elegant Border Separator

I'm attempting to achieve the design below (with a 1 pixel gap on each end): ...

Tips for integrating custom code into your Angular cli service worker

Although I have successfully generated and configured the service worker using a config file generated by Angular CLI, I am struggling to find documentation on how to add custom code to the ngsw-worker.js file. I want to include functions such as push no ...

when the submit button is clicked, verify whether the input field is empty

I have exhausted all my options and nothing seems to work. All I want is for the following functionality to be implemented: When a submit button is clicked -> check if a text field is empty -> if it is, display an error alert and prevent advancing t ...

Disconnected WebSocket in Node.js using Socket.io

Currently, I am encountering an issue. It involves a login page that leads to another page where my socket connection is disrupted. The goal I am striving for is: Within my server-side app.js app.post('/login', urlencodedParser, function(req, ...