Question

I am working on a greasemonkey script for gmail where i need to make a copy of the "Inbox" link. Using cloneNode works ok, but i think there's an onclick event that gets attached to it at runtime. So, this is a two part question: 1. Is there a way to see what events are attached to a node? 2. Is there a way to copy those events as well? The closest thing i found was jQuery, and i am not ready to go there yet. Thanks!

Was it helpful?

Solution

  1. Not unless it's set using the onclick attribute on the element.
  2. Not reliably (you can copy the onclick attribute, but whether that will continue to work depends on if it was used and what it does).

You're better off adding your own click handler, and then triggering that event on the original... Or simulating the behavior in some other way.

OTHER TIPS

I think we can solve this stuff using this theory:

We have NodeList in JS, also called liveLists. We can check whenever their length changes, addEvent the desired common events to the new element in list at (length-1).

What say....

Here is the example using Nodelist for adding events.

<body>
        <div id="one" class="clones" style="background:red;width:100px;height:100px"></div>
    </body>

    <script>

        //Selecor based live list [Advantage]
        var nodeList = document.getElementsByClassName('clones')

        //Common Function for nodelist
        nodeList.addEvents = function(){
            nodeList.item(nodeList.length-1).addEventListener('click',function(){
                    console.log(this.id);
            });
        }
        nodeList.addEvents();

        //Making Clone
        var _clone  =  document.getElementsByTagName('div')[0].cloneNode(true);

        //Changing Id
        _clone.id="two"

        document.body.appendChild(_clone);
        nodeList.addEvents();
    </script>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top