JavaScript vanilla can be difficult to grasp, especially when it comes to

I'm experiencing a delay in displaying and hiding the mobile menu and table of contents section on my website when viewed on a mobile device. I'm using vanilla JavaScript to add and remove classes, but it's taking about one second for the menus to show or hide. How can I make them open immediately? Can someone help me identify the issue with my JavaScript implementation?

Website:

function myFunction() {
        var x = document.getElementById("myTopnav");
        if (x.className === "topnav") {
            x.className += " responsive";
        } else {
            x.className = "topnav";
        }
    }

Answer №1

Store the element in cache:

const navigation = document.getElementById('myNavigation');

Add an eventListener:

<a href="#" class="icon" id="menuButton"><small>MENU</small> </a>

JavaScript code:

document.getElementById('menuButton').addEventListener('click', event => { 
  event.preventDefault(); // prevent default action
  navigation.classList.toggle('responsive')
});

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 most efficient method for sending query parameters through a URL in Vue.js with Axios?

My goal is to use Axios upon page load to retrieve a JSON object from the base URL. When a button is clicked, I want to append query parameters to the URL and fetch a different JSON object. For example, if the base URL is 'test.com', clicking the ...

What is the functionality of the "async:false" setting in a jQuery AJAX request?

I understand the purpose and usage of {async:false} in jQuery AJAX requests. However, I am curious to know how this operates synchronously. What is the mechanism behind it? ...

The issue of JQuery UI Dialog remaining open even after triggering it through an Input focus event

I am facing an issue with JQuery and JQuery UI. I thought upgrading to the latest stable version would solve it, but unfortunately, that was not the case. I am currently using Chrome. When I initiate the dialog by clicking on a specific element, everythin ...

Adjusting the empty image source in Vue.js that was generated dynamically

Currently experimenting with Vue.js and integrating a 3rd party API. Successfully fetched the JSON data and displayed it on my html, but encountering issues with missing images. As some images are absent from the JSON file, I've saved them locally on ...

What is the proper way to utilize useRef with HTMLInputElements?

Dealing with React and hooks: In my code, there is a MainComponent that has its own operations and content which refreshes whenever the value of props.someData changes. Additionally, I have designed a customized InputFieldComponent. This component generat ...

Can date ranges be utilized as separate date items on the time scale in D3.js?

I have a chart that resembles the one shown below, however, there is a crucial component missing. Currently, my time scale follows the standard format as depicted in the first picture. I am looking to convert it to the time scale seen in the second picture ...

Having trouble with the `npm run dev` command in a Laravel project? You may be encountering a `TypeError: program.parseAsync is not

Recently, I integrated Vue.js into my ongoing Laravel project using npm to delve into front-end development with the framework. Following the installation, the instructions guided me to execute npm run dev in order to visualize the modifications made in . ...

What is the process for comprehending an event that is not triggered by the task queue within the event loop specifications?

According to the guidelines: Various events are triggered through tasks apart from just the task queue. I am curious to understand what exactly is meant by "various" and the specific types of tasks being referred to here? ...

Delete the placeholder image from a div once live content has been inserted into it

If I have a container div that displays an image when empty, but I want to remove the image when content is dynamically added to the container, what would be the most effective way to do this with jQuery? The usual method of checking if the container' ...

npm not working to install packages from the package.json file in the project

When using my macbook air, I encounter an issue where I can only install npm packages globally with sudo. If I try to install a local package without the -g flag in a specific directory, it results in errors. npm ERR! Error: EACCES, open '/Users/mma ...

Adding content to an empty element will not produce the desired result

I'm trying to show each character of a string, which is stored in an array, one at a time. However, when I use threadsleep(a) with the code found here: http://jsfiddle.net/thefiddler99/re3qpuoo/, all the characters are displayed at once. There seems t ...

How to import an HTML file using TypeScript

I need to load an html file located in the same directory as the typescript file and return it from the function. public ...(... ) : angular.IHttpPromise<string> { ... return $http({ method: 'GET', url: &apos ...

What is the process for assigning a function and its arguments as a callback in programming?

Here is a code snippet for your consideration: $scope.delete=function(){ foo('x',3); }; How can we improve the clarity of this code snippet when the callback function contains only one line that calls another function? It's important ...

The time zones between Node 8 and Node 11 are not the same

Executing a basic new Date().toString() command produces different results on Node 11 compared to Node 8. In Node 11, the output includes the full timezone abbreviation like this: 'Fri May 10 2019 10:44:44 GMT-0700 (Pacific Daylight Time)' On t ...

I am looking to change the state of only the element that is being moused over in a React Hooks useState function, rather than changing the

Currently, I have a component from line 61-67 that controls the state of an editIcon. The issue is that it changes the state values for all items in the column, rather than just the specific item or row it should apply to. When hovering over a span element ...

Obtain the selected dropdown value and transfer it to the controller seamlessly without the need to reload the page

Currently, I am facing an issue with two dropdown lists in a bootstrap modal - CATEGORY and SUBCATEGORY. The values in the SUBCATEGORY list depend on the selection made in the CATEGORY list. My goal is to retrieve the selected value ID and pass it to my co ...

How to modify values in a JSON array using JavaScript

Currently, I am facing an issue with displaying dates properly on the x-axis of a graph created using Highcharts. To solve this problem, I need to parse the dates from the JSON response. Despite my attempts to manipulate the JSON date, I have not been able ...

The function of AJAX is to send and receive data asynchronously without

Recently, I was experimenting with AJAX. When I use echo "hello" in my PHP file, everything works perfectly. However, if I try something like echo "<script language=Javascript> alert('hi');</script>"; in the PHP file, the alert ...

Executing a sequence of jQuery's $.when().then() functions

I am facing challenges in understanding how to properly sequence my functions, especially in relation to the $.when() method. function y() { defer = $.Deferred(); $.when(defer).then(console.log(defer.state())); } y(); <script src="https://ajax.go ...

I'm having trouble with my Selenium as it doesn't seem to be able to open

Hey there, I've been working on a script to login to Gmail, but I'm having trouble with entering the password after entering the email. public static void main(String[] args) throws Exception { System.setProperty("webdriver.chrome.driver", "E:&b ...