JavaScript allows for the manipulation of elements within a webpage, which includes accessing elements from one

There is a file that contains a fragment for the navbar. The idea is to have listItems in the navbar, and upon clicking on those listItems, another subnavigationbar should open below it.

Below is the code I currently have:

<!DOCTYPE html>
<html xmlns:th="https://www.thymeleaf.org"
    xmlns:sec="https://www.thymeleaf.org/thymeleaf-extras-springsecurity5">
<body>
    <div>
        <div th:fragment="navbar">
            <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
                <button class="navbar-toggler" type="button" data-toggle="collapse"
                    data-target="#navbarTogglerDemo03"
                    aria-controls="navbarTogglerDemo03" aria-expanded="false"
                    aria-label="Toggle navigation">
                    <span class="navbar-toggler-icon"></span>
                </button>

                <div class="collapse navbar-collapse">
                    <ul class="navbar-nav mr-auto mt-2 mt-lg-0">
                        <li class="nav-item active"><a id="movies"
                            th:class="(${#httpServletRequest.requestURI}=='/movies') ? 'nav-link active' : 'nav-link'"
                            href="#subNavbarId">Movies</a></li>  <!-- href fails -->
                        <li class="nav-item"><a id="hr"
                            th:class="(${#httpServletRequest.requestURI}=='/info') ? 'nav-link active' : 'nav-link'"
                            href="/info">Info</a></li>

                    </ul>
                </div>

                <ul class="nav navbar-nav navbar-right">
                    <div sec:authorize="isAuthenticated()">
                        Logged in: <span sec:authentication="name"></span>
                    </div>
                </ul>
            </nav>
            <script type="text/javascript">
                var projects = document.getElementById("movies");
                var subNavBar = document.getElementById("subNavbarId"); //Failure
                projects.addEventListener("click", function() {
                    subNavBar.style = "display:block;"
                })
            </script>
        </div>

        <div class = "subNavClass" id="subNavbarId" th:fragment="subnavbar" style="display: none;">
            <nav id="navbar-nav ms-auto" class="navbar navbar-expand-lg"
                style="background-color: #F5F5F5;">
                <div class="collapse navbar-collapse">
                    <a class="navbar-brand px-5"></a>
                    <ul class="navbar-nav mr-auto mt-2 mt-lg-0">
                        <li class="nav-item"><a id="subnavbar-content"
                            href="/movieList"> movieList</a></li>
                    </ul>
                </div>
            </nav>

            <script type="text/javascript">
                var subNavBar = document.getElementById("subNavbarId");
                subNavBar.addEventListener("mouseleave", function() {
                    subNavBar.style = "display:none;"
                })
            </script>
        </div>
    </div>
</body>
</html>

The desired scenario is to click on "movies" in the navbar and have a subnavbar displayed with movieList. Similarly, when clicking somewhere outside, the subnavbar should fade away.

Please provide guidance. PS: Complete beginner here

Answer №1

The code

subNavBar.style = "display:block;"
appears to be incorrect.

A more appropriate syntax would be

subNavBar.style.display = "block";

Answer №2

Based on information from the Bootstrap documentation, a dropdown menu can be implemented as follows:

<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c7a5a8a8b3b4b3b5a6b787f2e9f6e9f4">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">

<div class="btn-group">
  <button type="button" class="btn btn-primary dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false">
    Action
  </button>
  <ul class="dropdown-menu">
    <li><a class="dropdown-item" href="#">An action</a></li>
    <li><a class="dropdown-item" href="#">Another action</a></li>
    <li><a class="dropdown-item" href="#">Something else here</a></li>
    <li><hr class="dropdown-divider"></li>
    <li><a class="dropdown-item" href="#">Separated link</a></li>
  </ul>
</div>

<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1f7d70706b6c6b6b57a26f6c7f5966347"15eaeeece8ecf4"\>[email protected]</a>/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>

It is advised to refrain from altering CSS using Javascript. Instead, create and toggle a CSS class. In the case of Bootstrap, you can toggle the provided d-none class like this:

subNavBar.classList.toggle("d-none");

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

What is the best way to wrap the content of a div and include ellipsis at the end?

There is a div on my page that shows some content. What I need is for it to display only the first 10 characters followed by '...' if the content exceeds that limit. 10 characters + '...' I have the option to use either jQuery or PHP ...

Incorporating JavaScript/jQuery values into C# backend with ASP.NET

Despite attempting all possible methods, I am unable to pass the screen.width value from a JS script on an aspx page to C# in the code behind. Even though the screen.width is correctly assigned, it never gets passed to my hidden field value. <asp:Conte ...

Creating an HTML file with a Windows-inspired icon and file name design using CSS

