16

I use this D3 snippet to move SVG g elements to top of the rest element as SVG render order depends on the order of elements in DOM, and there is no z index:

d3.selection.prototype.moveToFront = function () {
  return this.each(function () {
    this.parentNode.appendChild(this);
  });
};

I run it like:

d3.select(el).moveToFront()

My issue is that if I add a D3 event listener, like d3.select(el).on('mouseleave',function(){}), then move the element to front of DOM tree using the code above, all event listeners are lost in Internet Explorer 11, still working fine in other browsers. How can I workaround it?

Sergei Basharov
  • 51,276
  • 73
  • 200
  • 335
  • I'm not familiar with the context of d3, but could you select something like `d3.select('body .selector').on(...`? – Zach Saucier Sep 26 '14 at 19:41
  • Try insertBefore to insert every node before that one. Maybe it is not buggy. Btw. if you find an msie bug why don't you report it? – inf3rno Sep 26 '14 at 19:45
  • 1
    Can you provide a test case? I've tried http://jsfiddle.net/7po8tdka/1 and http://jsfiddle.net/7po8tdka/2 on IE 11.0.9600.17280 and am unable to reproduce the issue. – Oleg Sep 26 '14 at 21:00
  • I've also tried with svg rectangles: http://jsfiddle.net/7po8tdka/4/ and http://jsfiddle.net/7po8tdka/5/ and with `` elements http://jsfiddle.net/7po8tdka/6/ and it works fine... – Oleg Sep 26 '14 at 21:18
  • What version of IE are you running? – Dom Sep 27 '14 at 00:26

3 Answers3

4

Single event listener on parent element, or higher DOM ancestor:

There is a relatively easy solution which I did not originally mention because I had assumed you had dismissed it as not feasible in your situation. That solution is that instead of multiple listeners each on a single child element, you have a single listener on an ancestor element which gets called for all events of a type on its children. It can be designed to quickly choose to further process based on the event.target, event.target.id, or, better, event.target.className (with a specific class of your creation assigned if the element is a valid target for the event handler). Depending on what your event handlers are doing and the percentage of elements under the ancestor on which you already are using listeners, a single event handler is arguably the better solution. Having a single listener potentially reduces the overhead of event handling. However, any actual performance difference depending on what you are doing in the event handlers and on what percentage of the ancestor's children on which you would have otherwise placed listeners.

Event listeners on elements actually interested in

Your question asks about listeners which your code has placed on the element being moved. Given that you do not appear concerned about listeners placed on the element by code which you do not control, then the brute-force method of working around this is for you to keep a list of listeners and the elements upon which you have placed them.

The best way to implement this brute-force workaround depends greatly on the way in which you place listeners on the elements, the variety that you use, etc. This is all information which is not available to us from the question. Without that information it is not possible to make a known-good choice of how to implement this.

Using only single listeners of each type/namespace all added through selection.on():

If you have a single listener of each type.namespace, and you have added them all through the d3.selection.on() method, and you are not using Capture type listeners, then it is actually relatively easy.

When using only a single listener of each type, the selection.on() method allows you to read the listener which is assigned to the element and type.

Thus, your moveToFront() method could become:

var isIE = /*@cc_on!@*/false || !!document.documentMode; // At least IE6
var typesOfListenersUsed = [ "click", "command", "mouseover", "mouseleave", ...];

d3.selection.prototype.moveToFront = function () {
  return this.each(function () {
    var currentListeners={};
    if(isIE) {
      var element = this;
      typesOfListenersUsed.forEach(function(value){
         currentListeners[value] = element.selection.on(value);
      });
    }
    this.parentNode.appendChild(this);
    if(isIE) {
      typesOfListenersUsed.forEach(function(value){
         if(currentListeners[value]) { 
           element.selection.on(value, currentListeners[value]);
         }
      });
    }
  });
};

You do not necessarily need to check for IE, as it should not hurt to re-place the listeners in other browsers. However, it would cost time, and is better not to do it.

You should be able to use this even if you are using multiple listeners of the same type by just specifying a namespace in the list of listeners. For example:

var typesOfListenersUsed = [ "click", "click.foo", "click.bar"
                            , "command", "mouseover", "mouseleave", ...];

General, multiple listeners of same type:

If you are using listeners which you are adding not through d3, then you would need to implement a general method of recording the listeners added to an element.

How to record the function being added as a listener, you can just add a method to the prototype which records the event you are adding as a listener. For example:

d3.selection.prototype.recOn = function (type, func) {
  recordEventListener(this, type, func);
  d3.select(this).on(type,func);
};

Then use d3.select(el).recOn('mouseleave',function(){}) instead of d3.select(el).on('mouseleave',function(){}).

Given that you are using a general solution because you are adding some listeners not through d3, you will need to add functions to wrap the calls to however you are adding the listener (e.g. addEventListener()).

