简体   繁体   中英

Listen event from Shadow Dom

How do I listen a mouseover event from shadow DOM. I did try as snipcode below but nothing happen. The template instance is generated after button Add is clicked and I register mouseover event for it and hopping this event is fired when mouseover.

Thank a lot

HTML

<body>
    <h1 class="text-center">Test import Node</h1>
    <div class="container-fluid" style=" background-color: #FAFAFA"></div>
    <div class="col-md-12" id = 'root'>
        <button type="button" class="btn btn-default go" id='_add'><i class="fa fa-pencil-square-o"></i> Add</button>
        <div id = 'textbox' style="height: 200px; width: 400px; font-size: 18px"></div>
    </div>
    <template id = 'area'>
        <div style="height : 400px; width: 300px ; background-color: red"></div>
    </template>
</body>

Javascript

$(document).ready(function() {
    var button = document.querySelector('#_add');
    button.addEventListener('click', function(){
        check();
    }, false);
});
function check(){
     // document.querySelector('#textbox').innerHTML = "Ukie";
     var content = document.querySelector('#area').content;
     content.addEventListener('mouseover', function(){
        display();
     }, false);
     var root = document.querySelector('#root');
     root.appendChild(document.importNode(content, true));
}

function display(){
    document.querySelector('#textbox').innerHTML = "Here";
}

As per addEventListener docs:

The event target may be an Element in a document, the Document itself, a Window, or any other object that supports events (such as XMLHttpRequest).

Therefore element must exist in the DOM, when you call addEventListener on it.

As a workaround, you can use event delegation using jquery on method to achieve the same. Here is a working jsfiddle by tweaking your sample a bit.

$('#root').on('mouseover', '.dyn', function(){
    display();
});

Here bound element will be parent of template content(about which you are sure that it will exist while binding event) and you'll pass selector of your content html to .on method as argument. Thus whenever event occurs on child(in this case your template content) it will bubble up to parent and callback will be triggered.

You can use on function with jQuery. With on function you can "bind" events on element which not created in the DOM when the code was executed.

Read this: http://api.jquery.com/on/

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