Guide on inserting a dropdown menu following a specific count of <li> elements using Javascript or Jquery

I am currently working on an HTML project

<div class="ktmsg">
  <ul>
    <li class="a1">
        <a title="Link Tools" href="#"> … </a>
    </li>
    <li class="a2">
        <a title="Link Tools" href="#"> … </a>
    </li>
    <li class="a3">
        <a title="Link Tools" href="#"> … </a>
    </li>
  </ul>
</div>

My goal is to insert a sub-menu after the second </li>. The sub-menu will contain a link "<a href="#">More</a>" and display the third list item when hovered over. The desired final output should appear as follows:

<div class="ktmsg">
  <ul>
    <li class="a1">
        <a title="Link Tools" href="#"> … </a>
    </li>
    <li class="a2">
        <a title="Link Tools" href="#"> … </a>
    </li>
    <ul> //Starting the sub-menu
    <a href="#">More</a> // The link that after i hover it will start showing the <li> starting from the third one
      <li class="a3">
        <a title="Link Tools" href="#"> … </a>
      </li>
    </ul>
  </ul>
</div>

I have tried writing some javascript code but I seem to be stuck. Any help or guidance would be greatly appreciated.

Answer №1

Utilizing jQuery

jQuery(function ($) {
    var $items = $('.ktmsg > ul > li');
    var $link = $('<li><a href="#">More</a></li>').insertAfter($items.eq(1));
    var $hiddenItems = $items.slice(2).hide();

    $link.hover(function () {
        clearTimeout($link.data('hoverTimer'));
        $hiddenItems.show();
    }, function () {
        var timer = setTimeout(function () {
            $hiddenItems.hide();
        }, 200);
        $link.data('hoverTimer', timer);
    });

    $hiddenItems.hover(function () {
        clearTimeout($link.data('hoverTimer'));
    }, function () {
        var timer = setTimeout(function () {
            $hiddenItems.hide();
        }, 200);
        $link.data('hoverTimer', timer);
    });
})

Demo: Fiddle

Answer №2

Utilizing jQuery for this purpose:

<ul><a href="#">More</a></ul>

To insert the above code after the second list item, use the following jQuery script:

$( 'li:eq(1)' ).after( '<ul><a href="#">More</a></ul>' );

Answer №3

Check out this demonstration I put together using jQuery. It's a straightforward approach - simply use CSS to hide the sub menu initially, then employ jQuery to toggle its visibility when "More" is hovered over. I opted for fadeIn() and fadeOut(), but you can easily swap them out with hide() and show() if you prefer. I made some minor adjustments to your HTML structure, so be sure to use my updated version if you implement this solution.

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

Error 400 occurs when attempting to make a PUT request on Firefox or IE, whereas it functions properly on Chrome and Opera

One particular website is utilizing jQuery to call a WCF Webservice on a different domain by making use of CORS. While most of the methods are GET requests, there are a couple of PUT requests as well. All the GET methods function properly across all brows ...

The variable referencing an unidentified function has not been defined

I've created an anonymous function assigned to a variable in order to reduce the use of global variables. This function contains nested functions for preloading and resizing images, as well as navigation (next and previous). However, when I try to run ...

Presenting a ui-router modal while maintaining the parent state's refresh-free appearance

I have implemented a unique feature in my angular app called modalStateProvider. It allows me to easily have modals with their own URLs. // Implementing the modalStateProvider app.provider('modalState', [ '$stateProvider', function ...

How to Use Jquery to Retrieve the Selected Option Value and Append a Parameter

I am attempting to expand the value by adding "&fullpage=true" <select name="navMenu" onchange="go(this.options[this.selectedIndex].value)"> <option value="-">Choose</option> <option value="page.html&amp;nyo=0" class="ccbnLnk" ...

Creating a character jump animation on an HTML5 canvas

