What should I do to resolve the issue of the function if ($(window).width() < 768) {} not functioning properly upon resizing the browser?

I am working on a functionality where the navigation bar items will toggle hidden or shown only when the browser width is less than 768px and an element with the class "navlogo" is clicked. I have included my code below for reference.

if ($(window).width() < 768) {

    $(".navlogo").click( function (){
        $(".navwrapper").toggle();
    });
    $(".navitem").click( function (){
        $(".navwrapper").hide();
   });

}

I understand that this might seem like a duplicate question, but it is not. My main concern is to make this functionality work without requiring a page refresh. If Angular.js is necessary for achieving this, I would appreciate guidance on the specific code to implement, as I am open to using it to enhance user experience.

One issue I have noticed is that if I do not include the following condition:

if ($(window).width() < 768) {}

The functionality still works correctly. However, even when the website is not in mobile mode (with a max width of 768px or lower), clicking on the element with the class "navlogo" hides the "navwrapper." While this behavior is not entirely undesirable, I would also like the "navwrapper" to hide when a user clicks on an element with the class "navitem."

Thank you for your assistance!

Answer №1

Ensure that the if statement is contained within the click function:

$(".navlogo").click( function (){
    if ($(window).width() < 768) {
        $(".navwrapper").toggle();
    }
});
$(".navitem").click( function (){
    if ($(window).width() < 768) {
        $(".navwrapper").hide();
    }
});

Edit:

To display or hide the .navwrapper based on window resizing, you should listen for the window resize event.

$(window).on('resize', function(e) {

    if ($(window).width() > 767 && $(".navwrapper").is(':hidden')) {
        $(".navwrapper").show();
    }

});

Here are some things to keep in mind:

  • Consider using variables for selectors that are repeatedly used
  • For efficiency, consider wrapping the actions inside the resize function with a timeout
  • Where possible, utilize CSS for responsiveness instead of relying solely on JavaScript

Answer №2

Are you considering implementing this feature exclusively for desktop platforms or do you want it to function on both mobile and desktop devices? If you're aiming for the latter, you can utilize two different events:

For mobile devices, use "orientationChange", and for desktop devices, utilize "resize".

For instance,

var supportsOrientationChange = "onorientationchange" in window,
    orientationEvent = supportsOrientationChange ? "orientationchange" : "resize";

Then,

$(window).on(orientationEvent, function(evt){
   if ($(window).width() < 768) {
    $(".navlogo").click( function (){
        $(".navwrapper").toggle();
    });
    $(".navitem").click( function (){
        $(".navwrapper").hide();
   });
}
});

Answer №3

If you're looking for a solution, I suggest utilizing the .resize() method in jQuery.

$(window).resize(function() {
    if(this.width() < 768) {
        $(".navlogo").click( function (){
            $(".navwrapper").toggle();
        });
        $(".navitem").click( function (){
            $(".navwrapper").hide();
        });
    }
});

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

The function createVNode does not exist in the context of Vue integrated with Laravel

I've been attempting to replicate a component rendering based on an online example. While it works smoothly in a sample project, it crashes when applied to the official codebase. Here is the content of the blade file being rendered: <html lang=&q ...

Hovering over a white background will darken the CSS styling

A stunning image on a dark background Displayed on Hover (right) An elegant picture with a white background Activated on hover (incorrectly) I would like it to have a darkened effect on the white background as well. CSS Styling .photo background: n ...

Encountering a "Window is undefined" error while trying to load a node_module package within a

I am attempting to incorporate the pickr package (a color picker library) into my nuxt.js application. However, I am encountering an error during import, specifically "window is undefined". Below is the code snippet: <script> import Pickr from &apo ...

Eliminate any unnecessary gaps that may exist between the cards within the deck

Utilizing Jinja2 with Flask to render a list on an HTML page, I aim to produce card decks containing data from the list using a Jinja2 loop. This is my current HTML code: <div class="container-fluid"> <div class="row"> <div clas ...

Differences between the http module and Express framework

