Issue with event.preventDefault() in Jquery not functioning as expected

My goal is to have the menu display and hide list items on click, with them being hidden by default. However, the issue I am facing is that the menu is generated in the admin section, so it automatically assigns a URL to each item. If I set the URL field of a specific link to null in the menu options, clicking on it reloads the home page.

What I would like is for when I click on any parent li, the default event generation should stop. I tried using preventDefault but it seems not to be working in my case as it still reloads the page after showing the list items of their parent.

Here's a fiddle: Fiddle

HTML:

<div class="mega-col col-xs-12 col-sm-12 col-md-4" data-type="menu">
    <div class="mega-col-inner">
        <ul>
            <li class="parent dropdown-submenu mega-group"><a class="dropdown-toggle" data-toggle="dropdown" href=""><span class="menu-title">Massachusetts Stores</span><b class="caret"></b></a>
                <div class="dropdown-mega level2">
                    <div class="dropdown-menu-inner">
                        <div class="row">
                            <div class="col-sm-12 mega-col" data-colwidth="12" data-type="menu">
                                <div class="mega-col-inner">
                                    <ul>
                                        <li class=" "><a href="index.php?route=common/location_details&amp;loc_id=24"><span class="menu-title">Burlington Mall, MA</span></a>
                                        </li>
                                        <li class=" "><a href="index.php?route=common/location_details&amp;loc_id=25"><span class="menu-title">Burlington Mall, MA - Cart</span></a>
                                        </li>
                                    </ul>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </li>
            ... (more HTML code here)
        </ul>
    </div>
</div>

JS:

$("#li_menu169 li.parent.dropdown-submenu.mega-group").click(function(event) {
    var id = $(this).prop('id');
    if (id == 'yes') {

        //I want to prevent
    } else {
        event.preventDefault();
        $(this).children('.dropdown-mega.level2').show();
        $(this).children('.dropdown-mega.level2').hide();
        //Redirect
    }
});

CSS:

li.parent.dropdown-submenu.mega-group .dropdown-mega.level2 {
    display: none;
}
li {
    padding: 10px;
    position: relative;
    margin: auto;
}

Answer №1

Check out a live demo here: http://example.com/demo

If you're wondering about the use of the id attribute, it's typically recommended to assign the onClick event to a link (<a> tag) rather than an li element. You can achieve this by implementing the following jQuery script:

$("li.tab.dropdown-option.submenu-item > a").on('click', function(event) {
    event.preventDefault();
    $('.dropdown-menu.level2').hide();
    $(this).closest('.tab').find('.dropdown-menu.level2').show();
});

Answer №2

Perhaps you are interested in implementing something along these lines:

$("#li_menu169 li.parent.dropdown-submenu.mega-group").click(function(event) {
    var id = $(this).prop('id');
    if (id == 'yes') {

        //I wish to block this action
    } else {

        $(this).children('.dropdown-mega.level2').show();
        $(this).children('.dropdown-mega.level2').hide();
        //Forwarding to new location
        window.location.href="desired_file_location_here";
    }
    event.preventDefault();

});

Answer №3

Grab the event once it is activated

