Display unique data-id values for each list item when hovering with Jquery

I am designing a menu for my website where it will appear on the left side of the web. The menu will consist of X <li> items, each with an icon. When I hover over each <li>, I want to display X data-id associated with that item along with the icon.

For example:

<ul><li data-id="My Profile">ICON</li></ul>

On mouseover:

<ul><li>ICON + My Profile</li></ul>

I have tried implementing this functionality but it seems to be not working correctly. Here is the example: http://jsfiddle.net/pqa84nec/1/

This is the JavaScript code I am using:

$("#menu").each(function() {
$(this).find('li').each(function(){
var oldData = $(this).html();
var data = $(this).attr("data-id");
var that = this;
        $(this).mouseover(function() {
setTimeout(function() {
            $(that).html(oldData+data);
}, 100);
        });
        $(this).mouseout(function () {
             $(this).html(oldData);
        });
});
    });

Can someone offer me some assistance with this issue?

P.S.

It appears that there is a bug in the code:

https://i.sstatic.net/fcgzz.png

Thank you!

Answer №1

Give this a shot:

Here's the JavaScript code snippet:

$(function() {
  $("#menu ul li").each(function() {
    var _this = $(this);
    var icon = _this.html()
    $(this).hover(function(e) {
      setTimeout(function() {
        _this.html(icon + _this.data('id'));
      }, 200);
    }, function(e) {
      setTimeout(function() {
        _this.html(icon);
      }, 200);
    })
  });
});


Include this CSS code:

#menu>ul>a {
  overflow: hidden;
}

Link to example on JsFiddle

Answer №2

Your script contains several errors that need to be addressed. Consider the following revised version:

$(document).ready(function() {
  $("#menu a li").each(function() {

    var previousContent = $(this).html();
    var dataValue = $(this).attr("data-id");

    $(this).mouseover(function() {
      setTimeout(function() {
        console.log(previousContent + dataValue);
        $(this).html(previousContent + dataValue)
      }, 100);
    });
    $(this).mouseout(function() {
      console.log(previousContent);
      $(this).html(previousContent)
    });

  });
})

Answer №3

If you're open to a CSS solution, I have something for you that builds on your existing code. This approach eliminates the need for JavaScript to operate your menu. It may not be elaborate, but it offers a starting point for improvement. In the provided fiddle, I included the Font Awesome library for icon usage.

HTML:

<div id="menu">
    <ul>
        <li>
            <a href="#">
                <i class="fa fa-user"></i>
                <span>My Profile</span>
            </a>
        </li>
        <li>
            <a href="#">
                <i class="fa fa-power-off"></i>
                <span>Log Out</span>
            </a>
        </li>
    </ul>
</div>

CSS:

*{margin:0;padding:0;}
html,body {
    background-color: #263238;
    font-family: 'Roboto', sans-serif;
    height: 100%;
}
li {
  position: relative;
}
a {
  text-decoration: none;
}
#menu {
  background-color: #37474f;
  height: 100%;
  left: 0;
  position: fixed;
  top: 0;
  width: 50px;
}
#menu ul {
  list-style: none;
}
#menu > ul > li {
  border-bottom: 1px solid #263238;
}
#menu > ul > li > a {
  color: #263238;
  display: block;
  font-size: 22px;
  height: 50px;
  line-height: 50px;
  overflow: hidden;
  position: relative;
  transition: all 0.3s ease 0s;
  width: 50px;
}
#menu > ul > li > a i {
  display: block;
  height: inherit;
  line-height: inherit;
  text-align: center;
  width: 50px;
}
#menu > ul > li > a span {
  color: #fff;
  font-size: 16px;
  left: 50px;
  max-width: 130px;
  opacity: 0;
  overflow: hidden;
  padding-left: 10px;
  padding-right: 10px;
  position: absolute;
  text-overflow: ellipsis;
  top: 0;
  transition: opacity 0.3s ease .2s;
  visibility: hidden;
  white-space: nowrap;
}
#menu > ul > li > a:hover {
  background-color: #fbd75b;
  color: #fff;
  width: 200px;
}
#menu > ul > li > a:hover span {
  opacity: 1;
  visibility: visible;
}

Check out the fiddle here: jsfiddle.net/LjLvwb8q/3/

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

The height of each Bootstrap column is equal to the height of its corresponding

I am trying to prevent the column height from being equal to the row height in Bootstrap. Here is my code snippet: <div class="row justify-content-center text-center"> <div class="col-sm-3"></div> <div class="col-sm-9"></d ...

What is the arrangement of the Bootstrap grid stack?

I'm facing an issue with positioning in the bootstrap grid on desktop view. My goal is to achieve: https://i.sstatic.net/VosAw.jpg The problem arises with the spacing when using <div class="col-xs-6 col-md-4">. It doesn't look good in mob ...

