JQuery showing text on hover - Looped Item

I need to show the text for an icon when it is hovered. The problem is the icons are showing through the loop. Meaning I have more than one icon with the same name. I'm pretty sure I need to somehow use "this" to only show the text next to the icon it is hovering over. However, I have not done this until now.

My basic code. How can I change the code to display the text depending on which icon is hovered on?

$(".material-icons").on({
        mouseenter: function () {
         console.log('Show Name for this Icon')
        },
        mouseleave: function () {
         console.log('Hide Name for this Icon')
        }
    });

      

Any help is appreciated!

Edit: Here is the loop that is used to display the icons.

   <li id='topSection' class="list-group-item active">Amenities </li>
             <li id="amnetiesBox" class="list-group-item">
              <% for(var i=0; i<rentals.amenities.length; i++){ %>
              <i class="material-icons"><%=rentals.amenities[i]%></i>
               <% } %>
            </li>
              </li> 

      

Example of selected icons:

<input type="checkbox" name="amenities" value="personal_video"><span>TV</span>
<input type="checkbox" name="amenities" value="call"><span>Phone</span>

      

+3


source to share


2 answers


I came up with a somewhat simple solution that works. The problem with other suggestions is that I am unable to add gaps to the icon due to the loop (as far as I know.)

I went with this:



  $(".material-icons").on({
        mouseenter: function () {
    var text = $(this).text();

    if (text === 'wifi'){
        text = 'Local Wifi'
    }

    if (text === 'local_laundry_service'){
        text = 'Laundry on site'
    }

      $(".showName").show()
      $(".showName").html(text)
        },
        mouseleave: function () {
         $(".showName").hide()
        }
    });

      

So what it does is first find the name of the icon and if the name of the icon is "local_laundry_service" etc. I update the text to simply say "Laundry in place." Obviously, you must do this for every icon that can be used. Not very dry code, but I'm not sure how to do it.

0


source


You can use $(this)

and display the text associated with this target element



$(".material-icons").on({
        mouseenter: function () {
            $(this).next("span").show()
        },
        mouseleave: function () {
           $(this).next("span").hide()
        }
    });
      

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="material-icons" ><span>Hover </span></div> <span style="display:none">first</span>
<div class="material-icons" ><span>Hover</span></div> <span style="display:none">second</span>
<div class="material-icons" ><span>Hover</span></div> <span style="display:none">third</span>
      

Run codeHide result


0


source







All Articles