Modify the way the menu functions using only CSS or Javascript

Looking to update a menu using only CSS or JavaScript. The menu is designed for an e-commerce website, featuring categories with collapsed subcategories. I'd like the sub-categories to automatically expand when the page loads, eliminating the need for users to click on them to view. The domain for this project is www.tackpal.com.

Answer №1

After reviewing your website, I noticed that when a user clicks on a category, they are directed to the specific category's webpage. As a result, the subcategories are currently not displayed on the homepage.

Your initial suggestion is to modify the menu template in your CMS if it permits customization.

AN ALTERNATIVE APPROACH IS PROVIDED BELOW, ALTHOUGH MODIFYING THE TEMPLATE IN YOUR CMS WOULD BE PREFERABLE

By incorporating this code snippet, whenever a user visits the homepage, the following script will instruct the browser to make Ajax calls to all categories with subcategories. Upon receiving the source of each category page, it locates the list of subcategories and integrates them into the menu on the homepage accordingly.

To test this code, simply navigate to your website's homepage, open the console, and paste the initial functions followed by the script inside the onload function.

//Define a function to perform an AJAX call and execute a callback upon successful retrieval of the target page's source
function getSubPageSource(url, successCallback) {
    var xhr = XMLHttpRequest();
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4 && xhr.status == 200) {
            //Execute callback with the response text upon source retrieval
            successCallback(xhr.responseText);
        }
    };
    xhr.open('GET', url, true);
    xhr.send();
}

//Encapsulate within an onload event
window.onload = function() {  
    //Identify all categories with subcategories
    var categories = document.getElementsByClassName('has-subcategories');
    //Iterate through each category
    for (var ii = 0, nn = categories.length; ii < nn; ii++) {
        //Utilize a closure to pass a static index value
        (function(ii) {
            //Retrieve element
            var element = categories.item(ii);
            //Obtain ID
            var id = element.getAttribute('data-category');
            //Fetch URL
            var href = element.getAttribute('href');
            if (id && href) {
                //If found
                getSubPageSource(href, function(data) {
                    //Locate subcategories
                    //Extract section starting from where ID appears first
                    var substrSource = data.substr(data.indexOf('data-category="'+id+'"'));
                    //Remove remainder of the category title
                    substrSource = substrSource.substr(substrSource.indexOf('</a>'));
                    //Eliminate subsequent category finding
                    substrSource = substrSource.substr(0, substrSource.indexOf('home-categories-main'));
                    //Omit start of next category, retaining source of all subcategories
                    substrSource = substrSource.substring(0, substrSource.lastIndexOf('<a '))
                    //Insert after category title in main menu
                    console.log(id, substrSource);
                    //Create new node
                    var newNode = document.createElement("span");
                    //Inject source into new node
                    newNode.innerHTML = substrSource;
                    //Insert new node after current element
                    element.parentNode.insertBefore(newNode, element.nextSibling);
                });
            }
        })(ii);
    }
};

This implementation may solely function on the HOME PAGE ONLY, as testing beyond this scope has not been conducted. Application on other pages could potentially duplicate subcategory lists on respective category pages.

NOTE: A significant drawback of the featured technique is that whenever a visitor accesses your homepage, their browser simultaneously loads all category pages containing subcategories. As a result, your server will have to serve multiple pages for every homepage visit.

I highly recommend exploring options to customize the menu template in your CMS instead of utilizing the aforementioned script

Upon pasting the script above, your homepage should display the requisite links, visible in the accompanying screenshot below.

Answer №2

To begin, it's important to determine how the menu is collapsing or expanding. Typically, a menu will collapse with one class and expand with another class that is added through JavaScript (or possibly switched)

Without examining the CSS, it's difficult to provide a specific solution. You can either modify the default class of the categories:

height:0;

or

display:none;

Remove this code and make sure to unbind any click functions associated with the menus to prevent unintended triggering when clicking on them.

Once again, without seeing the actual code, it's challenging to give precise advice.

Edit: Disregard my previous response, I visited the link you provided. It appears that the subcategories are loaded via an ajax call. After reviewing some minified JavaScript files, it seems that without access to the original source code, making adjustments may not be feasible.

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

Unable to load JQuery from a div element

My goal is to create a standard .html file containing the navigation, footer, and other elements that will be used across multiple pages for a small site I'm building. I want to keep it simple and avoid using php or other programming languages. I&apo ...

The ethereal essence of my breath hovers just beyond reach- I yearn for it

I've been struggling to find a solution for this issue from various perspectives. You can view my map here: I am looking to have the country names displayed on top of everything else. Despite using z-index and having my span positioned absolutely, I ...