I searched everywhere on the internet but couldn't find a solution. If anyone knows of a similar link to my question, please share it with me. I am trying to achieve a design similar to Windows icons and file names in HTML using CSS. Please refer to ...

Seeking a method to attach information from a div to a hyperlink

As a complete novice in the world of CSS websites, I find myself struggling to accomplish what seems like a simple task. I am working with an automatically generated CSS/JavaScript website where on the "individual" page, a person's name is listed with ...

How can I transform a Firestore collection into an array?

I'm struggling with converting the data retrieved from Firestore into an array that can be used for a chart.js graph. Retrieving Data from Firestore fetchData(){ //Get data this.updatesCollection = this.afs.collection(pathStats); this. ...

Shifting Vue components within the dom structure?

Whenever I am on a mobile device, I move Vue components higher up in the dom so that I can use absolute positioning without being contained within a relative container. if (this.mobile) { this.$el.parentNode.removeChild(this.$el); document.getElem ...

Transmitting an image from an HTML file to a Node.js server

Hello, I am currently working on capturing frames from a video and converting them into images. However, I am encountering an issue when passing this image to server.js as I am unable to access it and the console shows its type as undefined. Below is the s ...

implementing HtmlSpanner with an appended css stylesheet

Using HtmlSpanner with CSS for TextView I recently discovered a library called HtmlSpanner that claims to assist in adding an HTML string with CSS to a TextView. However, I am struggling to locate any detailed documentation on how to achieve this, except ...

Troubleshooting automatic login problem in VB 2013 settings

For my application, I am utilizing the most recent version of Awesomium's WebControl. The goal is for it to automatically log in when it reaches "accounts.google.com/ServiceLogin" by executing some Javascript. In my.settings.java file, I have the foll ...

I am unable to engage with an element encapsulated within a #shadow-root that includes an <iframe> element

Original page source: Currently utilizing selenium with Java for web automation. In order to reach the shadow-root, I am utilizing JavaScriptExecutor (document.shadowRoot.querySelector) Successfully able to interact with various elements within the page ...

Leverage the power of JSON data in conjunction with HighCharts through

I'm struggling to understand the JSON format and HighCharts. Despite trying various techniques found on forums, I haven't been able to achieve the desired result. Here's my issue: 1- When clicking, an Ajax call is made to a PHP file that g ...

Filtering function that works without specific knowledge of keys

I'm working on a JavaScript method to filter a list dynamically without knowing the specific key (s). I've made some progress, but I'm stuck and not sure how to proceed. The foreach loop I have isn't correct, but I used it for clarity. ...

Guide to generating a text string by utilizing the foreach loop

Is there a way to combine text strings from interfaces into a single file for display in UI? The current code is generating separate files for each interface. How can I achieve the expected result of having all interfaces in one file? Additionally, is it ...

CSS challenge: designing a tab interface

I am facing a CSS challenge that has got me stumped. I'm not even sure if it's achievable. Here is what I'm trying to achieve: There are three buttons/tabs displayed like this . When a tab is clicked, a different div should be shown for eac ...

Oops! Looks like we couldn't locate the request token in the session when attempting to access the Twitter API

Every time I attempt to connect to the Twitter API using Passport OAuth, an issue arises that redirects me to an error page displaying this message: Error: Failed to locate request token in session at SessionStore.get (/Users/youcefchergui/Work/ESP/socialb ...

Adapting padding based on the height of the browser to ensure optimal layout

I'm interested in adjusting the padding value of a button element based on the height of the browser window, not its width. I want to make sure that the padding adjusts proportionally to the browser window's height. Is this achievable using CSS? ...

Silhouette as the backdrop image

There is a span element that I am using in the following way - <span class="tick"></span> This creates a decorative "tick" for a checkbox. The CSS code used for this is - input[type="checkbox"] + span > span.tick { display: block; ...

Retrieve a JSON response from within a schema housed in MongoDB

I have a document structure that looks like this: { "id": "someString", "servers": [ { "name": "ServerName", "bases": [ { "name": "Base 1", "status": true }, { "name": "Base 2", ...

Website Not Loading Correctly

Why is my webpage not loading properly, even though it has the same HTML and CSS as my other functioning pages on the site? The page loads without the h1 element. If I comment out the span used for adding a transparent background image behind the whole we ...

What is the best way to maintain the layout design when resizing the font?

Here is the HTML and CSS code snippet: .navi ul li { float:left; list-style-type: none; border-right: 1px solid #c0c0c0; margin:0px 0 0 0; } .navi ul li:last-child { border:none; } .navi ul li a { display:block; margin:0 20px; text-dec ...