Santa
Santa

Reputation: 47

hover on dynamically created list

I have a menu with a list of items created dynamically using javascript.
They have different colour and country attributes created using setAttribute.

$("#menuList a").hover(
  function() {
    var countryName = $(this).attr('country');
    var fruitColour = $(this).attr('colour');
    $('#toshow').append($("countryName \n fruitColour"));
  },
  function() {}
);
.toshow {
  display: none;
}

#menuList a:hover div.toshow {
  top: 0;
  right: 0;
  display: block;
  position: absolute;
  z-index: 99999;
  background: red;
  width: 200px;
  height: 100px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="menubar" id="menuList">
  <li><a href="#" country="US" colour="green">Watermelon</a></li>
  <li><a href="#" country="Australia" colour="green">Grapes</a></li>
  <li><a href="#" country="null" colour="null">Strawberry</a></li>
  <li><a href="#" country="null" colour="null">Blueberry</a></li>
</ul>


<div class="toshow" id="toshow"></div>

Here, I want to have a separated hidden div (display at top right of the page or next to the menuList) that does not have any content until any of the <a> tag being hovered, and show its responding two attributes until no more mouse hovered.

The code does not have errors. But I don't see anything in red when the mouse hovered through the list. Is it possible to achieve what I am looking for?

Upvotes: 0

Views: 1681

Answers (1)

slider
slider

Reputation: 12990

You can use the mouseout event to hide the toshow div with hide as you leave a list element. And at each hover event, you can change the html of toshow to the values of the li element which the user is hovering over and use show to display it.

Also make sure you attach the event handlers after you've inserted the html of the dynamically generated list.:

function displayGeneratedList() {
  $('#menuList').html(`
    <li><a href="#" country="US" colour="green">Watermelon</a></li>
    <li><a href="#" country="Australia" colour="green">Grapes</a></li>
    <li><a href="#" country="null" colour="null">Strawberry</a></li>
    <li><a href="#" country="null" colour="null">Blueberry</a></li>
  `);
  $("#menuList a").hover(function() {
    var countryName = $(this).attr('country');
    var fruitColour = $(this).attr('colour');
    $('#toshow').html(`${countryName}<br>${fruitColour}`).show();
  });
  $('#menuList a').mouseout(function() {
    $('#toshow').hide();
  });
}

$(document).ready(function() {
  displayGeneratedList();
});
#menuList {
  display: inline-block;
}

.toshow {
  display: none;
  float: right;
  background: maroon;
  width: 200px;
  height: 100px;
  padding: 5px;
  color: white
}
<ul class="menubar" id="menuList">
</ul>

<div class="toshow" id="toshow"></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Upvotes: 1

Related Questions