Does angular have a feature comparable to JavaScript's .querySelectorAll()?

I developed an inventory calculator in JavaScript that provides item count based on weight. The calculator has 4 inputs, and now I'm looking to replicate the same functionality using Angular. Is there a method in Angular similar to .querySelectorAll() ...

Error in Node and Express: Unable to access route

Currently, I am in the process of developing an Express application and running into some obstacles with routing. While my '/' route is functioning perfectly fine, other routes are not working as expected. Despite researching similar questions fr ...

Tips for updating a list of orders using keywords entered in a text input field

I have a collection of car objects and an input field that triggers a change event. When the value in the input field is updated, I want to reorganize the order of the cars. For example, if I enter "Tau" in the input box, I want the ford object to be plac ...

Angular http.get() recognizing when a call exceeds its timeout limit

I'm currently facing a challenge in detecting request timeouts with Angular http and promises. My code is designed to format API responses, but it fails to handle timeout errors effectively. Despite working when the API returns an error message, it do ...

Creating a background overlay on top of an image background using styled-components in React: A step-by-step guide

I need help figuring out how to construct a unique component in react styled component that combines a background image with a black semi-transparent overlay. For visual reference, here is an example: https://i.sstatic.net/R6IBY.jpg ...

Is there a way to prevent an external script from making changes to an inline style?

There is a mysterious script running on a page that seems to be controlling the height of an inline style. The source of this script modifying the height property is unknown. <div class="vgca-iframe-wrapper wpfa-initialized" style="heigh ...

Don't forget to keep in mind the importance of the "Radio" value when you are submitting a form to yourself on

When dealing with a text input, you can remember the value entered by the user if the form is submitted to itself. This technique comes in handy for tools like a picture upload tool, where the user's input needs to be saved to avoid retyping after upl ...

What is the name attribute of an ES2015 function?

var individual = { announceIdentity() { console.log(this.identity); }, get firstID() { return "Superman"; } }; individual.announceIdentity.identification // "identity" individual.firstID.identifier // "get firstID" I recently came acros ...

"Can you guide me on how to display a React component in a

I have a function that loops through some promises and updates the state like this: }).then((future_data) => { this.setState({future_data: future_data}); console.log(this.state.future_data, 'tsf'); }); This outputs an array o ...

Discovering an npm module within an ember-cli addon component

I recently encountered an issue while using ember-browserify to locate npm modules in my ember-cli applications - it seems to not function properly for ember-cli addons. This leads me to wonder: Are there alternative methods for importing npm modules into ...

The Google Maps API is not providing any data in response to my jQuery JSONP request

Similar Topic: Unpacking Google Geo API (Reverse Geocoding) using jQuery $(window).load(function() { var purl = "http://maps.googleapis.com/maps/api/geocode/json?latlng=32.759294499999996,-97.32799089999999&sensor=false"; $.getJSON(purl,f ...

Solving layout issues / Techniques for determining element heights

This new question is in relation to my previous one: How to position relative elements after absolute elements I have updated the JsFiddle from that question to better represent my current HTML, which I unfortunately do not have a URL for at the moment. Y ...

Tips for waiting for a function to finish executing in node.js (using a for loop)

Currently, the issue lies in the fact that the for loop instantly loops through everything. However, I want it to pause before looping because each time the loop runs, it inserts data into the database (which takes time). Therefore, I would like it to wait ...

Applying a background image to Django templates: Step-by-step guide

I am encountering an issue on my website where I need to insert an image as a background in a specific table cell. However, the image appears duplicated because it is smaller than the cell's width and height, causing an overlap effect. Even though I ...

Turn on and off jquery tabs depending on user's choice

Currently, I am utilizing jQuery tabs to showcase specific data. However, I aim to offer users the flexibility to choose whether they prefer to view the content as tabs or in a sequential manner. Even after attempting to manipulate the ui-tabs classes ba ...

Are there any features in web browsers that support accessibility, such as those designed for sign language?

Many web browsers currently share the user's preferred language with the websites they visit (e.g. in JavaScript: navigator.language || navigator.userLanguage). However, what if a user's native language is sign language, or if they need a simple ...

Refreshing the calendar events in the eventDrop function using Jquery FullCalendar

I'm looking for a way to reload my jQuery Fullcalendar using an AJAX call without having to create a new calendar each time. Currently, I am initializing my calendar events by fetching dates with the GetSchedule method. When an eventDrop occurs, I ne ...

Alignment of labels in Bootstrap for various form groups with error messages and required fields

How can I align a horizontal text box in the same row even though the label is on a different line? <div class="row"> <div class="col-sm-12 col-lg-4"> <div class="form-group"> ...