Change the dropdown header behavior from hovering over it to clicking on it

This snippet of code is integrated into our header to showcase the cart. Currently, the dropdown appears when hovering over it.

Is there a way to adjust this so that the dropdown shows up when onclick?

<a href="#header-cart" class="skip-link skip-cart <?php if($_cartQty <= 0): ?> no-count<?php endif; ?>">
    <span class="icon"></span>
    <span class="label"><?php echo $this->__('Cart'); ?></span>
    <span class="count"><?php echo $_cartQty; ?></span>
</a>

<div id="header-cart" class="block block-cart skip-content">
    <?php echo $this->getChildHtml('minicart_content');?>
</div>

The following code controls the dropdown functionality on the website:

    <?php //Drop-down ?>
    var ddOpenTimeout;
    var dMenuPosTimeout;
    var DD_DELAY_IN = 200;
    var DD_DELAY_OUT = 0;
    var DD_ANIMATION_IN = 0;
    var DD_ANIMATION_OUT = 0;

    $('.clickable-dropdown > .dropdown-heading').click(function() {
        $(this).parent().addClass('open');
        $(this).parent().trigger('mouseenter');
    });

    //$('.dropdown-heading').on('click', function(e) {
    $(document).on('click', '.dropdown-heading', function(e) {
        e.preventDefault();
    });

    $(document).on('mouseenter', '.dropdown', function() {

        var ddToggle = $(this).children('.dropdown-heading');
        var ddMenu = $(this).children('.dropdown-content');
        var ddWrapper = ddMenu.parent(); <?php //$(this); ?>

        <?php //Clear old position of dd menu ?>
        ddMenu.css("left", "");
        ddMenu.css("right", "");

        <?php //Show dd menu ?>
        if ($(this).hasClass('clickable-dropdown'))
        {
            <?php //If dropdown is opened (parent already has class 'open') ?>
            if ($(this).hasClass('open'))
            {
                $(this).children('.dropdown-content').stop(true, true).delay(DD_DELAY_IN).fadeIn(DD_ANIMATION_IN, "easeOutCubic");
            }
        }
        else
        {
            <?php //Add class 'open' to dd ?>
            clearTimeout(ddOpenTimeout);
            ddOpenTimeout = setTimeout(function() {

                ddWrapper.addClass('open');

            }, DD_DELAY_IN);

            //$(this).addClass('open');
            $(this).children('.dropdown-content').stop(true, true).delay(DD_DELAY_IN).fadeIn(DD_ANIMATION_IN, "easeOutCubic");
        }

        <?php //Set new position of dd menu.
              //This code is delayed the same amount of time as drop-down animation. ?>
        clearTimeout(dMenuPosTimeout);
        dMenuPosTimeout = setTimeout(function() {

            if (ddMenu.offset().left < 0)
            {
                var space = ddWrapper.offset().left; <?php //Space available on the left of dd ?>
                ddMenu.css("left", (-1)*space);
                ddMenu.css("right", "auto");
            }

        }, DD_DELAY_IN);

    }).on('mouseleave', '.dropdown', function() {

        var ddMenu = $(this).children('.dropdown-content');
        clearTimeout(ddOpenTimeout); <?php //Clear, to close dd on mouseleave ?>
        ddMenu.stop(true, true).delay(DD_DELAY_OUT).fadeOut(DD_ANIMATION_OUT, "easeInCubic");
        if (ddMenu.is(":hidden"))
        {
            ddMenu.hide();
        }
        $(this).removeClass('open');
    });

Answer №1

Make sure to change the event from 'mouseenter' to 'click', as using 'click' will save you from unnecessary brain strain. However, it seems like your problem description is not fully clear. To receive a comprehensive solution for your desired outcome, please provide more details about the issue and share the complete HTML code. Utilize Fiddler to upload the HTML and scripts, then share the link for further assistance.

Answer №2

modify this line

