When space runs out, tuck menu choices into the "more" button

As I venture into the world of web development, please forgive me if my queries seem elementary.

I am currently using Bootstrap 4 and have implemented a navbar with a hamburger menu that hides the entire menu when the screen reaches a certain width. However, I wish to modify this so that individual menu elements hide within a "more" button one by one. Essentially, if only one menu option exceeds the space available, it should move to the "more" button.

Initially, I attempted to use JavaScript to adjust the screen width and make the last element disappear:

setInterval(okno, 25)

function okno() {
    var a = window.innerWidth;
    if (a < 1335) {
        document.getElementById("kontakt").style.display = "none";
    }
}
<nav class="navbar navbar-expand-xl navbar-light"
    style="background-color:dimgrey;position:fixed;width:100%;z-index:100">
    <button class="navbar-toggler" type="button" style="background:white;float:left !important" data-toggle="collapse"
        data-target="#colapsibleNavbar">
        <span class="navbar-toggler-icon" style="color:black !important"></span>
    </button>
    <div class="collapse navbar-collapse justify-content-center" id="colapsibleNavbar">
        <ul class="navbar-nav">
            <li class="nav-item">
                <a class="nav-link" href="kopysno.html">Strona Główna</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="Aktualnosci.html">Aktualności</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="mapaokolicy.html">Mapa Okolicy</a>
            </li>
            <li class="nav-item">
                <div class="dropdown">
                    <a class="dropdown-toggle" style="text-align:center;text-decoration:none" data-toggle="dropdown"
                        href="#">Informacje</a>
                    <div style="background-color:dimgrey" class="dropdown-menu">
                        <a class="dropdown-item" href="Historia.html">Historia</a>
                        <a class="dropdown-item" href="#">Geografia</a>
                        <a class="dropdown-item" href="#">Środowisko</a>
                        <a class="dropdown-item" href="#">Kartografia Archiwalna</a>
                        <a class="dropdown-item" href="#">Galeria Fotografii</a>
                    </div>
                </div>
            </li>

            <li class="nav-item">
                <a class="nav-link" href="#">Filmy</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="dawnimieszkancy.html">Dawni Mieszkańcy</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="#">Artykuły prasowe</a>
            </li>
            <li class="kontakt nav-item">
                <a class="nav-link" href="kontakt.html">Kontakt</a>
            </li>
        </ul>
    </div>
</nav>

Unfortunately, this approach does not yield the desired results, and I am unsure why. Can anyone provide assistance? Thank you in advance.

Answer №1

You currently do not have an element with the ID kontakt, but you can locate it using its className by utilizing

document.querySelector('.className')
.

To solve this, create a function and execute it when the DOM is fully loaded or when the window is resized by adding event listeners for each scenario:

function showHideElement() {
    if(window.innerWidth < 1335) {
         // Hide the element if window width is less than 1335
         document.querySelector(".kontakt").style.display = "none";
    } else {
         <!-- Show the element if window width is greater or equal to 1335 -->
         <!-- Use an empty string to set the default display setting of the element -->
         document.querySelector(".kontakt").style.display = "";
    }
}
// Execute the function when the DOM is fully loaded
document.addEventListener('DOMContentLoaded', showHideElement);
// Execute the function when the window is resized
window.addEventListener('resize', showHideElement);
<nav class="navbar navbar-expand-xl navbar-light" style="background-color:dimgrey;position:fixed;width:100%;z-index:100">
                        <button class="navbar-toggler" type="button" style="background:white;float:left !important" data-toggle="collapse" data-target="#colapsibleNavbar">
                            <span class="navbar-toggler-icon" style="color:black !important"></span>
                        </button>
                        <div class="collapse navbar-collapse justify-content-center" id="colapsibleNavbar">
                        <ul class="navbar-nav" >
                           <!-- Navigation Links -->
                        </ul>
                        </div>
                    </nav>

Answer №2

Have you ever considered using a CSS script like this?

  <style>
       #your_div{
           max-height: specify your desired height here, for example 150px;
       }
  </style>

Then you can run a JavaScript code to monitor the div's height. If the height exceeds or matches a certain value, you can use .append to add a button that triggers the following function:

<button onclick="my_function()" value="Load More Content">
 <script>
      function my_function(){
           $.("#your_div").style("max-height", "1000px (any number will work)");
      }
 </script>

This is just a suggestion, but hopefully it proves useful.

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

Issue with Axios Get method: Data not displaying in table

Can someone assist me with displaying JSON data on my website? I am using an API with a security token, and everything seems to be working fine until I try to display the JSON data on my page. I can see the data in my console, but not on the actual page. ...

Refreshing JWT Authentication in Angular

I am currently following a tutorial on Egghead.io, which can be found here. However, I am adding a MongoDB to fetch my users which is causing me some issues. I have managed to get everything working except for the part where it mentions that the /me route ...

