Having trouble finding a solution to prevent code from automatically adding a class in jQuery/JavaScript?

I am currently in the process of customizing the FlexNav Plugin. I have made a modification to allow sub-menus to open on click instead of hover.

However, a new issue has arisen where it requires two clicks to open a submenu.

Upon investigation, I have identified that the problem lies in the code adding the "flexnav-show" class to the submenu ul when the menu is initially opened. Subsequent clicks then toggle this class, requiring an extra click to open the submenu.

If anyone can guide me on how to modify the code to prevent adding the class on all ul elements, or if there are alternative solutions...

$.fn.flexNav = function(options) {
var $nav, $top_nav_items, breakpoint, count, nav_percent, nav_width, resetMenu, resizer, settings, showMenu, toggle_selector, touch_selector;
settings = $.extend({
  'animationSpeed': 250,
  'transitionOpacity': true,
  'buttonSelector': '.menu-button',
  'hoverIntent': false,
  'hoverIntentTimeout': 150,
  'calcItemWidths': false,
  'hover': false
}, options);
$nav = $(this);
$nav.addClass('with-js');
if (settings.transitionOpacity === true) {
  $nav.addClass('opacity');
}
$nav.find("li").each(function() {
  if ($(this).has("ul").length) {
    return $(this).addClass("item-with-ul").find("ul").hide();
  }
});
if (settings.calcItemWidths === true) {
  $top_nav_items = $nav.find('>li');
  count = $top_nav_items.length;
  nav_width = 100 / count;
  nav_percent = nav_width + "%";
}
if ($nav.data('breakpoint')) {
  breakpoint = $nav.data('breakpoint');
}
showMenu = function() {
  if ($nav.hasClass('lg-screen') === true && settings.hover === true) {
    if (settings.transitionOpacity === true) {
      return $(this).find('>ul').addClass('flexnav-show').stop(true, true).animate({
        height: ["toggle", "swing"],
        opacity: "toggle"
      }, settings.animationSpeed);
    } else {
      return $(this).find('>ul').addClass('flexnav-show').stop(true, true).animate({
        height: ["toggle", "swing"]
      }, settings.animationSpeed);
    }
  }
};
resetMenu = function() {
  if ($nav.hasClass('lg-screen') === true && $(this).find('>ul').hasClass('flexnav-show') === true && settings.hover === true) {
    if (settings.transitionOpacity === true) {
      return $(this).find('>ul').removeClass('flexnav-show').stop(true, true).animate({
        height: ["toggle", "swing"],
        opacity: "toggle"
      }, settings.animationSpeed);
    } else {
      return $(this).find('>ul').removeClass('flexnav-show').stop(true, true).animate({
        height: ["toggle", "swing"]
      }, settings.animationSpeed);
    }
  }
};
resizer = function() {
  var selector;
  if ($(window).width() <= breakpoint) {
    $nav.removeClass("lg-screen").addClass("sm-screen");
    if (settings.calcItemWidths === true) {
      $top_nav_items.css('width', '100%');
    }
    selector = settings['buttonSelector'] + ', ' + settings['buttonSelector'] + ' .touch-button';
    $(selector).removeClass('active');
    return $('.one-page li a').on('click', function() {
      return $nav.removeClass('flexnav-show');
    });
  } else if ($(window).width() > breakpoint) {
    $nav.removeClass("sm-screen").addClass("lg-screen");
    if (settings.calcItemWidths === true) {
      $top_nav_items.css('width', nav_percent);
    }
    $nav.removeClass('flexnav-show').find('.item-with-ul').on();
    $('.item-with-ul').find('ul').removeClass('flexnav-show');
    resetMenu();
    if (settings.hoverIntent === true) {
      return $('.item-with-ul').hoverIntent({
        over: showMenu,
        out: resetMenu,
        timeout: settings.hoverIntentTimeout
      });
    } else if (settings.hoverIntent === false) {
      return $('.item-with-ul').on('mouseenter', showMenu).on('mouseleave', resetMenu);
    }
  }
};
$(settings['buttonSelector']).data('navEl', $nav);
touch_selector = '.item-with-ul, ' + settings['buttonSelector'];
$(touch_selector).append('<span class="touch-button"><i class="navicon">&#9660;</i></span>');
toggle_selector = settings['buttonSelector'] + ', ' + settings['buttonSelector'] + ' .touch-button';
$(toggle_selector).on('click', function(e) {
  var $btnParent, $thisNav, bs;
  $(toggle_selector).toggleClass('active');
  e.preventDefault();
  e.stopPropagation();
  bs = settings['buttonSelector'];
  $btnParent = $(this).is(bs) ? $(this) : $(this).parent(bs);
  $thisNav = $btnParent.data('navEl');
  return $thisNav.toggleClass('flexnav-show');
});
$('.touch-button').on('click', function(e) {
  var $sub, $touchButton;
  $sub = $(this).parent('.item-with-ul').find('>ul');
  $touchButton = $(this).parent('.item-with-ul').find('>span.touch-button');
  if ($nav.hasClass('lg-screen') === true) {
    $(this).parent('.item-with-ul').siblings().find('ul.flexnav-show').removeClass('flexnav-show').hide();
  }
  if ($sub.hasClass('flexnav-show') === true) {
    $sub.removeClass('flexnav-show').slideUp(settings.animationSpeed);
    return $touchButton.removeClass('active');
  } else if ($sub.hasClass('flexnav-show') === false) {
    $sub.addClass('flexnav-show').slideDown(settings.animationSpeed);
    return $touchButton.addClass('active');
  }
});
$nav.find('.item-with-ul *').focus(function() {
  $(this).parent('.item-with-ul').parent().find(".open").not(this).removeClass("open").hide();
  return $(this).parent('.item-with-ul').find('>ul').addClass("open").show();
});
resizer();
return $(window).on('resize', resizer);

};

