Concealing subcategories within a responsive menu using jQuery

My website's responsive menu changes based on screen resolution, but I encountered an issue. On mobile viewports, the sub items in the menu are displayed by default. I want them to only appear when the parent item is clicked. Currently, clicking the parent item shows/hides them correctly, but I want them to start hidden. The code snippet below illustrates my implementation:

<script>
// JavaScript code for toggling menu and sub-menu items
$(document).ready(function () {
    // Code for toggle functionality
});
</script>

<style>
/* CSS styles for the menu */
@media (min-width: 768px) and (max-width: 979px) {
    /* Media query specific styling */
}

@media (max-width: 767px) {
    /* Media query specific styling */
}

@media (max-width: 480px) {
    /* Custom styling for smaller viewports */
}

@media (max-width: 320px) {
    /* Styling adjustments for tiny screens */
}
</style>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <meta name="description" content="" />
    <meta name="author" content="" />
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
  
    <!-- Link your CSS files here --!>

    <link rel="stylesheet" href="mobile/css/style.css" type="text/css" media="screen" />
    <link rel="stylesheet" href="mobile/font-awesome/css/font-awesome.css" />
</head>
<body>    
<form id="mainform" runat="server">
         <div class="container">
        <a id="touch-menu" class="mobile-menu" href="#"><i class="icon-reorder">AGROBIZSA</i></a>
            <nav>
                <ul class="menu">
                    <li><a href="#"><i class="icon-home"></i>Inicio</a></li>
                    <li><a id="sub-menu-anchor-1" href="#"><i class="icon-user"></i>Noticias</a>
                        <ul id="sub-menu-1" class="sub-menu">
                            <li><a href="#">Últimas Noticias</a></li>
                            <li><a href="#">Noticias Corporativas</a></li>
                            <li><a href="#">Ecoambiental</a></li>
                            <li><a href="#">Agropecuaria</a></li>
                            <li><a href="#">Innovación</a></li>
                            <li><a href="#">Agronomía</a></li>
                            <li><a href="#">Salud</a></li>
                        </ul>
                    </li>
                    <li><a id="sub-menu-anchor-2" href="#"><i class="icon-camera"></i>eBooks</a>
                        <ul id="sub-menu-2" class="sub-menu">
                            <li><a href="#">Sanidad Vegetal</a></li>
                            <li><a href="#">Medio Ambiente</a></li>
                            <li><a href="#">Social</a></li>
                            <li><a href="#">Suelos y Agua</a></li>
                            <li><a href="#">Producción Agrícola</a></li>
                            <li><a href="#">Gestión</a></li>
                        </ul>
                    </li>
                    <li><a href="#"><i class="icon-bullhorn"></i>Hoy en la Historia</a></li>
                    <li><a href="#"><i class="icon-envelope-alt"></i>Eventos</a></li>
                </ul>
            </nav>
    </div>
        <div class="container">
            <asp:ContentPlaceHolder ID="empaquetador" runat="server">
            </asp:ContentPlaceHolder>
        </div>
    </form>
</body>

Answer №1

Consider trying out this code snippet:

$(document).ready(function () {
        var touch = $('#touch-menu');
        var menu = $('.menu');
        var touchsub1 = $('#sub-menu-anchor-1');
        var submenu1 = $('#sub-menu-1');
        var touchsub2 = $('#sub-menu-anchor-2');
        var submenu2 = $('#sub-menu-2');
        var touchsub3 = $('#sub-menu-anchor-3');
        var submenu3 = $('#sub-menu-2');

        $(touch).on('click', function (e) {
            e.preventDefault();
            menu.slideToggle();
        });

        $(touchsub1).on('click', function (e) {
            e.preventDefault();
            submenu1.slideToggle();
        });
        $(touchsub2).on('click', function (e) {
            e.preventDefault();
            submenu2.slideToggle();
        });
        $(touchsub3).on('click', function (e) {
            e.preventDefault();
            submenu3.slideToggle();
        });

        w = $(window).width();
        if (w < 767) {
            $('.sub-menu').hide();
        }

        $(window).resize(function () {
            var w = $(window).width();
            if (w < 767 && menu.is(':hidden')) {
                menu.removeAttr('style');
            }
            if (w > 767) {
                $("#sub-menu-1").css('display:', 'none;');
                $("#sub-menu-2").css('display', 'none');
                $("#sub-menu-3").css('display', 'none');

                }
        });

    });

I specifically integrated the check for window width outside of the resize() function to ensure that submenus are hidden when the screen size is less than 767. You can observe the functionality by visiting this link.

Answer №2

attempt:

$(document).ready(function () {
            var touch = $('#touch-menu');
            var menu = $('.menu');
            var touchsub1 = $('#sub-menu-anchor-1');
            var submenu1 = $('#sub-menu-1');
            var touchsub2 = $('#sub-menu-anchor-2');
            var submenu2 = $('#sub-menu-2');
            var touchsub3 = $('#sub-menu-anchor-3');
            var submenu3 = $('#sub-menu-2');

            $(touch).on('click', function (e) {
                e.preventDefault();
                menu.slideToggle();
            });

            $(touchsub1).on('click', function (e) {
                e.preventDefault();
                submenu1.slideToggle();
            });
            $(touchsub2).on('click', function (e) {
                e.preventDefault();
                submenu2.slideToggle();
            });
            $(touchsub3).on('click', function (e) {
                e.preventDefault();
                submenu3.slideToggle();
            });
            touchsub1.trigger('click');
            touchsub2.trigger('click');
            touchsub3.trigger('click');

            $(window).resize(function () {
                var w = $(window).width();
                if (w > 767 && menu.is(':hidden')) {
                    menu.removeAttr('style');
                }
               if (w > 767) {
                    $("#sub-menu-1").css('display:', 'none;');
                    $("#sub-menu-2").css('display', 'none');
                    $("#sub-menu-3").css('display', 'none');

                    }
            });
});

