Home » Jquery » jquery – ToolTips for ONLY a long sentence

jquery – ToolTips for ONLY a long sentence

Posted by: admin February 22, 2020 Leave a comment

Questions:

I have a UL LI dropdown menu, each LI element has a different length. If I pick a LI with long sentence, it will show only a part of this sentence and … at the end.

Goal: If a short sentence is picked, it won’t show a tooltip when hovering it. If I pick a long sentence, then I hover it, a tooltip will show its entire name.

Problem: If I pick a long sentence, I hover it, a tooltip will show its entire name, THEN I pick a short sentence, it shouldn’t shows a tooltip, but it hover it, the tooltip shows previous long sentence with I just picked.

Please help.

$(document).on("click", '.list-unstyled li', function() {
  var textString = $(this).html();
  var textLength = $(this).text().length
  console.log("This : " + textString);
  console.log('length: ' + textLength);
  $(document).on('mouseenter', '.list-unstyled', function() {
    if (textLength > 30) {
      $('.textBox').html(textString).show();
    } else {}

  });
  $(document).on('mouseleave', '.list-unstyled', function() {
    $('.textBox').hide();
  });
});



$("ul").on("click", ".init", function() {
  $(this).closest("ul").children('li:not(.init)').toggle();
});

var allOptions = $("ul").children('li:not(.init)');
$("ul").on("click", "li:not(.init)", function() {
  allOptions.removeClass('selected');
  $(this).addClass('selected');
  $("ul").children('.init').html($(this).html());
  allOptions.toggle();
});
body {
  padding: 30px;
}

ul {
  height: 30px;
  width: 150px;
  border: 1px #000 solid;
}

ul li {
  padding: 5px 10px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  -o-text-overflow: ellipsis;
  z-index: 2;
}

ul li:not(.init) {
  float: left;
  width: 130px;
  display: none;
  background: #ddd;
}

ul li:not(.init):hover,
ul li.selected:not(.init) {
  background: #09f;
}

li.init {
  cursor: pointer;
}

a#submit {
  z-index: 1;
}

.textBox {
  position: absolute;
  top: 0;
  left: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="textBox"></div>
<ul class="list-unstyled">
  <li class="init">[SELECT]</li>
  <li data-value="value 1">Sentence 1</li>
  <li data-value="value 2">Sentence 2</li>
  <li data-value="value 3">This sentence is longer than 30 characters</li>
  <li data-value="value 3">This is another sentence longer than 30 characters</li>
</ul>
How to&Answer: