Create an elegant and responsive collapsible navigation bar with Bootstrap 4's standalone collapse JavaScript

After creating a small website using Bootstrap 4.3.1, I realized that the only JavaScript required is for the collapse plugin in the responsive navbar with a toggler button.

Unfortunately, since there is no longer a customizer for Bootstrap 4, I am forced to include jquery-3.3.1.slim.min.js (69 kiB) and bootstrap.min.js (57 kiB), resulting in a total download of 126 kiB of JavaScript just for an interactive menu toggle button on small screens.

Is there any way to reduce the file size of JavaScript downloaded by users?

Answer №1

Get rid of all jQuery and bootstrap JavaScript code, and incorporate the following script instead:

  <script type="text/javascript">
   const links = Array.from(document.querySelectorAll('[data-toggle="collapse"]'));
   links.forEach(link => {
       link.addEventListener('click', event => {
           const selector = link.getAttribute('data-target');
           collapse(selector, 'toggle');
       });
   });

   const actions = {
       'toggle': 'toggle',
       'show': 'add',
       'hide': 'remove'
   };

   const collapse = (selector, action) => {
       const targets = Array.from(document.querySelectorAll(selector));
       targets.forEach(target => {
           target.classList[actions[action]]('show');
       });
   };
  </script>

This script was inspired by https://medium.com/dailyjs/mimicking-bootstraps-collapse-with-vanilla-javascript-b3bb389040e7

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

Error occurring when attempting to pass messages within an iframe on a sandboxed page in a Chrome extension

Whenever I try to utilize my popup page for a chromium extension as a conduit for communication between the background page and a page shown within an iframe on the popup, I encounter the following error. I required a sandboxed environment to execute Vue.j ...

How can I stop the hover event on a series in Highcharts from triggering a hover event on the nearest point (marker)?

When hovering over the series line on a date-time chart, the default behavior is to trigger the hover event on the nearest point of the series. However, I only want to trigger the hover event on the markers (points), not the series itself. If I use stopP ...

Exploring Unicode Symbols for Icon Selection

I'm currently working on integrating an icon picker into my application that will enable the user to select a mathematical operator for data comparison. While I have successfully implemented the fontawesome-iconpicker on the page, I am encountering d ...

Unable to refresh the view from the controller once the promise has been resolved

On my webpage, I want to display a dynamic list of items that updates whenever the page is refreshed. To achieve this, I am using Parse to store and retrieve my items using promises. Here's a simplified example of how it works: When the index.html pa ...

Utilizing Bootstrap to allow for seamless text wrapping around a text input field

I am trying to implement a "fill-in-the-blank" feature using Bootstrap, where users need to enter a missing word to complete a sentence. Is there a way to align the text input horizontally and have the rest of the sentence wrap around it? This is my curr ...

Is there a way for me to divide the data in a JSON file and display user tags in place of their IDs?

Looking to create a list admins command for a bot, I'm facing challenges in converting user ids to tags within the command. Take a look at what I have accomplished so far: const { MessageEmbed } = require('discord.js'); const { readFileSync, ...

JQuery UI autocomplete vanishes instantly without any warning

I am encountering an issue with JQuery UI's autocomplete feature where the dropdown results do not stay visible. While debugging, I noticed that the list briefly appears before disappearing. Below is my code snippet: HTML: <input type="text" plac ...

Leverage moment.js for formatting dates within a Vue component

I am currently working on a Vue component that includes an input field with a date type: <input type="date" name="start_date" id="start_date" v-model="absence.start_date" > Within my script, I ...

Open the HTML page from a separate directory

I'm facing an issue with loading additional HTML onto a page in my project when a link is clicked. The HTML fragment file I want to load is stored in a different folder within the project structure. Despite my efforts, I keep encountering a 404 error ...

Capture line breaks from textarea in a JavaScript variable with the use of PHP

I need help with handling line breaks in text content from a textarea. Currently, I am using PHP to assign the textarea content to a Javascript variable like this: var textareaContent = '<?php echo trim( $_POST['textarea'] ) ?>'; ...

Filtering an array in Vue using Lodash based on the values of another array

As I continue to learn JavaScript, I have encountered something that is confusing me. Within my Vue data object, I have the following properties: data: { allergenFilter: [], categoryFilter: [], results: {}, }, I am using an array of check ...

I am unsure of the timestamp format for the value 1522899000000. Can it be used in both Ionic and AngularJS? And how would one go

While parsing a JSON from an external URL, I came across a timestamp with the value starttime: 1522899000000 (on 4/5/2018 -> 5th April 2018). The value seemed like a Unix timestamp, but when I tried to convert it, it displayed the year 1912. What kind o ...

The Gulp task is stuck in an endless cycle

I've set up a gulp task to copy all HTML files from a source folder to a destination folder. HTML Gulp Task var gulp = require('gulp'); module.exports = function() { return gulp.src('./client2/angularts/**/*.html') .pipe( ...

no visible text displayed within an input-label field

Currently, I have started working on a multi-step form that is designed to be very simple and clean. However, I am facing an issue where nothing is being displayed when I click on the next arrow. I am puzzled as to why it's not even displaying the te ...

Exploring the mechanics of JavaScript and jQuery Ajax: What's the secret to its function

It's common knowledge that browsers are single-threaded, meaning they can only either render the UI or execute Javascript snippets. While web workers offer a way to achieve multi-threading, let's focus on the default behavior. I'm curious a ...

Can you provide me with the sequelize query that is equivalent to this raw query?

Retrieve the ID from the offers table where the user ID is not equal to '2' and the ID is not present in the list of notified offers for user '2'. ...

What are the steps to ensure my MERN application refreshes properly when deployed on Heroku?

After successfully deploying my MERN app to Heroku, I encountered an issue where pages would come up blank when refreshed. Despite being able to navigate between pages using the nav bar without any errors, a page refresh renders them empty. This troublin ...

Customizing external elements with React's inline styling feature

Trying to use React to style elements generated by a third-party library has been a challenge. In the snippet below, I was able to achieve the desired styling using CSS, but now I am looking to accomplish the same using JavaScript. This way, users can defi ...

Experiencing a lack of information in express?

Whenever I attempt to send a POST request (using fetch) with the body containing the state of the application, I receive an empty object on the server side. What am I doing wrong here? I should be receiving the object with the properties name, username, an ...

Why am I consistently obtaining NaN as the output for the majority of my calculations?

Looking to calculate the average of cities in each state using the Reduce Function in mongoDB, but encountering an issue where only one correct result is obtained while rest return as 'nan'. Below is the map function: function map(){ key = {sta ...