preview:
http://jsbin.com/nedodafizi/1/edit?html,css,js,output

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

MAC Safari is not registering input fields

I'm experiencing a small issue with a form that has two input fields for indicating time (in the format HH:mm) that are very close together, like this: Here is the HTML code snippet: <label> <span>Hour*</span> <input typ ...

As the screen width shrinks, I've noticed that my grid system in HTML using Bootstrap starts to glitch

Why is my row going onto a second line when I shrink the width? Here is a screenshot of the issue. I am currently using bootstrap 5 for this and I am unsure how to fix it. Below is the code snippet: Current Screenshot Below is the desired look on mobil ...

Utilize AJAX, PHP, and MySQL to create a search functionality that retrieves data from a MySQL database based on a dynamically generated variable

I'm in the process of creating a custom part builder and am working on implementing a search function within MySQL Database based on the Part Number generated. The goal is to display the price in a table cell. However, I'm encountering difficulty ...

Calculate the total amount from the selected items on the list, depending on the clicked ('active') element

My main objective is to achieve the following: Before any clicks || After the user selects the desired item After conducting some research, I successfully implemented this using vue.js https://jsfiddle.net/Hanstopz/Lcnxtg51/10/ However, I encountered ...

Create a toggle effect using attribute selectors in CSS and JavaScript

I am looking to switch the "fill: #000;" from the CSS property "svg [id^='_']". Usually, I would use a method like this, but it seems that I can't do so because "svg [id^='_']" is not an element, correct? pub.toggleClass = functi ...

Changing the visual appearance of an alert in JavaScript and HTML

My knowledge in JavaScript is limited, but I have a script that retrieves a query from a Python service to a Mongodb database. The query is returned in the following format: [{CHAIN: "STREET ELM, ELMER", CODE: "1234"}, {CHAIN: "STREET LM, LMAO", CODE: ...

Looking for a reliable CSS aggregator for .Net that can merge and minimize style sheets effectively?

Is there an open source or free project that offers a CSS manager? I want to optimize performance and am hoping to find a pre-built solution rather than starting from scratch. Some key features I'm looking for include: Merging multiple .css files in ...

What is the method for determining the width of a Mat-Table once it has been displayed?

When utilizing Angular Material Mat-Table in conjunction with Angular 8, I am passing the dataSource dynamically. The number of rows and columns varies each time. Is there a method to calculate the width of the table once it is rendered on the screen? &l ...

Problems with Displaying Facebook Ads on Mobile Web

Currently, I am incorporating Facebook Audience Network (MobileWeb-beta) for advertisements on my mobile website. However, the 320x50 HTML source code is not displaying the ad across the width of the mobile screen as intended; instead, it appears smaller ( ...

What is the most dependable method for referencing a CSS class through programming?

Within my Sharepoint project, I am dynamically generating controls in the overridden CreateChildControls() method. I am uncertain which approach is more preferable when it comes to referencing the .css file: protected override void CreateChildControls() { ...

Align a button to the left or right based on its position within the layout

On the left side, there is dynamic text and on the right side, a button is displayed as shown below: <div class="dynamic-text"> {{ dynamicText }} </div> <div class="some-button"> < ...

drop down menu in navigation bar: unable to display items

I am having trouble with a dropdown menu in my code. Even though I used the code from the official Bootstrap website, the items are not appearing in the dropdown list. <nav class="navbar navbar-expand-lg navbar-dark bg-primary "> ...

Exploring the functionality of placeholders within jQuery

I am trying to create a customizable text template where I can insert placeholders and then fill those placeholders with data to use on my page. For example: var template = '<div class="persons">'; template += '<p> <span clas ...

The pair of divs with distinct backgrounds

Looking to customize the navigation on my website by creating a separate background for the list links menu and making sure the left part of the navigation with the logo has its own distinct background that extends until the next div. I've experimente ...

Is there a way to freeze a row in Bootstrap 4?

I recently put together a slider featuring four images, but I've encountered an issue. When the pixel size drops below 768px, the image quality diminishes and they start stacking on top of each other. Is there a way to keep the images in a single row ...

Is there a way to prevent on-click errors in ReactJS that someone can share with me?

The onclick listener was expected to be a function, but instead received a value of string type. getListener@http://localhost:3000/static/js/bundle.js:18256:15 accumulateSinglePhaseListeners@http://localhost:3000/static/js/bundle.js:22846:39 <button on ...

Implementing the slideToggle function with Angular directives

Hi there! I have successfully implemented the slideToggle function using Angular and jQuery. To ensure that this function only affects a specific HTML element, I am currently passing a parameter within the ng-click function. While my code is functioning as ...

Arrange the table by column following a service request

Is there a method to organize the table below once it has been loaded? I am utilizing Google API to retrieve distance matrix data, but I want the table to be sorted by distance. However, this sorting should take place after the Google service call is comp ...

The issue of `window.setTimeout` not functioning properly with Google Maps Marker/XML integration has been a persistent

I'm having difficulty displaying markers individually from my database by making them "fly in." Here's the Ajax call: $.ajax({ type: "GET", async: true, url: '<?php echo PATH;?>ajax/map_process.php ...

Error in Jquery.get(): the success callback function is being triggered twice

I am experiencing an issue where the success callback function is being called twice, and I am unsure of why this behavior is occurring. $.get("getDetails", { selCity : $("#selCity")[0].value}, function(data) { alert("reached here"); $("#myform").html("") ...