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 are the steps to perform an Ajax request to an online web service?

I would like to send an AJAX request to an external web service using jQuery. However, I am encountering an error and unable to receive a successful response from the server. var url = "http://www.example.com/api/convert"; var requestData = { temperat ...

Is your script tag not functioning properly with Promises?

Below is the code snippet used to dynamically append scripts in the DOM using promises. This piece of code is executed within an iframe for A-frame technology and it is generated using Google Blockly (Block-based coding). export const appendScript = asy ...

Display JSON data in a hierarchical tree structure using AngularJS

Looking to display three nodes of a JSON file as a tree using AngularJS. The nodes are data.key, data.parentItem, and data.title. Below is the JavaScript code: var phonecatApp = angular.module('myApp', []) phonecatApp.controller('myContr ...

React JS does not allow TextField and Select to change

I am relatively new to full stack development and I am currently working on a project to enhance my understanding of frontend development with React JS. While working on this project, I have been using Redux without any issues so far. However, I am facing ...

How can I conceal login and register router-links in the Vue + Laravel SPA project navbar immediately after a user logs in?

Currently, I am working on my Bachelor's degree project and have encountered a specific issue. While the login, register, and logout functions all seem to be working well, there is an inconsistency with the navigation bar not automatically switching b ...

Initiate the execution of JavaScript functions in the loaded partial view using Ajax

I am currently working with a javaScript function that loads a partial view within my page's layout using the following logic: $('.follow-tasks').click(function (e) { e.preventDefault(); var $followtaskList = $("#td-" + $(this).attr ...

The validation did not pass using the validate.min.js script

Hey everyone, I had this code working perfectly before but now it seems to have stopped working. Can anyone help me figure out what's going on? Below is the form I am referring to: <form action="CreateUser" method="POST" id="subscribe"> & ...

Ways to modify babel output file extensions

I'm facing an issue where babel --out-file-extension is not working as expected. Below is my package.json : { "name": "Assets", "version": "1.0.0", "description": "", "main" ...

Load HTML table values dynamically with Ajax post page load in PHP

My goal is to retrieve the connectivity status of available servers in a database on a PHP page. <tbody> <?php foreach ($data['servers'] as $server) { ?> <tr> <td class=""><?php echo $server->server_ ...

error in jquery when splitting

I encountered an issue while trying to split data for checkboxes. var ukuran = data['model'].ukuran_model; var cek = ukuran.split(",").join('], [value='), $inputs = $('input[name^=ukuran]'); $inputs.filter('[value=&a ...

Avoiding white spaces in user input with Material UI (MUI)

<FormControl variant="standard"> <InputLabel className="input-box-label" htmlFor="component-helper">My Value</InputLabel> <Input id="component-helper" value={m ...

Create an interactive visualization using d3.js

Currently, I am on the hunt for a technology that can help me render a tree structure based on Json data. After researching options like graphViz and d3, it seems like d3 is more optimized for modern browsers. With the extracted Json data, my goal is to c ...

Why is ng-bind-html not functioning within ng-repeat when ngSanitize is included in the module?

I'm a beginner with AngularJS and I'm trying to bind tags inside an ng-repeat loop, but I've tried using ng-bind-html and ng-bind-html-unsafe without success. The output is not displaying correctly. <script src="https://ajax.googleapis.c ...

NextJS rendering props in a loop

I need help figuring out how to render props in a loop using the forEach function. This is my current code: {console.log('the catalog inside the component ----->', catalog)} {Object.keys(catalog).forEach(key => { return ( <d ...

Vue JS: Extracting both the unique ID and value from an array of input simultaneously

I am new to Vue and currently exploring its capabilities. I am experimenting with the Element UI for Vue's user interface. Specifically, I am working with the Input Number Component, to manage an array of data. Let's assume my data is structured ...

The search button is malfunctioning after I submit search data and generate dynamic HTML using axios

When a user clicks on the search button, I retrieve the input value and then use axios to send a GET request with the search data. Everything works fine, but when I query the database and dynamically create data from the mongoose data, the page reloads w ...

There appears to be an inexplicable issue hindering the functionality of smoothscroll in

Continuing to improve my website: I have implemented a button for scrolling down the page, but I would like to add smooth scrolling functionality for a better user experience. After some research and experimentation, I came across this compact script tha ...

Tips on how to properly position the navigation bar within a wrapper element

I'm having trouble fixing the navigation bar at the top of the wrapper when scrolling down. However, when I try using position: fixed in the #nav ul, the navigation bar extends beyond the wrapper. Below is my HTML code, where the nav bar should be con ...

SVG text tags displaying Russian characters incorrectly

Upon visiting my website, I noticed that the Russian text within the SVG is not displaying correctly in certain browsers. Here is the code snippet causing the issue: <g> <rect id="XMLID_2_" x="409.1" y="102.3" transform="matrix(0.7071 -0.7071 ...

What is the best way to extract multiple values from a JavaScript variable and transfer them to Node.js?

Script JavaScript script snippet embedded at the bottom of an HTML file: var savedValues = [] var currentId = document.getElementById("fridgeFreezer").value function handleChange() { // Logic to handle user input changes: var temp = document.ge ...