简体   繁体   中英

Simulate Click with Vanilla Javascript

I have a SELECT element that I am replacing with a dropdown. I have successfully created the dropdown from the SELECT and child OPTION elements, but I need to add a click event.

This click event would be as such:

If LI is clicked, also click corresponding OPTION.

This is because Woocommerce must have some JS or PHP working where depending on the option, it shows stock status and variable amount. As such, I assume that the click event will also bind the OPTION value to the form for adding to cart.

I have this JS code:

window.onload = main;
function main(){ 
var select = document.querySelector('.turnintodropdown');
var selsOpts = document.querySelector('.turnintodropdown option');
var selsLi = document.querySelector('.selectOption');
var trigger = document.createElement('a');
var openDropdown = 'dropdownVisible';
var closeDropdown = 'dropdownHidden';

(function addDropdown() {
    if(select) {
        var selsCon = document.createElement('div');
        var selsOuter = document.createElement('ul');
        selsCon.classList.add('selectContainer');
        selsOuter.classList.add('selectOuter');
        select.parentNode.insertBefore(selsCon, select);
        selsCon.appendChild(selsOuter);
        for(var i=0; i<select.length; i++) {
            if(select.childNodes[i].classList.contains('enabled') || select.childNodes[i].innerHTML == '- -'){ // Select First Child and <option> Tags with Enabled Class

                // Create New Elements
                var optsNew = document.createElement('li');
                optsNew.innerHTML = select.childNodes[i].text;
                optsNew.classList.add('selectOption');

                // Set Attributes to New Elements
                if(optsNew.innerHTML !== '- -') {
                    optsNew.setAttribute('value', select.childNodes[i].text);
                }
                else {
                    void(0);
                }

                optsNew.click(clickFunc);

                // Add New LI <option> to UL <container>
                selsOuter.appendChild(optsNew);

                // Click Events
                console.log(select.firstChild);
            }
        }
        var clickFunc = function() {
            select.click();
        };
        select.style.display = 'none';

    }

})();
}

Any help would be greatly appreciated.

Regards Michael

I was a bit long to answer, sorry.

the function was originally taken from this webpage and not modified, it is supposed to work with most old browsers. I actually tested on last versions of Firefox / Chrome / Opera / Edge with success.

The version which handles all types of events is more complicated because you have to make cases for standard events to process them by type (not all are MouseEvents ).

It also supports the inline functions, with onclick= in the html tag, and works also for events set with jQuery.

Note that if you want the same support for old broswers, you'll have to differentiate cases for the setting of events too, the modern addEventListener being not supported by all.

function fireClick(node){
    if ( document.createEvent ) {
        var evt = document.createEvent('MouseEvents');
        evt.initEvent('click', true, false);
        node.dispatchEvent(evt);    
    } else if( document.createEventObject ) {
        node.fireEvent('onclick') ; 
    } else if (typeof node.onclick == 'function' ) {
        node.onclick(); 
    }
}

used like this for example:

fireClick(document.getElementById("myId"));

Vanilla JS (without jQuery)

/**
 * Simulate a click event.
 * @public
 * @param {Element} elem  the element to simulate a click on
 */
var simulateClick = function (elem) {
    // Create our event (with options)
    var evt = new MouseEvent('click', {
        bubbles: true,
        cancelable: true,
        view: window
    });
    // If cancelled, don't dispatch our event
    var canceled = !elem.dispatchEvent(evt);
};

To use it, call the function, passing in the element you want to simulate the click on.

var someLink = document.querySelector('a');
simulateClick(someLink);

src / full article: https://gomakethings.com/how-to-simulate-a-click-event-with-javascript/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM