How to Create Hoverable Select Box Options with JavaScript?

Patricia Arquette
Release: 2024-11-01 07:59:01
Original
205 people have browsed it

How to Create Hoverable Select Box Options with JavaScript?

Hoverable Select Box Options

The question at hand involves creating a select box where the option descriptions are visible when the field is hovered over, rather than clicking to open the options.

Implementation

To achieve this functionality, we utilized a JavaScript approach as follows:

$('#selectUl li:not(":first")').addClass('unselected');
// Hide the 'unselected' elements in the ul.

$('#selectUl').hover(
    function(){
    // mouse-over
        $(this).find('li').click(
            function(){
                $('.unselected').removeClass('unselected');
                // removes the 'unselected' style

                $(this).siblings('li').addClass('unselected');
                // adds 'unselected' style to all other li elements

                var index = $(this).index();
                $('select option:selected').removeAttr('selected');
                // deselects the previously-chosen option in the select

                $('select[name=size]')
                    .find('option:eq(' + index + ')')
                    .attr('selected',true);
                // assumes a 1:1 relationship between the li and option elements
            });
    },
    function(){
    // mouseout (or mouseleave, if they're different, I can't remember).
    });
Copy after login

In this approach, the unselected class is utilized to initially hide all options except the first one. When the ul is hovered over, the non-clicked elements are given the unselected class, effectively disappearing. The selected element remains visible and its corresponding value is reflected in the underlying select field.

The above is the detailed content of How to Create Hoverable Select Box Options with JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!