$(document).on('mouseenter', '.dropdown', function() {

to

$(document).on('click', '.dropdown', function() {

it is advisable to eliminate the on('mouseleave') function entirely and incorporate it into your click logic

UPDATE below is a comprehensive solution in one JS (and please refrain from using a <?php tag for commenting)

    var ddOpenTimeout;
    var dMenuPosTimeout;
    var DD_DELAY_IN = 200;
    var DD_DELAY_OUT = 0;
    var DD_ANIMATION_IN = 0;
    var DD_ANIMATION_OUT = 0;

    $('.clickable-dropdown > .dropdown-heading').click(function() {
        $(this).parent().addClass('open');
        $(this).parent().trigger('mouseenter');
    });

    //$('.dropdown-heading').on('click', function(e) {
    $(document).on('click', '.dropdown-heading', function(e) {
        e.preventDefault();
    });

    $(document).on('click', '.dropdown', function() {
        if($(this).hasClass('open')) {

            var ddMenu = $(this).children('.dropdown-content');
            clearTimeout(ddOpenTimeout); <?php //Clear, to close dd on mouseleave ?>
            ddMenu.stop(true, true).delay(DD_DELAY_OUT).fadeOut(DD_ANIMATION_OUT, "easeInCubic");
            if (ddMenu.is(":hidden"))
            {
                ddMenu.hide();
            }
            $(this).removeClass('open');
        } else {
            var ddToggle = $(this).children('.dropdown-heading');
            var ddMenu = $(this).children('.dropdown-content');
            var ddWrapper = ddMenu.parent();


            ddMenu.css("left", "");
            ddMenu.css("right", "");

            if ($(this).hasClass('clickable-dropdown'))
            {
                if ($(this).hasClass('open'))
                {
                    $(this).children('.dropdown-content').stop(true, true).delay(DD_DELAY_IN).fadeIn(DD_ANIMATION_IN, "easeOutCubic");
                }
            }
            else
            {
                clearTimeout(ddOpenTimeout);
                ddOpenTimeout = setTimeout(function() {

                    ddWrapper.addClass('open');

                }, DD_DELAY_IN);

                //$(this).addClass('open');
                $(this).children('.dropdown-content').stop(true, true).delay(DD_DELAY_IN).fadeIn(DD_ANIMATION_IN, "easeOutCubic");
            }
            clearTimeout(dMenuPosTimeout);
            dMenuPosTimeout = setTimeout(function() {

                if (ddMenu.offset().left < 0)
                {
                    var space = ddWrapper.offset().left; <?php //Space available on the left of dd ?>
                    ddMenu.css("left", (-1)*space);
                    ddMenu.css("right", "auto");
                }

            }, DD_DELAY_IN);
        }
    });

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

Various HTML tables display varying column widths even when utilizing the same colgroup settings

I'm facing an issue with multiple HTML tables on a single page, each following this structure: H2 Header Table H2 Header Table H2 Header Table My requirement is to have all tables occupy 100% width, with columns set at widths of 50%, 30%, and 20%. I ...

Trouble arises when incorporating a new feature onto a map with OpenLayers and Vue.js

I'm currently working on integrating a custom control into my map using OpenLayers with Vue.js. The Explore.vue component is responsible for creating the "map" (olmap) with OL, and I bind it to the child component LeftSideBar2.vue. However, when att ...

Retrieve information from a JavaScript file to incorporate into an HTML file

Seeking a solution to store the base URL in a separate JavaScript file, I've implemented a JavaScript file named config.js containing: export const baseUrl = "https://example.com/"; There are multiple HTML files utilizing this base URL for ...

Is there a way to automatically retrieve CSV data using ashx on a web page?

After researching the provided links from SO without success, I decided to reach out here for help. (For privacy reasons, the actual URL and header data have been obscured) I am struggling to automate downloading data from an HTTPS web page using Delphi ...

"Learn how to use jQuery to retrieve a specific row from an HTML table based on equality with a certain

I have a dynamically generated table using PHP. The information in this table is related to different semesters (such as first, second, third, etc.). I want to display specific semester information when a user clicks a link from the same table without need ...

Preventing a user from navigating away from a page without completing a specific action, such as clicking a submit button

I am in the process of developing an interactive quiz platform. The quiz includes a timer that begins counting down once the user initiates the quiz. Upon completing the quiz, the user is expected to submit their answers. If the user runs out of time, th ...

the angular-ui-tinymce directive allows for seamless image uploads using a file browser

Utilizing jQuery, we have the ability to incorporate local images into the tinymce editor similar to what is demonstrated in this jsfiddle, by following the guidelines provided in the documentation. The Angular module for tinymce can be found at angular-u ...

Tips for incorporating a live URL using Fetch

I'm having some trouble with this code. Taking out the &type = {t} makes it work fine, but adding it causes the fetch to not return any array. let n = 12 let c = 20 let t = 'multiple' let d = 'hard' fetch(`https://opentdb.com/ ...

PyQt TreeView scrollbar obstructing the header

I've been experimenting with the QTreeView widget (instead of QListView) in order to have a horizontal header. Additionally, I wanted to use stylesheets to customize the colors and appearance of the header and scrollbars. However, there is an issue w ...

Troubleshooting incorrect data display in AngularJS using ng-repeat

Being a newbie in the world of JavaScript, AngularJS, and Parse, I am eager to learn. If there are any mistakes in my approach, please do point them out as I aim to gain as much knowledge as possible. I have been given an assignment that requires me to ut ...

Using Node.js, Express, and Socket.IO to establish real-time communication between two static client pages

I'm in the process of creating a remote control for a gallery using nodejs, express, and socket.io. Here's the project structure: /index.js /public/screen.html /screen.js /remote.html /remote.js The goal is to display a gallery of ima ...

The redirection to the HTML page happens too soon, causing the ASYNC functions to fail in saving the user's image and data to the server

Hey everyone! I'm facing an issue with async/await functions. Here's the code snippet from my backend where I'm trying to save details of a newly registered user. I'm puzzled as to why the Redirect() function is executing before the f ...

Unable to make getJSON function properly with CodeIgniter

I'm experimenting with using getJSON to retrieve the most recent data from my database. So far, I've stored it in an array and used json_encode(the array). This method successfully displays the information on the view, but the problem lies in the ...

Including hyperlink tags within a CSS file

Can you create internal links within a CSS file, like inserting a table of contents at the top where you can click on an item and immediately jump to that section in the CSS file similar to an anchor tag? This feature would be extremely handy for long CSS ...

What is the most effective approach for preventing the inadvertent override of other bound functions on window.onresize?

As I delve deeper into JavaScript, I constantly find myself pondering various aspects of it. Take for instance the window.onresize event handler. If I were to use the following code: window.onresize = resize; function resize() { console.log("resize eve ...

What is the best way to retrieve the data submitted in the Input field by using Ajax?

One feature I'm working on involves an input field within a form where users can update their name by clicking a button. The goal is to capture this change in the input field using Ajax and update it accordingly. Here's the HTML code snippet: & ...

Is it possible to use an Ajax callback function to add a select dropdown HTML to a table

I am currently in the process of using jQuery to append some HTML with the code provided below. My main objective is to select an option based on AJAX response data and create a select dropdown menu. However, the variable scope of sOut doesn't seem to ...

The dropdown menu with Bootstrap's <li> sub menu is not expanding as expected

<li class="dropdown"> <a href="#" class="dropdown-toggle" data-bs-toggle="dropdown" role="button" aria-expanded="false">Utilitas<span class="c ...

Checking and contrasting dates within Javascript

Looking to compare two dates with different formats: a) Date1 - 01 Feb 2019 b) Date2 - 2/3/2017 It's important to account for invalid dates and ensure that Date1 is greater than Date2. function CompareAndValidateDates() { var Date1 ="01 Feb 20 ...

Issue with jQuery Mobile causing Bookmark Links to malfunction

I am facing issues with Jquery-Mobile interfering with my internal links on the same page. Despite attempts to disable ajax calls for hyperlinks within the site, bookmarked links are still not functioning correctly. After thorough research on the jquery m ...