Search code examples
htmlcssyui3

Duplicating Element and Children Styling Using YUI3


So I've been cannibalizing this code from this YUI 3 Drag n' Drop tutorial, and it's been working great.

The one issue that I'm running into is that the example code only copies a few of the CSS styles (individually). This also doesn't include styling of any children elements that may be present.

Y.DD.DDM.on('drag:start', function(e) {
  var drag = e.target;

  drag.get('dragNode').set('innerHTML', drag.get('node').get('innerHTML'));

  drag.get('dragNode').setStyles({
    opacity: '.5',
    borderColor: drag.get('node').getStyle('borderColor'),
    backgroundColor: drag.get('node').getStyle('backgroundColor')
  });
});

So when the drag starts, we create a dragNode and set its HTML based on the item being dragged. After the dragNode HTML is set, we then set the styles using .setStyles() which seems to accept an object.

Is there a more effective way of creating this dragNode so that it not only gets the correct HTML, but also gets all the styles of the element and its children?

I know I could use .one() or .all() to get to the children elements and manually copy over each style that is set, but I feel like there has to be a way of doing that without all the manual style copying.


Solution

  • What I ended up finding out was that I was missing a top-level class (which applied the styling to its children elements).

    The fix was surprisingly easy in my case, since I had to only add a single class based on if the element had a specific class or not.

    Y.DD.DDM.on('drag:start', function(e) {
      var drag = e.target;
    
      drag.get('dragNode').set('innerHTML', drag.get('node').get('innerHTML'));
    
      if( drag.get('node').hasClass('policy') ) {
        drag.get('dragNode').addClass('policy');
      } else {
        drag.get('dragNode').addClass('lead');
      }
    
      drag.get('dragNode').setStyles({
        opacity: '.5',
        borderColor: drag.get('node').getStyle('borderColor'),
        backgroundColor: drag.get('node').getStyle('backgroundColor')
      });
    });