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 encountered: The fiber texture failed to load due to a component becoming suspended during the response to synchronous input

I'm encountering an issue while attempting to load a texture through the TextureLoader: const texture = useLoader(TextureLoader, '/textures/texture.png') The error message I receive from react is as follows: ERROR A component suspended w ...

Converting the 'require' call to an import may be a more efficient method when importing package.json in a typescript file

In my current project, I am creating a class where I am directly accessing the package version number like this: const pkg = require('../package.json') export class MyClass() { constructor() { // Set the base version from package.jso ...

Transform the display format of the input type date field from 'MM/DD/YYYY' to 'February 5, 2012' in a React.js application using Material-UI's TextField component

https://i.stack.imgur.com/9p7Mz.jpg I am working with a material-ui/ TextField date component and I am looking to maintain the current style and input method, but I need to adjust how the entered value is displayed to the 'en-us' format. const o ...

Can I send an AJAX request from an .ascx page? Below is my code for your review

I am working on an .ascx page and facing an issue with calling the .autocomplete function inside it along with an ajax call. Any assistance would be appreciated. $("#txtUsers").autocomplete({ //source: availableTags source: function (request, resp ...

Waiting for user submission before executing a JavaScript function

const onSubmit = ()=>{ someFunction().then(()=>{ // next step is to wait for user interaction by clicking a specific button // user initiates the action // perform specific task }) } Essentially, after the initial form submissi ...

Ensure that the token remains current with each axios operation

I need to access an Express REST API that demands a valid json web token for certain routes. In order to include the token from localstorage every time I needed, I had to create an "Axios config file". My http.js file includes the code below: import Vue ...

Unable to load JSON information into an ExtJS grid

I have exhausted all the solutions I found (there are many on Stackoverflow) in an attempt to fix my extjs store issue. Despite ensuring that the grid is displayed correctly, the data still refuses to show up. Feeling perplexed, I am sharing the "store" co ...

Guide: Looping through a typed Viewbag array - best practices

I have passed a List<AdminUsers> through the Viewbag to a view. This list is then assigned to a JavaScript variable and looped through. However, when debugging on the view, I noticed that the for loop is not being executed, even though I set a break ...

What sets apart the CSS file directories in a React application compared to those in an Express server?

For instance, there is a public folder that contains all the css files, and a separate view folder for ejs files. When linking the css file in the ejs file, the code usually looks like this: <link rel=”stylesheet” href=”styles.css”> or like ...

Deleting a particular tag with regular expressions: a step-by-step guide

I'm attempting to remove a ul tag along with any nested tags inside it. <ul class="related"> <li><a href="/related-1.html" target="_blank">Related article</a></li> <li><a href="/related-2.html" target="_blank"&g ...

Javascript will not recognize or interpret PHP's HTML tags

When PHP sends HTML strings to HTML through AJAX wrapped in <p class="select"></p> tags, the CSS reads the class perfectly. However, JavaScript/jQuery does not seem to work as expected. Even when trying to parse <p onclick="function()">&l ...

How can I send a variable into the DOM using AJAX?

Apologies for posting a question earlier about creating a condition for checkbox without proper investigation. It appears that I need to pass my variables here. function setsession(sessionid, action, data) { $("#totalselection").show(); $. ...

Guarantee the successful execution of a server-side function using my client-side function

I am currently in the process of creating a website that utilizes Javascript and Asp.net. My code contains numerous functions on the client side, within my html code, while my server side functions are called using a webservice. How can I ensure that my c ...

Adding a query parameter to my website causes a particular element to fail to display on the page

I'm facing a challenge in sharing my code, but since my project is open source, you can find the code here. I've noticed that when I receive a link from another site with /? at the end, it causes an issue on my website where the hero image secti ...

Retrieve 2 data points from an HTML source code using Python

I'm struggling to extract data-b following the term "Grab" from the unmodified webpage code. There are multiple <tr> tags on the page and I need to specifically target those containing "Need" just before </a>. While I initially tried using ...

Integrating webpack with kafka-node for seamless communication between front

I am in the process of embedding a JavaScript code that I wrote into an HTML file. The script requires kafka-node to function properly, similar to the example provided on this link. To achieve this, I am using webpack to bundle everything together. I am fo ...

How can I use Angular 7 to create a background image for a View made up of multiple components?

Here is the HTML code that I am working with: <app-navbar></app-navbar> <router-outlet></router-outlet> My goal is to have an image set as the background for the home view, which consists of two components: navbarComponent and hom ...

A dysfunctional JS object

I am grappling with a rather intricate object and have simplified it by removing unnecessary functions. However, I am facing an issue when I try to initialize it and I can't figure out the reason behind it. Safari is throwing this error at me: [Error] ...

Step-by-step guide on activating and utilizing file versioning in Firebase Storage

Google Cloud Platform powers Firebase storage, allowing for versioning of files. Within the Firebase console, there are no options related to the GCP bucket. If you access the GCP console, it may not be apparent how to enable versioning in the bucket asso ...

What is the process for importing specific modules from jQuery?

When working with webpack or browserify, what is the specific procedure required to import only the essential modules from jQuery as mentioned here? import {core, dimensions} from 'jquery' Unfortunately, this approach does not seem to be effect ...