How can I bring a "floating" element above its sibling element without taking up space?

I have attempted setting all the parent elements to relative and this specific one to absolute, but it doesn't seem to be working. I'm quite puzzled at this point, here is the code snippet: <template> <div> <div @mouseover=" ...

Python: Change text within HTML content rather than the HTML tags

Looking for help with converting HTML code? <pre class="script">template("main/GlobalShared");</pre> <pre class="script"> var link = '/Draft/Tracker_1.1'; if (wiki.pageexists(link)) { &lt;div class="version"&gt; web ...

Attempting to send a formik form to a specified action URL

Seeking assistance with a simple fix as I navigate through the learning process. I have created an action called addTenant() that is supposed to receive the state and use it to dispatch a post API call, like so: export const addTenant = (tenant) => (di ...

Using controllerAs in an AngularJS directive allows for multiple instances to be created, each with the

In my form, I have directives that contain identical input fields, selects, and check boxes. To handle this, I created a directive with an isolate scope and controllerAs syntax using bindToController=true. The controller has a method triggered by an ngChan ...

I created a footer using Bootstrap 4 that is perfectly centered on the desktop version but unfortunately appears off-center on mobile devices

.footer_img{ padding-left: 30px; width:170px; height:63px; align-self: center; } .footer{ margin-bottom: 41px; } <div class="footer container"> <div class="clearfix"> <span class="float-left"><a href="#"><img class="footer_img ...

What is the best way to implement startdate and endate in Bootstrap React JS?

I am attempting to create a date input where the end date cannot be selected before the start date (e.g. if I choose 10/10/2019 as the start date, the end date should only allow dates from 10/10/2019 onwards). I have tried implementing this in React js b ...

Choose Option 1 in order to proceed with selecting Option 2 and displaying the outcome in the VueJs framework

Looking for help on how to show the text value from multiple related select fields. I want Option 1 to display a list of parent options. Upon selecting an Option 1, it should determine what values are available in Option 2 select field. After selection, ...

Exploring the potential of utilizing records within deepstream.io

Lately, I've been delving into the world of records and I find myself pondering on the practical limitations when it comes to the size of a json structure. Is there a recommended maximum length? Can you store an entire chat history as an (anonymous) r ...

VueJS File Upload Field Failing to Reset Post Successful Submission

I am facing an issue in my VueJS application where the form does not clear all field values after submission, especially the file upload field. After a successful submission, the uploaded file name still remains displayed on the screen. Below is the code ...

Exploring ways to create a dynamic background image that allows the rest of the page to float over seamlessly

Currently working on a responsive website and almost done with the build. However, I came across a site where an image appears to be floating behind the rest of the webpage content. Tried searching for a solution using w3.css without any luck. Any sugge ...

Use an array to populate a map in Javascript

While working in JavaScript, I am in need of an equivalent of a hash map. After some research, it appears that using the Map object would be the most suitable option. However, my requirement is to set the value of each key-value pair in the Map as an array ...

Jest - Silence greets the test results

Struggling with Jest has been a common theme for me ever since I first attempted to use it. Regardless of the tests I run or the options I try to pass to Jest, I never seem to get the expected 'Pass' or 'Fail' results in the console. In ...

The AngularJS ngModel directive encounters issues when used within a ui-bootstrap tabset

Check out the code snippet below to see the issue at hand: <!DOCTYPE html> <html ng-app="plunker"> <head> <title>AngularJS Plunker</title> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/cs ...

Troubleshooting a TypeScript Problem with React Context

In my AppContext.tsx file, I have defined the following import React, { useState, createContext } from "react"; import { Iitem } from "../utils/interfaces"; interface AppContext { showModal: boolean; setShowModal: React.Dispatch< ...

Customize the CSS for material-ui buttons or create a new style altogether

Looking to customize the background color of a material UI RaisedButton, I have encountered a challenge. This is what I currently have: const style = { backgroundColor: 'green' }; export default class CreateLinksave extends React.Component { ...

How can I detect when the user has finished typing in the input field using React?

I've implemented a highly efficient component that sends messages to the server and displays them to other users in real-time. Check out the code snippet: const ChatInput = (props) => { const [message, setMessage] = useState(''); con ...

Take away the attention from the span element

I have been experimenting with the following jsfiddle and attempted various methods suggested in this Stack Overflow thread, but I am struggling to remove the focus from the "feedback" span after clicking on the cancel button in jQuery confirm dialog. Her ...

Customizing the appearance of the browser's autocomplete feature as we input information into the form field

https://i.sstatic.net/p7PvH.png The image illustrates the issue of the background turning white when the browser autofills. However, I am seeking a solution similar to the transparent input below. ...