You would then need a function which you call after the appendChild in your moveToFront(). It could contain the if statement to only restore the listeners if the browser is IE11, or IE.

d3.selection.prototype.restoreRecordedListeners = function () {
    if(isIE) {
        ...
    }
};

You will need to chose how to store the recorded listener information. This depends greatly on how you have implemented other areas of your code of which we have no knowledge. Probably the easiest way to record which listeners are on an element is to create an index into the list of listeners which is then recorded as a class. If the number of actual different listener functions you use is small, this could be a statically defined list. If the number and variety is large, then it could be a dynamic list.

I can expand on this, but how robust to make it really depends on your code. It could be as simple as keeping tack of only 5-10 actually different functions which you use as listeners. It might need to be as robust as to be a complete general solution to record any possible number of listeners. That depends on information we do not know about your code.

My hope is that someone else will be able to provide you with a simple and easy fix for IE11 where you just set some property, or call some method to get IE to not drop the listeners. However, the brute-force method will solve the problem.

Community
  • 1
  • 1
Makyen
  • 31,849
  • 12
  • 86
  • 121
3

One solution could be to use event delegation. This fairly simple paradigm is commonplace in jQuery (which gave me the idea to try it here.)

By extending the d3.selection prototype with a delegated event listener we can listen for events on a parent element but only apply the handler if the event's target is also our desired target.

So instead of:

d3.select('#targetElement').on('mouseout',function(){})

You would use:

d3.select('#targetElementParent').delegate('mouseout','#targetElement',function(){})

Now it doesn't matter if the events are lost when you move elements or even if you add/edit/delete elements after creating the listeners.

Here's the demo. Tested on Chrome 37, IE 11 and Firefox 31. I welcome constructive feedback but please note that I am not at all familiar with d3.js so could easily have missed something fundamental ;)

//prototype. delegated events
d3.selection.prototype.delegate = function(event, targetid, handler) {
    return this.on(event, function() {
        var eventTarget = d3.event.target.parentNode,
            target = d3.select(targetid)[0][0];
        if (eventTarget === target) {//only perform event handler if the eventTarget and intendedTarget match
            handler.call(eventTarget, eventTarget.__data__);
        }
    });
};    
//add event listeners insead of .on() 
d3.select('#svg').delegate('mouseover','#g2',function(){
    console.log('mouseover #g2');
}).delegate('mouseout','#g2',function(){
    console.log('mouseout #g2');
})    
//initial move to front to test that the event still works
d3.select('#g2').moveToFront();

http://jsfiddle.net/f8bfw4y8/

Updated and Improved...

Following Makyen's useful feedback I have made a few improvements to allow the delegated listener to be applied to ALL matched children. EG "listen for mouseover on each g within svg"

Here's the fiddle. Snippet below.

//prototype. move to front
d3.selection.prototype.moveToFront = function () {
  return this.each(function () {
    this.parentNode.appendChild(this);
  });
};

//prototype. delegated events
d3.selection.prototype.delegate = function(event, targetselector, handler) {
    var self = this;
    return this.on(event, function() {
        var eventTarget = d3.event.target,
            target = self.selectAll(targetselector);
        target.each(function(){ 
            //only perform event handler if the eventTarget and intendedTarget match
            if (eventTarget === this) {
                handler.call(eventTarget, eventTarget.__data__);
            } else if (eventTarget.parentNode === this) {
                handler.call(eventTarget.parentNode, eventTarget.parentNode.__data__);
            }
        });
    });
};


var testmessage = document.getElementById("testmessage");
//add event listeners insead of .on() 
//EG: onmouseover/out of ANY <g> within #svg:
d3.select('#svg').delegate('mouseover','g',function(){
    console.log('mouseover',this);
    testmessage.innerHTML = "mouseover #"+this.id;
}).delegate('mouseout','g',function(){
    console.log('mouseout',this);
    testmessage.innerHTML = "mouseout #"+this.id;
});

/* Note: Adding another .delegate listener REPLACES any existing listeners of this event on this node. Uncomment this to see. 
//EG2 onmouseover of just the #g3
d3.select('#svg').delegate('mouseover','#g3',function(){
    console.log('mouseover of just #g3',this);
    testmessage.innerHTML = "mouseover #"+this.id;
});
//to resolve this just delegate the listening to another parent node eg:
//d3.select('body').delegate('mouseover','#g3',function(){...
*/


//initial move to front for testing. OP states that the listener is lost after the element is moved in the DOM.
d3.select('#g2').moveToFront();
svg {height:300px; width:300px;}
rect {fill: pink;}
#g2 rect {fill: green;}
#testmessage {position:absolute; top:50px; right:50px;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<svg id="svg">
    <g id="g1"><rect x="0px" y="0px" width="100px" height="100px" /></g>
    <g id="g2"><rect x="50px" y="50px" width="100px" height="100px" /></g>
    <g id="g3"><rect x="100px" y="100px" width="100px" height="100px" /></g>