Answer №1

Within line 34 of the code, the class 'flexnav-show' is appended to every descendant 'ul' element.

The functionality triggers when the showMenu function is invoked.

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

Encountering an error of "undefined is not iterable, cannot read property Symbol(Symbol.iterator)"

While learning React through coding, I encountered an error (Uncaught TypeError: undefined is not iterable (cannot read property Symbol(Symbol.iterator)). I am unsure where the problem lies. Any suggestions? When utilizing useEffect to activate setFiltere ...

An autocomplete CSS editor with Firebug-like features

Looking for a CSS (or HTML) editor that offers code autocompletion similar to Firebug's features. I believe it's referred to as "autocomplete as you type." Thank you! Edit: I came across a tool called Zen Coding that provides shortcuts for cod ...

The data retrieved by jQuery AJAX is empty when accessed outside of the success handler

Here is a code snippet to consider: let source = null; fetch('https://example.com/data') .then(response => response.json()) .then(data => { source = data; console.log(source); }); console.log(source) When the fetch request ...

Position of fixed div set relative to its parent fixed div

I'm facing an unusual situation where I need a fixed div to be positioned relative to its parent, which is also a fixed div. When you take a look at my example, everything will become clear. <div class="drawer"> <p>Drawer</p> & ...

Encountering an error: "Unable to assign the 'id' property to an undefined object while attempting to retrieve it"

I'm running into an issue while attempting to retrieve a specific user from Firebase's Firestore. export class TaskService { tasksCollection: AngularFirestoreCollection<Task>; taskDoc: AngularFirestoreDocument<Task>; tasks: Obs ...

Is there a way to include an instance variable as a CSS rule in Rails?

Assume I have the following ActiveRecord class: ......... store :skin_properties, accessors: [ :background_color, :font_size, :font_family, :color ] ......... This class saves values in the format shown below: {"background_color"=> ...

Continue scanning the expanding page until you reach the end

One of the challenges I am facing is that on my page, when I manually scroll it grows and then allows me to continue scrolling until I reach the bottom. This behavior is similar to a Facebook timeline page. In an attempt to address this issue, I have writ ...

When using jqueryprint.js to print from Firefox browser, an additional blank page appears before the content

Seeking assistance in printing a section of an HTML page using PHP with a large header space for empty space after printing. Despite multiple attempts, achieving the desired result in Chrome, but facing issues with Firefox, which adds an additional page be ...

Having difficulty with closing an HTML dialog using Selenium Webdriver in Java

Here is a snippet of my HTML code where I am attempting to use Selenium WebDriver to close a dialog box. <div class="ui-dialog dialog "> <div class="od-ui-dialog-content dialog_content"> <div class="od-ui-dialog-box ui_dialog_bo ...

How can you use JavaScript to create hyperlinks for every occurrence of $WORD in a text without altering the original content?

I've hit a bit of a roadblock. I'm currently working with StockTwits data and their API requires linking 'cashtags' (similar to hashtags but using $ instead of #). The input data I have is This is my amazing message with a stock $sym ...

Why isn't P5.JS's .display() working like it should?

I'm having trouble figuring out the scope of this code. I moved the function around, but I keep getting a "not a function" error. let bubbles = []; function setup() { createCanvas(400, 400); for (let i = 0; i < 10; i++){ bubbles[i] = new Bubbl ...

Unable to apply the flex-grow property to a column flex box that has a specified minimum height

I am currently working on designing a website layout that harnesses the power of flexbox to fill the entire page with content, even when the content does not fully occupy the length of the page. My approach involves creating a large flexbox container with ...

Exploring Tabletop.js to retrieve information from an array of data

Issue I am currently attempting to retrieve data from an array that contains two objects. I have implemented Tabletop.js to fetch the data from a public Google Spreadsheet, but I encountered an error in the console stating ReferenceError: object is not de ...

Encountered an error when attempting to load resource: net::ERR_CERT_AUTHORITY_INVALID following deployment on Vercel

I recently deployed a chatUI-app on Vercel that fetches chats from an API located at "http://3.111.128.67/assignment/chat?page=0" While the app worked perfectly in development, I encountered an issue after deploying it on Vercel where it ...

Is it possible to execute functions depending on a list of <li> elements that have been added?

To maintain a neat post, I have minimized everything. My goal is to append items to the dom after removing the last <li> element from the page, added via jQuery. I am using an .each function that utilizes a JSON array to populate an unordered list t ...

SailsJS failing to detect changes in local JSON file

https://i.stack.imgur.com/RG13Y.png This sailsjs application does not utilize any database. Instead, it relies on multiple JSON files located in the data folder within the root directory. The controller accesses this data as follows: req.session.categori ...

Leverage the Power of JSON Data Manipulation in WordPress with Angular JS and the WordPress JSON

After testing code in this particular post and making some adjustments, I encountered an issue with obtaining a JSON object from the API of my blog created using the WordPress JSON plugin. URL of API from BLOG (NOT FUNCTIONING): URL from W3C example (WO ...

Exploring the process of dynamically updating a form based on user-selected options

I need assistance with loading an array of saved templates to be used as options in an ion-select. When an option is chosen, the form should automatically update based on the selected template. Below is the structure of my templates: export interface ...

unable to clear form fields after ajax submission issue persisting

After submitting via ajax, I am having trouble clearing form fields. Any help in checking my code and providing suggestions would be greatly appreciated. Here is the code snippet: jQuery(document).on('click', '.um-message-send:not(.disabled ...

Swapping out a subarray within an array containing objects with a fresh array consisting of objects

Here is the structure of my data document: { "_id": "6287a6c5975a25cc25e095b0", "userName": "Robot", "projectName": "TestProject", "projectTypeName": "fixed project", "pro ...