Home  >  Article  >  Web Front-end  >  How to Make HTML Select Box Options Appear on Hover?

How to Make HTML Select Box Options Appear on Hover?

Barbara Streisand
Barbara StreisandOriginal
2024-10-31 00:26:30957browse

How to Make HTML Select Box Options Appear on Hover?

How to Display HTML Select Box Options on Hover

The challenge you presented involves creating a select box where the options are hidden until the user hovers over it. Here's a detailed solution:

Implementation:

The code provided utilizes jQuery's hover() event to toggle the visibility of the list elements. The unselected CSS class is used to style list items that are not currently displayed.

HTML Markup:

<code class="html"><select name="size">
  <option value="small">Small</option>
  <option value="medium">Medium</option>
  <option value="large">Large</option>
</select></code>

CSS Styles:

<code class="css">select {
  opacity: 0.5;
}
ul {
  width: 8em;
  line-height: 2em;
}
li {
  cursor: pointer;
  display: list-item;
  width: 100%;
  height: 2em;
  border: 1px solid #ccc;
  border-top-width: 0;
  text-indent: 1em;
  background-color: #f90;
}
li:first-child {
  border-top-width: 1px;
}
li.unselected {
  display: none;
  background-color: #fff;
}
ul#selectUl:hover li.unselected {
  background-color: #fff;
}
ul#selectUl:hover li,
ul#selectUl:hover li.unselected {
  display: list-item;
}
ul#selectUl:hover li {
  background-color: #fc0;
}
ul#selectUl li:hover,
ul#selectUl li.unselected:hover {
  background-color: #f90;
}</code>

JavaScript Event Handling:

<code class="js">$('#selectUl li:not(":first")').addClass('unselected');

$('#selectUl').hover(
  function () {
    $(this).find('li').click(function () {
      $('.unselected').removeClass('unselected');
      $(this).siblings('li').addClass('unselected');
      var index = $(this).index();
      $('select option:selected').removeAttr('selected');
      $('select[name=size]')
        .find('option:eq(' + index + ')')
        .attr('selected', true);
    });
  },
  function () {}
);</code>

How It Works:

  1. Initially, all option elements in the ul are hidden by adding the unselected class.
  2. When the user hovers over the ul, the hover() event is triggered, causing all list items except the first one (which is the selected option display) to become visible.
  3. Clicking on any list item toggles the unselected class, hiding all other options and revealing the clicked option as selected.
  4. The index() method is used to determine the index of the clicked option, which is then used to update the selected option in the