Fuzzy Background to Enhance Your Bootstrap 5 Offcanvas Navigation Menu

Currently utilizing Bootstrap v5.2, I am endeavoring to replicate the image displayed in the link below: Blurry Sidebar Backdrop As per the MDN Documentation, backdrop-filter is intended for blurring the background of an element. .offcanvas-backdrop { ...

What are some strategies for receiving multiple responses with just one ajax request?

. I am having trouble grasping the concept of using ajax and how to get multiple responses while passing a single request. Can anyone provide me with a sample code to help me understand better? ...

Graphql query using $http.post is unsuccessful

I successfully made a request for the code below, but I am encountering an issue where I am not receiving any data back. The "preview" tab of the request in Chrome simply displays "Error Not Found". Interestingly, when I try the same query in GraphiQL, i ...

Encountering an error with NextJs & Strapi when utilizing the getStaticPaths functionality

Currently, my project involves using Strapi to develop a custom API and NextJs for the frontend. I am experimenting with utilizing getStaticPaths to generate pages based on different categories. In Strapi, I have set up a collection for categories that is ...

Is there a way to have the even numbers in an array printed before the odd numbers?

Looking for a way to separate even and odd numbers into two arrays? This function will do just that, but with a twist - the evens array will be printed before the odds. var numbersArray = [1,2,34,54,55,34,32,11,19,17,54,66,13]; function customDivider(n ...

Tips for creating a Bootstrap table with a "table-bordered" style, fixed header, and scrollable body

How can I keep the table header fixed while allowing the body to scroll without breaking the table layout? I've tried using the CSS below, but it results in the width of the header columns being different from the width of the body columns. Any sugges ...

React: Render function did not return any content. This typically indicates that a return statement is missing

Can anyone help me troubleshoot this error? Error: CountryList(...): No render was found. This typically indicates a missing return statement. Alternatively, to display nothing, return null index.js import React from 'react'; import ReactDOM f ...

TinyMCE Node Replacement Feature

I am working on a WordPress plugin that adds a button to the TinyMCE editor. The intended behavior when the button is clicked is as follows: 1. If the selected text is not part of a shortcode (or is the shortcode itself), then the shortcode should be inser ...

Guide on selecting a specific title attribute as the chosen option in Angular by utilizing Bootstrap's selectpicker

I encountered an issue where some of the options in my select element have the same value, making it difficult to choose the correct one using setValue(...). As a workaround, I attempted to use 'selected', but unfortunately it did not yield the d ...

How can I use jQuery to trigger a left or right movement on a Waterwheel Carousel?

I'm a beginner in jquery and I'm looking to navigate my Waterwheel Carousel to the left or right using buttons. Let's say I have a button for moving to the right. How can I achieve this using the Waterwheel Carousel function? I've atte ...

Resetting the datetime picker in Eonasdan/bootstrap-datetimepicker using an external JavaScript function

When using Eonasdan/bootstrap-datetimepicker version : 4.17.47, I encountered a scenario where after selecting a date from the datetimepicker and then clearing it using an onclick function, the previously selected date remains highlighted when reopening th ...

Distinguishing between resolving a promise in a service/factory as opposed to in a controller within AngularJS

After experimenting with resolving a promise in both a service and a controller, I have found that I prefer to resolve it in the service so that I can reuse the variable without having to resolve it multiple times. However, I am encountering an issue where ...

Incorporating the unshift method in JavaScript: A Step-by-

I'm looking to create a new function with the following requirements: Function add(arr,...newVal){ } array = [1,2,3]; add(array,0) console.log(array); //I want this to output [0,1,2,3] I tried creating the function similar to push like this: ...

Ensuring that the second level unordered list is set to a height of 100% of the first unordered list, rather than the

I'm working with this menu http://codepen.io/alexandernst/pen/oxpGYQ (I wanted to include it here but the result viewer on SO is causing some display issues...) and I am trying to ensure that the second and third level ul elements are the same height ...

How can I navigate to a different page using Node.js and Express?

I am currently developing a chat application in Node.js with the use of socket.io. Whenever a new user logs into localhost:3000, they are presented with a form where they can input their name and the room they wish to join. How can I efficiently redirect t ...

The class "col-md-*" is not functioning properly when used with an Infragistics grid

I am working with a simple HTML table and an Infragistics (igx) grid to display data: <div class="container"> <div class="row"> <div class="col-md-4"> <table> </table> </div> < ...

encountering a problem with npm while trying to execute the project

Encountering a persistent issue when attempting to run my project with npm start, even after downgrading my node version. Despite trying various solutions found on platforms like stackoverflow and stackexchange, such as deleting the node_modules folder, ru ...