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

Initiate a Gravity Forms form refresh after modifying a hidden field with jQuery

TO SUM IT UP: Is there a way in Javascript to activate an update on a Gravity Form that triggers the execution of conditional logic? ORIGINAL QUESTION: I'm using Gravity Forms and I have set up an "on change" event $('#gform_1').find(&apos ...

Formatting dates in a C# MVC application after parsing JSON

I am working on an MVC application that retrieves data from a SQL database and passes it to a view. One of the views contains a Kendo grid that displays the data, including a date column. The date data is stored in the SQL database as DateTime, while the m ...

How can we automatically redirect users to an external website based on their responses to a specific question in SurveyJS?

Within my SurveyJS json, I have a radiogroup question that prompts users to make a choice. If they select a specific option, I'd like to redirect them to a different page. Otherwise, I want them to continue with the survey. Is this achievable? (The s ...

I am having trouble with my scroll reveal effects on JavaScript, how can I troubleshoot and fix the issue?

I'm currently making updates to my portfolio website, but for some reason, the scroll reveal animation has suddenly stopped working. I made a few edits and now it seems to be broken. /*===== SCROLL REVEAL ANIMATION =====*/ const sr = ScrollReveal({ ...

Troubleshoot: Bootbox Confirm Functionality Issues

Can anyone help me troubleshoot this issue? I'm trying to implement code that uses bootbox.confirm when deleting a file, but it's not functioning correctly. $('#fileupload').fileupload({ destroy: function (e, data) { var that = $(th ...

A guide on showcasing the compilation results of PHP code directly on the web browser

How can I compile PHP code on an HTML Button click and display the compilation output in a browser? The code snippet below works well in the terminal but doesn't show anything in the browser. I am currently using XAMPP server on a Windows machine. &l ...

JavaScript property counterparts

Recently, I've been working on creating alias's for a specific property in my code. var default_commands = {} default_commands['foo'] = "bar"; My goal is to create multiple aliases for the key 'foo' in the object. For examp ...

The two divs are positioned on top of one another, with the link in the bottom div being unclickable

I am trying to create a unique effect where a tile divides into two on hover, with each tile acting as an individual link. Additionally, I want the background color of the tiles to change on hover. To achieve this, I have stacked two divs (toptile and bot ...

Is your Navbar having trouble readjusting its height?

My navbar is not resizing properly when I shrink the logo image. Here's a link to the Codepen page with the full code: https://codepen.io/gabor-szekely/pen/JeMqQz I'm trying to reduce the size of the "Sino Medical" logo image in the top left co ...

Achieving Text Wrapping Around Unconventional Shapes Using CSS

I'm currently facing a challenge in getting text to wrap around an irregular shape on a web page. Despite numerous attempts, I have yet to find a solution that meets my requirements. Attached is an image illustrating the layout I am aiming for. The ...

What is the best method for setting up message scheduling for a Microsoft Teams bot based on different time

I am trying to figure out how to send messages to users from my bot at specific time intervals. Currently, I'm using agenda for scheduling messages, but I've run into an issue with the timezone discrepancy - agenda is 5:30 hours behind my timezon ...

I'm having trouble getting an audio file to play in my Laravel application. I uploaded the audio file to local storage, but when I try to play it using the audio tag, it's not

Having trouble with the path of my mp3 file stored in local storage and saved in the database. When retrieving the record from the database along with the mp3 file, it seems like the path is incorrect and I can't play it. I executed php artisan stora ...

Matching multiple divs with different ids in PHP using preg_match_all and regex

I have an HTML page structured like this: <!DOCTYPE html> <html> .... <body> <div class="list-news fl pt10 "> Blue </div> <div class="list-news fl pt1 ...

Retrieve the concealed method's name within the immediately invoked function expression (IIFE

This Meteor sever code has a private method called printFuncName within an IIFE. However, when this method is invoked from a public method, it results in the following error: TypeError: Cannot read property 'name' of null I am curious to unde ...

Transform a span into a div while retaining its content and styles, ensuring compatibility with Internet Explorer

Is there a reliable JavaScript method to convert a span into a div while preserving its contents and the original classes of the span? The classes are pre-set, so hardcoding should be possible. <span class="my class"> <p class="conten ...

If the number exceeds 1, then proceed with this action

I currently have a variable called countTicked, which holds an integer representing the number of relatedBoxes present on the page. I am in need of an if statement that will perform certain actions when the value stored in countTicked exceeds 1. if (!$(c ...

Positioning elements within a Bootstrap column: Fixed versus Absolute positioning

Striving to maintain the absolute positioning of the right column as users scroll through the left column has proven to be a challenging task. Despite exploring various solutions from stackoverflow and google, none seem to effectively address this issue. ...

Is there a way to apply textTransform to all components across the board?

I need to ensure that all text in my muiv5 project is capitalized by default, unless specifically overridden using sx or individual component styling. My attempted solution: <ThemeProvider theme={theme}> <IntlProvider locale="en& ...

When requesting a Node.js API from Javascript fetch, the session custom property is throwing an undefined error

I am currently working on a User Login Project, where the APIs are built using Node.js and Express. The UI part is developed using HTML and JavaScript, with these components existing as separate projects. Upon user login, a fetch call is made in JavaScrip ...

What is the best way to incorporate PHP code within a JavaScript function?

Is it possible to dynamically append the uploaded file name to the list displayed in ('.list')? The challenge lies in passing $_FILES["fileImage"]["name"] as an argument to a separate JavaScript function for appending, especially since the PHP sc ...