Home > Web Front-end > JS Tutorial > Why Doesn\'t My `onClick` Event Listener Work in IE8, and How Can I Fix It?

Why Doesn\'t My `onClick` Event Listener Work in IE8, and How Can I Fix It?

Patricia Arquette
Release: 2024-11-28 08:44:14
Original
611 people have browsed it

Why Doesn't My `onClick` Event Listener Work in IE8, and How Can I Fix It?

IE8 onClick Event Listener Compatibility Issue

Problem:
In the provided code, the JavaScript event listener for the li element is not functioning in the IE8 browser.

Solution:

IE8 lacks the addEventListener method, so an alternative cross-browser event handling solution is required. The following code provides a polyfill for addEventListener that works in both standard and legacy browsers:

var hookEvent = (function() {
    var div;

    // Standard-compliant browsers
    function standardHookEvent(element, eventName, handler) {
        element.addEventListener(eventName, handler, false);
        return element;
    }

    // Legacy IE browsers
    function oldIEHookEvent(element, eventName, handler) {
        element.attachEvent("on" + eventName, function(e) {
            e = e || window.event;
            e.preventDefault = oldIEPreventDefault;
            e.stopPropagation = oldIEStopPropagation;
            handler.call(element, e);
        });
        return element;
    }

    function oldIEPreventDefault() {
        this.returnValue = false;
    }

    function oldIEStopPropagation() {
        this.cancelBubble = true;
    }

    div = document.createElement('div');
    if (div.addEventListener) {
        div = undefined;
        return standardHookEvent;
    }
    if (div.attachEvent) {
        div = undefined;
        return oldIEHookEvent;
    }
    throw "Neither modern event mechanism (addEventListener nor attachEvent) is supported by this browser.";
})();
Copy after login

Usage:
In the provided code, replace the getElementById().addEventListener() calls with:

hookEvent(document.getElementById("hd_vertical"), "click", function(e) {
   // ...
});
Copy after login

Additional Notes:

  • IE8 also does not support getElementsByClassName. Use querySelectorAll instead.
  • The provided polyfill normalizes some event properties but not all. Consider using a library like jQuery for comprehensive event handling.

The above is the detailed content of Why Doesn\'t My `onClick` Event Listener Work in IE8, and How Can I Fix It?. 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