$("#li_menu169 li.parent.dropdown-submenu.mega-group").click(function(event) {

    event.preventDefault();

}

Answer №4

I must confess that I made a mistake with your code.

Check out this JSBin link for reference.

To start off, you are missing a list with the id "#li_menu169". Make sure to add it to the ul element like this:

<div class="mega-col col-xs-12 col-sm-12 col-md-4" data-type="menu"><div class="mega-col-inner">
    <ul id="li_menu169">

Furthermore, there seems to be some confusion in how you are showing and hiding elements. My suggestion would be to first hide all inner elements and then show only the inner elements of "this" context.

 $("#li_menu169 li.parent.dropdown-submenu.mega-group").click(function(event) {
    var id = $(this).attr('id');

    if (id === 'yes' && typeof id !== undefined) {
        console.log("I'm there");
        //I want to prevent
    } else {
        console.log("I'm here");
        event.preventDefault();
        $('.dropdown-mega.level2').hide();
        $(this).find('.dropdown-mega.level2').show();
        //Redirect
    }
});

Everything should work as expected within the JSBin environment.

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 Router.use() function is looking for a middleware function, but instead received an undefined value at the

Currently, I am working on implementing authentication with node.js following a tutorial. However, I have encountered some issues that I am struggling to resolve. This is how I have configured the server: // Inserted code for configuring the server The ...

Creating an effective Google Login Button in a React application

Struggling to implement a Login/Sign In Google Button on my page using react, I'm new to this framework and it's just not working as expected. Following tutorials from the internet but still facing issues. To summarize, I'm utilizing tailw ...

Enigmatic void found beneath image surfacing

Similar Question: Dealing with Additional Space at the Bottom of an Anchor Tag Take a look at this example page here.. There seems to be a mysterious gap below the picture of the family, just before the gray-bordered (5px #333) div that holds the ima ...

What is the best way to design a Global Navigation menu for websites?

For example, I am looking to integrate a Navigation menu into my website using just one file. I have considered using PHP or creating an HTML frame, but I am wondering what the current industry standard is for professionals. Any insights? ...

The issue with dynamic sizing in React and Tailwind is that it does not consistently work with arbitrary sizes. Some sizes do not appear properly, causing items to

In this code snippet, I am attempting to create a circle component of dynamically sized using html div and Tailwind CSS w-[diameter] & h-[diameter] attributes in a create-next-app@latest project. However, the circle fails to render properly with certa ...

Optimizing HTML/CSS performance: Comparing flexbox and tables for handling extensive datasets

Creating a React table component with hundreds of lines and variable cell widths can be complex. Would it be better to implement this using flexbox or a traditional table structure in HTML/CSS? ...

Ways to automatically close the external window upon logging out in Angular 12

I have successfully created an external window in my Angular application. Everything is working as expected, but I am facing an issue when trying to automatically close the external window upon user logout. Although I have written the code below and it wo ...

Dynamic filtering of items using Knockout's foreach binding based on value change

I'm working on some HTML/Knockout code where I want to display a dayDivider div only when there is a new date. This means that messages from the same day should appear under a date banner. Typically, I would save the last value in a temporary variable ...

Color overlay on top of image background

I'm struggling to create a striped colored background with a narrow center single color background on top for showcasing articles and photos. However, I am unable to get the colored background to display correctly. Despite trying different approaches ...

Tips for waiting for a page to fully load before clicking the "load more" button using selenium

When using Selenium to load a page and attempting to click the "load more" button, encountering an issue after clicking it more than 100 times. An error of "element click intercepted" is being displayed, as the page takes longer to load after multiple cli ...

Tips for ensuring that the click event function properly for numerous elements sharing the same class

I'm currently working on adding a flip effect to multiple tiles whenever a user clicks on them as part of building a dashboard-style webpage. I am having trouble making the click event work for all tiles with the same class name. Even though all the ...

Encountering a "Method Not Allowed" error when attempting to process a Laravel Stripejs

Seeking to integrate stripe payment into my laravel app, The stripe payment form I utilized can be found at, The HTML code used is as follows: <div class="container"> <div class='row'> <div class='col-md-4' ...

Guide on aligning text beneath and to the side of an image, and positioning them in the same row using CSS Bootstrap 4

I am looking to organize two different texts alongside and under an image within a single article. I also want these two articles to be displayed in the same row when the window size is col-md or larger. https://i.sstatic.net/ZjigH.jpg The second article ...

Does the resolve function within a Promise executor support async operations?

I'm trying to wrap my head around the following code: function myPromiseFunc() { return new Promise((resolve) => { resolve(Promise.resolve(123)); }); } We all know that the Promise.resolve method immediately resolves a Promise with a plain ...

Event that occurs when modifying a user's Firebase Authentication details

Monitoring User Actions with Firebase Authentication Within my application built using Angular, Node.js, and Firebase, I am seeking a method to track user events such as additions, modifications, and deletions. Is there a mechanism to recognize when a us ...

Images overlapping within a dynamic container

I am currently working with a responsive container that contains one image. The container and image resize well when the window size changes. However, I now need multiple images to overlap each other (all of the same size). How can I achieve this using HTM ...

Converting an OpenRasta XML request to JSON for response

I have a simple application using OpenRasta framework with a Home resource containing a single string property called Title (taken from the OpenRasta community documentation example). I've configured both XML and JSON data contracts for this resource ...

Are there any resources available to ensure my jQuery script is compatible with multiple browsers?

After realizing that Internet Explorer does not support certain selectors in jQuery, I began to question how to ensure my code will function properly during the writing process. As a Linux user, my testing options are limited to Chrome and Firefox. Is ther ...

The min-height property in Bootstrap 3 causes a div element to not expand as expected

Having a bootstrap 3 page with a centered box that contains content, I noticed that the box does not expand when the content grows. The bootstrap container grows, but the box remains static. I have tried using "position:relative" and "overflow:hidden", as ...

The Eonasdan DateTimePicker plugin for Bootstrap v4 (Tempus Dominus) is experiencing technical difficulties

When it comes to my Javascript file, I am including and using it as shown below: import 'moment'; import 'tempusdominus-bootstrap-4'; export default class AddHolidayPane { static Initialise() { $('#start-date').d ...