Click on the submenu to expand it, then simply select the desired option to navigate

I have created a toggle menu that displays a list of child elements when clicked, and hides them if clicked again.

However, when a child element is clicked, I want it to navigate to the corresponding page. I am having trouble getting this functionality to work. Could it be related to my use of preventDefault?

//  Language select in global nav
$('.sub-lang').on('click', function(e) {

if ($(this).hasClass('active') && $(e.target).parent().hasClass('active')) {
    $(this).removeClass('active');
    $(this).css('height', 'auto');
    $(this).children('ul').hide();
} else {
    $(this).addClass('active');
    $(this).css('height', $(this).find('ul').height() + 65);
    $(this).children('ul').show();
}

e.preventDefault();
});

You can view the code on JsFiddle.

Answer №1

Why not simply convert your main menu element into a paragraph tag? Alternatively, you could insert a # inside your main menu element and remove the prevent default function. This way, you won't have to worry about preventing default on your main elements.

Even though google.com doesn't load within an iFrame, you can test it out with this fiddle. It actually works!

Take a look at this (with # in the anchors) fiddle

HTML

<ul style=" ">
  <li class="sub-lang">
    <a href="#">English</a>
    <ul style="">
      <li><a href="http://www.google.com">International</a></li>
      <li><a href="">UK &amp; Ireland</a></li>
    </ul>
  </li>
  <li class="sub-lang">
    <a href="#">Espanol</a>
    <ul style="">
      <li><a href="/es-es/">Español</a></li>
      <li><a href="http://www.google.com">España</a></li>
    </ul>
  </li>
  <li class="sub-lang">
    <a href="#">Francais</a>
    <ul style="">
      <li><a href="/fr-fr/">Français</a></li>
      <li><a href="http://www.google.com">France</a></li>
    </ul>
  </li>
</ul>

Answer №2

Include the following line at the beginning of your code

$('.sub-lang > a').removeAttr('href');

Delete

e.preventDefault();

These changes should resolve the issue

Answer №3

Make sure to include an additional condition for that scenario.

if($(e.target).parent().hasClass('sub-lang') )

This will enable you to easily interact with the submenu.

// Customizing language selection in global navigation
$('.sub-lang').on('click', function(e) {
  
 if($(e.target).parent().hasClass('sub-lang') ){
 
    if ($(this).hasClass('active') && $(e.target).parent().hasClass('active')) {
      $(this).removeClass('active');
      $(this).css('height', 'auto');
      $(this).children('ul').hide();
    } else {
      $(this).addClass('active');
      $(this).css('height', $(this).find('ul').height() + 65);
      $(this).children('ul').show();
    }
    e.preventDefault();
  }
});
ul li ul {
    display: none;
    z-index: 2;
    right: 0;
    background-color: #fff;
    width: 250px;
}
ul li.active ul {
    display: block;
    text-align:left;
    background: #f1f1f1;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul style=" ">
  <li class="sub-lang">
    <a href="">English</a>
    <ul style="">

      <li><a href="http://www.google.com" traget="_blank">International</a></li>

      <li><a href="">UK &amp; Ireland</a></li>

    </ul>
  </li>

 
  <li class="sub-lang">
    <a href="/es-es/">Español</a>
    <ul style="">

      <li><a href="http://www.google.com">España</a></li>

    </ul>
  </li>

  <li class="sub-lang">
    <a href="/fr-fr/">Français</a>
    <ul style="">

      <li><a href="http://www.google.com">France</a></li>

    </ul>
  </li>

</ul>

Check out the Working Fiddle here

Trust this information is beneficial.

Answer №4

Take a look at this example.

Explanation:

Instead of attaching the event to the entire li element, I attached it specifically to all immediate child <a> elements within the li. This way, we can prevent event propagation for that particular element without needing to worry about stopping the event from reaching the children elements.

If the JSFiddle is having trouble loading external iframe, you can view the solution here.

Answer №5

In my opinion, incorporating stopPropagation into your inner list items is necessary.

$('.sub-lang ul li').on('click', function(e) {
  e.stopPropagation();
});

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

Using BeautifulSoup4 in Python to extract text data from a nested tag within an h1 element

Seeking assistance in extracting the text content within an anchor tag that is nested inside a heading tag. <h1 class="branded-page-header-title"> <span class="qualified-channel-title ellipsized"><span class="qualified-channel-title-w ...

Boost the scrolling velocity of my sidebar using Jquery

Hello there, I am completely new to the world of web development and particularly to using JavaScript and jQuery. I am interested in learning how to adjust the speed at which my Sidebar scrolls down as the user navigates through the page. Here is the jQue ...

Is applying a bevel effect when hovering achievable?

Is there a way to add a bevel effect to my hyperlink image so it stays in place without moving down? I need the bevel effect to be inside the image as it keeps shifting position. Any suggestions would be greatly appreciated. I really need the bevel effect ...

Unable to retrieve jwt token from cookies

Currently, I am developing a website using the MERN stack and implementing JWT for authentication. My goal is to store JWT tokens in cookies. Despite invoking the res.cookie function with specified parameters (refer to the code below), I am facing difficul ...

The debounced function in a React component not triggering as expected

I am facing an issue with the following React component. Even though the raiseCriteriaChange method is being called, it seems that the line this.props.onCriteriaChange(this.state.criteria) is never reached. Do you have any insights into why this.props.onC ...

Retrieving ng-repeat $index with filtering in AngularJS controller

I am facing a challenge with my ng-repeat list and filter in AngularJS. I am unable to retrieve the visible $index value from inside my controller. Although I can display the index easily and see it change dynamically when the list is filtered, I am strug ...

Guide to adding a theme switcher feature to your current React website

Currently, I am faced with a challenge involving two theme files, theme.js and theme-dark.js, within the context of a complex React-based website. Despite having already set up the site, I am struggling to find a way to allow users to seamlessly switch bet ...

Verify if the form has been refreshed in React JS

In my React application, I have a form inside a modal pop-up. When the user closes the pop-up, I want to check for any changes made in the form fields. If there are changes, I will display a confirmation modal; if not, I will simply close the pop-up. <F ...

Amcharts displays individual balloons for each graph instead of a single balloon for all graphs

My goal is to have a single balloon for all stacked graphs. I modified my code according to this guide. Unfortunately, the data for messages is not being displayed. Did I make an error in my implementation? function createChart(chartDiv, title) { ret ...

Problem with the menu button overflowing

I'm exploring the process of designing burger menus for the mobile version of my site. I've successfully created a basic burger menu with some JavaScript assistance, but I encountered an overflow issue. The burger menu functions properly, but the ...

Guide on transforming a text element into an input field when clicked using AngularJS

I'm curious about how to achieve this functionality using AngularJS. Specifically, I'd like to display a list of keywords with an edit button next to each one. <tr ng-repeat="keyword in keywords"> <td> <st ...

Learn how to dynamically activate an icon in Angular to enhance user interaction

HTML Code: The Zoom Component <div class="zoom py-3"> <i nz-icon nzType="minus" (click)="zoomToggle(false)" nzTheme="outline"></i><br> <i nz-icon nzType="plus" (click)=&q ...

Oops! The Route.get() function in Node.js is throwing an error because it's expecting a callback function, but it received

Currently, I am learning how to create a web music admin panel where users can upload MP3 files. However, I have encountered the following errors: Error: Route.get() requires a callback function but received an [object Undefined] at Route. [as get] (C:&bso ...

Determine if the same origin policy is in effect

Is there a method to determine if the same origin policy is applicable to a URL before attempting to use ajax methods? Below is an example of what I currently have: function testSameOrigin(url) { var loc = window.location, a = document.create ...

What is the best approach to dealing with a non-TypeScript project that is requesting the installation of @types for

With the project set up using create-react-app and custom-react-scripts to utilize decorators for MobX, I am aiming to incorporate the react-c3js library for data visualization. Surprisingly, everything is functioning correctly, but there's a warning ...

Guide on attaching an onclick function to a search bar

I found a search bar code on this website and I want to enhance it by adding a function that redirects users to a URL when they click on the search icon. Here is the existing code: <svg xmlns="http://www.w3.org/2000/svg" style="display:none"> ...

Sliding in the wrong direction on Bootstrap 5.2 carousel

I'm currently working on a carousel project. However, I encountered an issue where the images slide down initially and then jump up to the correct level as depicted in the image below. I've tried adjusting the height, width, and auto settings to ...

Is it necessary to define module.exports when using require() to import a file?

While setting up my Express server, I am using Babel to transpile my ES6 files seamlessly. In my vanilla JS server.js file, I include require('babel-core/register') and require('./app'). Within my ES6 file app.js, I handle all the usua ...

Using JavaScript and jQuery to compare two JSON objects, then storing the result in a separate object

I am currently working on an API call that provides an updated JSON object, as well as a static JSON object file. My goal is to compare a specific value in the objects for teams with the same name. For example, if Team John had 22 members in the old file ...

Tips for refreshing a DOM element after inserting with jQuery

I'm trying to update the LI element after using the insertBefore function in jQuery. The issue arises after adding new elements to UL where I encounter difficulty deleting the same element (using emailTagRemove). Check out the demo to see the proble ...