Navigate your cursor over the dynamically generated link

I am struggling to create a hover effect similar to the example here in jQuery because the link is being dynamically generated.

Here's what I've tried:

$(document).ready( function() {
    $('a.g-tabs').on('hover', 'a', function() {
            $( this ).append( $('<i class="icon-clear-remove" onClick="tabRemove();"></i>') );
        },
        function() {
            $( this ).find( ".icon-clear-remove:last" ).remove();
    });
});

Unfortunately, this code isn't working. It seems like my selector is the issue. How can I correctly select it?

UPDATE:

This JavaScript code prevents the view from refreshing when a new tab is created:

$(document).on('submit','#pop-form', function(e) {
    // make an ajax request
    $.post('../admin/FLT_add_tab.do',
            $('#pop-form').serialize(),
            function( data ) {
                // if data from the database is empty string
                if( $.trim( data ).length != 0 ) {
                    // hide popover
                    $('#popover').popover('hide');
                    //append new tab and new tab content
                    var id = $(".nav-tabs").children().length - 1;
                    $('#popover').closest('li').before('<li><a href="#tab_'+ id +'" data-toggle="tab" class="g-tabs">' + data + '</a></li>');
                    $('.tab-content').append('<div class="tab-pane" id="tab_' + id + '"> <c:import url="flt-pis.html"></c:import> </div>');
                } else {
                    // error handling later here
                }
            }
    );
    e.preventDefault();
});

The following HTML handles tabs when the user initially visits the page:

<!-- Other tabs from the database -->
<c:forEach var="tabNames" items="${ allTabs }">
     <li><a href="#" data-toggle="tab" class="g-tabs"> ${ tabNames.key }</a></li>
</c:forEach>

<!-- Add new tab -->
<li><a href="#" id="popover">New <i class="icon-plus-sign"></i></a></li>

Lastly, here is the server-side code for creating a new tab:

@ResponseBody
@RequestMapping( value = "/admin/FLT_add_tab", method = RequestMethod.POST )
public String createNewTab( @RequestParam
String newTab, HttpServletRequest request )
{
     HttpSession session = request.getSession();
     String returnVal = Credentials.checkSession( session );

     if( returnVal != null )
     {
         return returnVal;
     }

     String tabName = null;
     try
     {
         DataSource dataSource = DatabaseCommunication.getInstance().getDataSource();
         QuestionnaireDAO qDAO = new QuestionnaireDAO( dataSource );

         if( qDAO.getTabName( 0, newTab ) == null )
         {
             qDAO.insertQtab( newTab );
                tabName = newTab;
         }
     }
     catch( Exception e )
     {
         // no logger yet
         e.printStackTrace();
     }

     return tabName;
}

Answer №1

If the content is dynamically generated, then you must utilize event delegation.

         $(document).on('mouseenter', 'a.g-tabs', function() {
                    $( this ).append( $('<i class="icon-clear-remove" onClick="tabRemove();"></i>') );
        });
    $(document).on('mouseleave', 'a.g-tabs', function() {
      $( this ).find( ".icon-clear-remove:last" ).remove();
 });

Answer №2

give this a shot

 $('a.tabs').on({
    mouseenter:  function() {
        $( this ).append( $('<i class="icon-clear-add" onClick="addTab();"></i>') );
    },
    mouseleave: function() {
        $( this ).find( ".icon-clear-add:last" ).remove();
    }
}, "a"); 

this script is sourced from jQuery .on and hover example

Answer №3

Utilize CSS.

.g-tabs a>.icon-clear-remove
{
 display:none;
}
.g-tabs a:hover>.icon-clear-remove
{
 display:inline-block;
}

E > F Selects any F element that is a direct child of an E element. E:hover Selects the E element when the user hovers over it.

Therefore, E:hover>F signifies that when a user hovers over E, the rule should be applied to F.

Experiment with it here http://jsfiddle.net/7bVTj/

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

Styling Multiple Fullscreen Rows with Bootstrap CSS

Does anyone have any suggestions for the CSS code needed to stack five rows on top of each other? Each row should be 100% height and width of the browser. Here is the HTML code I currently have: <div id="wrapper"> <div class="container-fluid"> ...

Adding a close button inside a circular background using HTML/CSS

I'm struggling to align the X inside the circle perfectly; they just don't seem to match up no matter what I try. Here's a glimpse: https://i.sstatic.net/OIZik.png html: <div class="messages"> <span class="c ...