While following a tutorial on creating character animations, I encountered an issue. The tutorial, located at , made it easy to make the character move left (the right movement was already implemented). However, I am struggling with how to animate the char ...

What is the best way to extract the last JSON object from a JSONArray based on a specified value

I am currently working with a JSONArray that looks like the following: [ { "id": 1, "firstName": "abc", "isActive": true }, { "id": 2, "firstName": "cde", "isActive": false }, { " ...

Generated a hierarchical JSON structure from a dynamically generated form

My client has a unique page builder that allows them to create web forms using a convenient drag and drop interface. Currently, the data is output in a JSON format like this: { "email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" dat ...

The module you are trying to access at './server/controller/controller.js' does not contain an export with the name 'default'

I'm fairly new to backend development and I've recently started using ES6 modules in my project. However, when I try to import the controller file into index.js and run the project, I encounter the following error: Syntax Error: The requested mo ...

Implementing basic functionality with React Router

I am currently working on implementing React router and I have a main class named App where I need to call ExpenseApp. In order for ExpenseApp to function properly, it needs to receive some 'data'. Additionally, I want ExpenseApp to be the first ...

How come my customized directive is not taking precedence over the original methods in AngularJS?

Following the guidelines in the Angular Decorator manual (https://docs.angularjs.org/guide/decorators), I attempted to create a directive and apply decoration to it. The directive's purpose is to display the current date and time. I included a (point ...

Extracting CSS data and storing it in a SQL database

Hello there, I've created a div using CSS like this: echo '#'. $pess2['naam'] .' { width: 190px; height: 90px; padding: 0.5em; float: left; left:'. $pess2['left'] .'px; top:'. $pess2['top'] ...

Encountering a syntax error with the spread operator while attempting to deploy on Heroku

I'm encountering an error when attempting to deploy my app on Heroku: remote: SyntaxError: src/resolvers/Mutation.js: Unexpected token (21:16) remote: 19 | const user = await prisma.mutation.createUser({ remote: 20 | data: { r ...

What could be the reason for my onChange event not functioning properly?

The issue I'm experiencing involves my onchange event not properly copying the text from the current span to the hidden field. Any ideas on why this might be happening? Check out my code at this link. ...

Having trouble finding errors in Python using Selenium?

I encountered an error while using selenium in conjunction with python: selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"/html/body/main/article/section/form/div[1]/div[2]/ ...

Retrieving Data Entries from a MySQL Database with AJAX, PHP, and JSON

I'm facing a challenge with my AJAX/PHP implementation and would greatly appreciate any assistance in identifying the error(s) I might be making. Below is a snippet from my initial file that effectively populates the select element in the HTML: < ...

Having issues with Django not recognizing multiple identical GET parameter names

A Django form is being used for filtering data via a GET form: from reservations.models import Reservation, ServiceType from django import forms PAYMENT_OPTIONS = ( ('CASH', 'Cash'), ('ROOM', 'Charge to room&apo ...

Ways to modify the data within a column for every row in a table without relying on props in Vue.js (specifically Element-ui)

I've been stuck on this issue for quite some time now. I've created a table with 3 columns, and for the first two columns, I can easily display the contents of each row using the prop property. However, for the third column, I need to display inf ...

What steps can I take to alter this situation?

I am working on creating an API Code. Here is the code I have written: When we run the code, it displays as follows: website <?php include('simple_html_dom.php'); $url = 'https://www.g2g.com/wow-us/gold-2299-19249?&server=30805&a ...

Prioritize returning AJAX data over iterating through the parent loop

Hey everyone, I'm having trouble wrapping my head around this issue even after researching various scenarios online. Here's what's going on: I have an array of strings named recipientsList. What I want to do is make an AJAX call for each s ...

Why are my subpages not appearing when using nodejs?

Currently, I'm in the process of creating a basic node app for my website. So far, I have set up my app.js, controllers, and routers. However, I am encountering an issue where two out of three subpages return a 404 error, while the index page works ...