After noticing this common pattern, I've become intrigued : const server = http.createServer(app); // Listen on provided port, on all network interfaces. server.listen(port); server.on('error', onError); server.on('listening', on ...

What is the process for editing or importing CSS within a React project?

I'm a beginner in React and I am encountering an issue with CSS not loading properly. I followed the tutorial for importing it, but it seems like there might be a better way to do it now as the tutorial is outdated. Below is my code, I would appreciat ...

Accessing RESTful data using an Angular service

I am currently following a tutorial on building a RESTful API using the MEAN stack from scotch.io. I have been able to successfully set up my API to return JSON data and now I am looking to test it out. Should I try accessing the API through the browser a ...

Concealing a div depending on the price variation

I'm looking for a way to dynamically show or hide a div based on the price of selected variations in my online store. Let's take a product with options priced at £359 and £455 as an example. In addition, there is a finance plugin with a minim ...

What is the best way to create an array within an object in JavaScript?

Here is the code snippet I'm working with: var Memory ={ personAbove: "someone", words: wordsMem = [] <<<<<this part is not functioning properly } I need help figuring out how to make it function correctly. Specific ...

Is there a way to troubleshoot why new data is not appending to existing data in React's infinite scroll feature?

I'm currently working on implementing react infinite scrolling for the first time. I've encountered an issue where the initial array of data keeps repeating. function Details() { const [facility, setFacility] = useState([]); const [loading, set ...

Decoding GeoJSON: Extracting a feature from an array

I am currently working on a map project where I am drawing polygons with properties pulled from a JSON file. Each polygon is colored based on feature values in the JSON file. Here's an example of a feature in the JSON file: { "type": "Feature", " ...

Creating collapsible items in Bootstrap

When using the standard bootstrap collapse tool, I encountered an issue: <div class="accordion" id="accordionExample"> <div class="card"> <div class="card-header" id="headingOne"> ...

What are some ways to display multiple divs within a single popup window?

I am attempting to create the following layout: https://i.sstatic.net/OzE98.png Here is what I have been able to achieve: https://i.sstatic.net/7GxdP.png In the second picture, the divs are shown separately. My goal is to display the incoming data in a ...

What causes my useEffect hook to trigger twice in React?

I'm currently utilizing @preact/signals-react in my react project for integration purposes. Encountered a challenge that requires resolution. Interestingly, I discovered that by removing import { signal } from '@preact/signals-react', the ...

Numerous data retrieval commands within the componentWillMount lifecycle method

Initially, I utilized the componentWillMount() method to populate the articles property successfully by iterating over the values to display various images/text. However, I am now encountering an issue as I also need to use componentWillMount to populate ...

Header formatting issue when attempting to implement tablesorter plugin

I implemented the widget-scroller and widget column Selector in my table using the table sorter plugin in jQuery. Has anyone encountered a problem like the one shown in this picture? It seems that my table headers do not align with the columns properly an ...

Enhance the appearance of datatables pagination with a personalized touch

I am working on a page that utilizes server-side datatables and I want to implement a custom pagination style on it: HTML <ul class="pagination pagination-danger"> <li class="page-item"><a class="page-link" href="#" data-original-title ...

What could be causing the calendar icon to not display in the table cell?

I've been working with the Bootstrap date picker inside a table, and I'm having trouble getting the date picker icon to display using the fas fa-calendar-alt css class. <td> <input type="text" id="expirydate{{$index}} ...

What could possibly be causing the "Unexpected token (" error to appear in this code?

Sorry if this appears as a typo that I am struggling to identify. My browser (Chrome) is highlighting the following line <a class="carousel-link" onclick="function(){jQuery('#coffee-modal').modal('show');}">Book a coffee</a> ...

Sort the array in alphabetical and numerical order while meeting a specific condition

In my code, I am attempting to sort an array based on two conditions. Specifically, I need to ensure that Pos 10 comes after single digits and follows a specific order after that. Initially, I tried to prioritize strings containing the word first, but whe ...