Subscribing to the DOM element events

Open in CodeSandbox

Dom elements can generate different types of events, depending on the browser and device. For example, hovering the mouse over an object can generate the 'mousedown' event, and touching an item on a tablet screen can generate the 'touchstart' event. The Yandex.Maps API converts various browser events to a single list of events. This means you can write the same code for handling dom events in all browsers and on all devices that are supported by the API.

For a list of API events and how events are converted, see the description of the IDomEventEmitter interface. To subscribe to events of dom elements, use domEvent.manager.

<!DOCTYPE html>

<html>
    <head>
        <title>Examples. Forward geocoding</title>
        <meta
            http-equiv="Content-Type"
            content="text/html; charset=UTF-8"
        />
        <!--
        Set your own API-key. Testing key is not valid for other web-sites and services.
        Get your API-key on the Developer Dashboard: https://developer.tech.yandex.ru/keys/
    -->
        <script
            src="https://api-maps.yandex.ru/2.1/?lang=en_RU&amp;apikey=<your API-key>"
            type="text/javascript"
        ></script>
        <script src="dom_event_manager.js" type="text/javascript"></script>
        <style type="text/css">
            body {
                font-family: Arial;
                font-size: 14px;
            }

            #myElement {
                height: 200px;
                width: 200px;
                display: flex;
                align-items: center;
                justify-content: center;
                font-size: 200px;
                cursor: default;
            }
        </style>
    </head>
    <body>
        <h3>Pet the cat!</h3>
        <div id="myElement">🐈</div>
        <button id="clear">Clear</button>
        <div id="log"></div>
    </body>
</html>
ymaps.ready(init);

function init() {
    /**
     * Even if the user touches the element on a tablet screen, events such as
     * 'touchstart', 'touchmove' and others will be converted into a single list of events.
     * This allows you to write cross-platform code and not to think about the type of device.
     */
    var targetElement = document.getElementById("myElement"),
        events = ["mouseenter", "mouseleave", "click", "dblclick", "wheel"],
        divListeners = ymaps.domEvent.manager
            .group(targetElement)
            .add(events, function (event) {
                log(event.get("type"));
            });

    document.getElementById("clear").onclick = function () {
        document.getElementById("log").innerHTML = "";
    };

    window.log = function (message) {
        document.getElementById("log").innerHTML =
            document.getElementById("log").innerHTML + "<br>" + message;
    };
}