Angular JS: By utilizing the ng-if directive, I aim to dynamically update the status from active to inactive

Using Angular's ng-repeat, I have a setup to display admin data. tr(data-ng-repeat="admin in admins") td {{$index+1}} td {{admin.profile.AdminName}} td(ng-if = "admin.account.status === 1") active ...

Arranged list becomes depleted (Although Lodash's groupBy function still functions properly)

Check out the sample plunker here Initially, I am grouping a collection by a specific key, which in this case is yob (year of birth). I have two approaches: I can create a custom function to group the collection, allowing for custom logic to be impleme ...

Implement dynamic routing in Express by utilizing handlebars templates

My current goal is to extract a page name from a GET request using express so that I can dynamically load a handlebar file based on this specified name. The challenge arises when the page loads, as express continues to receive requests for assets such as ...

pace.js will always fall short of reaching 100% complete

I recently integrated pace.js and pace.css into my website. Following the instructions on the pace website, I added the .js and .css files to the header element as early as possible: <head> <meta charset="utf-8" /> <title>@ViewB ...

Tips on utilizing the Google Maps autocomplete feature exclusively for place suggestions, without displaying the map itself

I have implemented an input form where users can see suggestions of places related to the word they type. I came across a solution using Google Maps autocomplete, but I do not need the map itself. All I require is the functionality that provides suggestion ...

What is preventing me from being able to import a React component from a file?

I've double-checked my code and everything seems correct, but when I view it on the port, only the app.js file is displayed. import React from 'react'; import ImgSlider from './ImgSlider'; import './App.css'; function ...

Error: Router service provider not found in Angular 2 RC5!

Having trouble with using this.router.navigate. Here is the content of my app.module.ts file: import {NgModule, NgModuleMetadataType} from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; im ...

Is There a Bug with jQuery.find() in Internet Explorer 7?

After writing some code using a certain function, I noticed that it only seems to detect the first element in IE7. Interestingly enough, it works as expected in IE8, Firefox, and Chrome. $(document).find("#JobID").attr('checked', $('#CheckA ...

Angular dropdown menu optionsHuge selection of dropdown menu

We currently have a dropdown menu code used in Angular.js that looks like this: <div class="additional-features"> <div class="event-update-label">Update Options</div> <div class="additional-features-item" ng-click="performOper ...

Steps for creating a resizable and automatically hiding side menu

I am working on a side menu that can be resized, and I want it to collapse (set to zero width) when it is empty. I have considered implementing one of these features individually, but I'm not sure how to make both work together. Is there a way to ad ...

Creating a wrapper class in Express JS: A step-by-step guide

I am currently developing a basic wrapper app that retrieves the following information from user requests: a) Request Date & Time b) Request URL c) Response Time This is my approach to wrapping the functionality using Express.js: var express = require(&a ...

Tips for getting rid of unnecessary spaces between Html table cells in Html5

I have the following HTML script: <header> <div id="header"> <table class="headertable"> <tr> <td> <table clas ...

The automatic selection process for IE document modes

It may seem simple, but I'm a little perplexed about how IE decides which browser mode to use. In IE9, there are options such as IE9 Compatibility Mode, IE9, IE8, and IE7. These modes are selected automatically depending on the webpage. Can someone e ...

Is there a way to hide a language switch without relying on JavaScript?

I have developed a functional concept using Bootstrap 5.2.3 that allows me to switch languages within a card element by clicking on an icon. This function is based on the multi-collapse feature and does not require JavaScript. When you click on the flag ic ...

Why is the greater-than operator not functioning correctly in the @if statement of this mixin?

.container { --random: 200px; @mixin test() { @if (var(--random) > 500px) { color: orange; } } @include test(); } My objective is to apply the style color: orange; to .container if the variable exceeds 500px. P.S. I was unsure ...

Generate an individualized rendering perspective

Hello, I am currently learning React and working on developing a Todo App. However, I have encountered an issue that has left me stuck. I need to figure out how to separate the value of [todos] into those marked as completed and pending. To-do List displ ...

Alignment Troubles with Icons

I am having trouble positioning some icons on the far right of my 960 grid template header, next to my logo which is on the far left. I have tried multiple ways but can't seem to get it right. Any assistance would be greatly appreciated. Below is the ...

Looking for assistance in creating a stunning portfolio showcase?

As I work on building my portfolio webpage, I've realized that with my limited knowledge of HTML/CSS, creating a great gallery might be challenging. In search of an efficient solution, I ventured across the web but couldn't find anything that ful ...