Search code examples
javascriptprototypejsdom-events

JS / Prototype - Detect SELECT element collapsed or option actually selected


I have functionality setup to execute whenever a select element changes its value. Instead of using the normal onchange event, it executes every 300ms and only calls the handler if it detects a changed value. I'm using prototype's Form.Element.Observer, if this means anything to you.

Now, in Firefox, when the user hovers over the option and the timed value check function fires, the handler is called because the browser says that the value has changed. What I would like to do is be able to detect when the option has actually been selected by the user instead of simply hovered over. I realize in the Prototype documentation, they explicitly note this bug (or feature, depending how you look at it) but I would like to be able to normalize the behavior.

In a way, this is somewhat similar to a question I've seen on StackOverflow before ( Detect if an HTML select element is expanded (without manually tracking state) ) but I was hoping someone out there would be able to tell me how to do this for only a specific select element and when it's closed instead of expanded.

To get a better idea of what I mean, check out http://jsfiddle.net/KxQd6/ , mess with the select element and check out the console logs.


Solution

  • Here is an example showing how to control SELECT element changes through the different stages you mentioned:

    (user, dom-load, and js update)

    This code utilizes event.simulate which provides a cross browser way of firing/simulating events.


    CODE (fiddle)

    document.observe('dom:loaded', function() {
        var select = $('box_1'),
            button_1 = $('change_via_ajax'), 
            button_2 = $('change_via_script'), 
            results = $('results');
    
        // create observer on our select
        select.observe('change', function(e) {
            var d = new Date()
                t = d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds();
            results.insert(new Element('div')
                   .update(t + ' - Change was fired, value is now [' + this.value + ']'));
        });
    
        button_1.observe('click', function() {
            new Ajax.Request('/echo/json/', {
                onComplete: function(j) {
                    select.options[Math.round(Math.random() * 2)].selected = true;
                    select.simulate('change');
                }
            });
        });
    
        button_2.observe('click', function() {
            select.options[0].selected = true;
            select.simulate('change');
        });
    });​