</svg>
<div id="testmessage"></div>

As with all delegated listeners if you move the target element outside of the parent you have delegated the listening to then naturally the events for that child are lost. However, there is nothing to stop you delegating the event listening to the body tag as you'll never move a child outside of that. EG:

d3.select('body').delegate('mouseover','g',function(){...
Moob
  • 14,420
  • 1
  • 34
  • 47
  • Should the squares in the fiddle raise on top of others on mouseover? – Sergei Basharov Sep 30 '14 at 20:33
  • No. The demo just logs a message to the Console on mouseover/out of #g2 but you could call moveToFront on mouseover instead http://jsfiddle.net/f8bfw4y8/5/ – Moob Sep 30 '14 at 21:09
  • A few issues: A) the element we want to listen for must never move out from under its original parent element. B) permits only one watched element per parent (the d3 `selection.on()` permits only one listener per event type per element. C) You could get around (B) if you use namespaces, but if you have multiple elements being listened for under the same parent *every single listener* will be called for *every* event (you might (d3 implementation dependent) reduce loading by `event.stopPropagation()` (not available in IE<9), which would give an average of N/2 event handlers called each event). – Makyen Oct 01 '14 at 08:13
  • @Makyen Thanks for the feedback. I have addressed these issues thus: A) The delegated listener can be ANY parent - even the `body`. B) Updated to allow listeners on all matched children – Moob Oct 01 '14 at 09:59
  • Better. However, in an event handler you should not have the extra DOM walk `.selectAll()` requires. Event handlers should be *as fast as possible, even if that sacrifices a bit of generalization*. That is why something like this does not already exist as part of d3; it is bad practice. Much better to assign a unique property (e.g. class) to the active targets and use one access to `event.target.className` to choose go/no go. If generalization, you should also implement passing `null` (remove all listeners) and `undefined` (return the current listener) as is for `selection.on()`. – Makyen Oct 01 '14 at 16:21
  • An alternate method of determining if the event.target matches the selector would be to use [`Element.matches()`](https://developer.mozilla.org/en-US/docs/Web/API/Element.matches). Note that it is non-standard; requires use the of browser specific calls (if using this, choose the browser specific method name when setting up the listener, not on each event); also note the compatibility table at the link. – Makyen Oct 01 '14 at 16:28
  • BTW: `var eventTarget = d3.event.target.parentNode,` should be `var eventTarget = d3.event.target,`. You are currently only ever calling the handler on the parentNode when the parentNode matches the selector. – Makyen Oct 01 '14 at 16:35
  • @Makyen Hmm, not sure about this one. In my testing `d3.event.target` is the `` so I'm using `d3.event.target.parentNode` to get the `` - which is what we're looking for in the selector. I could update it so it calls the callback if the event target OR its parent match the selector. eg: http://jsfiddle.net/moob/f8bfw4y8/11/ I'm not sure if this has any negative repercussions... – Moob Oct 01 '14 at 17:32
  • @Makyen - I've updated my answer to account for this. – Moob Oct 01 '14 at 17:44
  • Hmmm.. You have a point. Actually what needs to be tested for is if the event.target matches the selector, or if *any* descendent of the node matching the selector is the `event.target` ([`Node.contains()`](https://developer.mozilla.org/en-US/docs/Web/API/Node.contains)]. An event would normally propagate down the DOM with the event handler being called for each ancestor of the `event.target`. Thus, the expected functionality would be that the event handler is called if the target is any descendant. – Makyen Oct 01 '14 at 17:52
  • Note that using this method might result in handlers being called out of DOM propagation order if listeners have been applied using methods other than this one. This method will call them in DOM order (top->bottom) for those set up through this method due to [`selectAll()`](https://github.com/mbostock/d3/wiki/Selections#on) operating in DOM order. The point is that this is not a direct replacement for putting a handler on a particular element. It is really that you are re-architecting to use a single handler to deal with a type of event happening on descendants (which is a normal practice). – Makyen Oct 01 '14 at 18:08
3

This also happens in IE prior to 11. My mental model for why this error occurs is that if you're hovering over an element and then move it to the front by detaching and re-attaching it, mouseout events won't fire because IE loses the state that a mouseover occured in the past and thus doesn't fire a mouseout event.

This seems to be why it works fine if you move all other elements but the one you're hovering over. And this is what you can easily achieve by using selection.sort(comparatorFunction). See the d3 documentation on sort and the selection.sort and selection.order source code for further details.

Here's a simple example:

// myElements is a d3 selection of, for example, circles that overlap each other
myElements.on('mouseover', function(hoveredDatum) {
  // On mouseover, the currently hovered element is sorted to the front by creating
  // a custom comparator function that returns “1” for the hovered element and “0”
  // for all other elements to not affect their sort order.
  myElements.sort(function(datumA, datumB) {
    return (datumA === hoveredDatum) ? 1 : 0;
  });
});
petergassner
  • 486
  • 4
  • 8