YUI 3.x Home -

YUI Library Examples: Drag & Drop: Photo Browser

Drag & Drop: Photo Browser

This example uses DD and YQL to build a Photo Browser application. This example was part of the YUI 3 presentation by Dav Glass at Open Hack : London

Drag & Drop

In this example, Drag & Drop is heavily customized by using event bubbling and custom proxies.

When you see Y.DD.DDM.on in the code, you are seeing the built-in event bubbling.

The DD dragNode is the proxy node, we add some styles to it allowing it to look the way we want.

YQL

Here is the Flickr YQL query used in this example.

  1. SELECT * FROM flickr.photos.search(100) WHERE
  2. (text="yuiconf")
  3. AND (safe_search = 1)
  4. AND (media = "photos")
SELECT * FROM flickr.photos.search(100) WHERE
    (text="yuiconf")
AND (safe_search = 1)
AND (media = "photos")

Slider and StyleSheet

In this example, we will use the Slider control to dynamically manipulate a CSS Style Rule.

First, we need to create the slider and render it.

  1. //Create and render the slider
  2. var sl = new Y.Slider({
  3. length: '200px', value: 40, max: 70, min: 5
  4. }).render('.horiz_slider');
//Create and render the slider
var sl = new Y.Slider({
    length: '200px', value: 40, max: 70, min: 5
}).render('.horiz_slider');

Now, we listen for the Slider's valueChange event. This event is fired when the value of the Slider has changed.

Next we use the StyleSheet utility to dynamically change a style rule to resize the images. The style rule that we want to change is #yui-main .yui-g ul li. When the Slider's value changes, we will take the value and divide it by 2, then use that as the percentage width of the li. This will give us the effect we want (resizing images) without touching all the images via the DOM.

  1. //Listen for the change
  2. sl.after('valueChange',function (e) {
  3. //Insert a dynamic stylesheet rule:
  4. var sheet = new Y.StyleSheet('image_slider');
  5. sheet.set('#yui-main .yui-g ul li', {
  6. width: (e.newVal / 2) + '%'
  7. });
  8. });
//Listen for the change
sl.after('valueChange',function (e) {
    //Insert a dynamic stylesheet rule:
    var sheet = new Y.StyleSheet('image_slider');
    sheet.set('#yui-main .yui-g ul li', {
        width: (e.newVal / 2) + '%'
    });
});

Event Delegation

This listener listens for all mouseup events on the document and it will only fire when the target element matches the * selector (which should be all elements).

This way we can remove all the selected CSS classes from all the images in the browser when a mouseup occurs, only if the shift key was not pressed. We can then check to determine if the mouseup came from one of the images. If it has, add the selected class back to it.

  1. //Listen for all mouseups on the document (selecting/deselecting images)
  2. Y.delegate('mouseup' , function(e) {
  3. if (!e.shiftKey) {
  4. //No shift key - remove all selected images
  5. wrapper.all('img.selected').removeClass('selected');
  6. }
  7. //Check if the target is an image and select it.
  8. if (e.target.test('#yui-main .yui-g ul li img')) {
  9. e.target.addClass('selected');
  10. }
  11. }, document, '*');
//Listen for all mouseups on the document (selecting/deselecting images)
Y.delegate('mouseup' , function(e) {
    if (!e.shiftKey) {
        //No shift key - remove all selected images
        wrapper.all('img.selected').removeClass('selected');
    }
    //Check if the target is an image and select it.
    if (e.target.test('#yui-main .yui-g ul li img')) {
        e.target.addClass('selected');
    }
}, document, '*');    

This listener, listens for all click events on the album list #photoList li. First, it stops the click, so the href is not followed. Next, it removes all the selected classes from the list. Then, it adds the selected class to the item that was clicked on.

After that UI setup, it uses Selectors to change the view of the images in the browser. First, it checks if we are viewing "all" or a "sub album". If all is selected, it removes the hidden class from all the images. If it was an album, it adds the hidden class to all the images, then selects all the images with the class of its id, then it removes the hidden class from them.

Basically, it hides all the images, then determines the ones it needs to show and removes the hidden class from them.

  1. //Listen for all clicks on the '#photoList li' selector
  2. Y.delegate('click', function(e) {
  3. //Prevent the click
  4. e.halt();
  5. //Remove all the selected items
  6. e.currentTarget.get('parentNode').all('li.selected').removeClass('selected');
  7. //Add the selected class to the one that one clicked
  8. e.currentTarget.addClass('selected');
  9. //The "All Photos" link was clicked
  10. if (e.currentTarget.hasClass('all')) {
  11. //Remove all the hidden classes
  12. wrapper.all('li').removeClass('hidden');
  13. } else {
  14. //Another "album" was clicked, get its id
  15. var c = e.target.get('id');
  16. //Hide all items by adding the hidden class
  17. wrapper.all('li').addClass('hidden');
  18. //Now, find all the items with the class name the same as the album id
  19. //and remove the hidden class
  20. wrapper.all('li.' + c).removeClass('hidden');
  21. }
  22. }, document, '#photoList li');
//Listen for all clicks on the '#photoList li' selector
Y.delegate('click', function(e) {
    //Prevent the click
    e.halt();
    //Remove all the selected items
    e.currentTarget.get('parentNode').all('li.selected').removeClass('selected');
    //Add the selected class to the one that one clicked
    e.currentTarget.addClass('selected');
    //The "All Photos" link was clicked
    if (e.currentTarget.hasClass('all')) {
        //Remove all the hidden classes
        wrapper.all('li').removeClass('hidden');
    } else {
        //Another "album" was clicked, get its id
        var c = e.target.get('id');
        //Hide all items by adding the hidden class
        wrapper.all('li').addClass('hidden');
        //Now, find all the items with the class name the same as the album id
        //and remove the hidden class
        wrapper.all('li.' + c).removeClass('hidden');
    }
}, document, '#photoList li');

Full Source

Here is the full commented JavaScript source for this example.

  1. YUI().use('yql', 'node', 'anim', 'dd', 'dd-plugin', 'dd-drop-plugin', 'slider', 'stylesheet', 'event-delegate', function(Y) {
  2. //Get a reference to the wrapper to use later and add a loading class to it.
  3. var wrapper = Y.one('#yui-main .yui-g ul').addClass('loading');
  4. //Set its height to the height of the viewport so we can scroll it.
  5. wrapper.setStyle('height', (wrapper.get('winHeight') - 50 )+ 'px');
  6. Y.on('windowresize', function() { wrapper.setStyle('height', (wrapper.get('winHeight') - 50 )+ 'px'); });
  7. //Make the YQL query.
  8. Y.YQL('select * from flickr.photos.search(100) where text="openhacklondon" and safe_search = 1 and media = "photos" and extras = "o_dims" and ((o_width = "1600" and o_height = "1200") or (o_width = "1200" and o_height = "1600") or (o_width = "800" and o_height = "600") or (o_width = "600" and o_height = "800"))', function(e) {
  9. if (e.query) {
  10. var photos = e.query.results.photo;
  11. //Walk the returned photos array
  12. Y.each(photos, function(v, k) {
  13. //Create our URL
  14. var url = 'http:/'+'/static.flickr.com/' + v.server + '/' + v.id + '_' + v.secret + '_m.jpg',
  15. //Create the image and the LI
  16. li = Y.Node.create('<li class="loading"><img src="' + url + '" title="' + v.title + '"></li>'),
  17. //Get the image from the LI
  18. img = li.get('firstChild');
  19. //Append the li to the wrapper
  20. wrapper.appendChild(li);
  21. //This little hack moves the tall images to the bottom of the list
  22. //So they float better ;)
  23. img.on('load', function() {
  24. //Is the height longer than the width?
  25. var c = ((this.get('height') > this.get('width')) ? 'tall' : 'wide');
  26. this.addClass(c);
  27. if (c === 'tall') {
  28. //Move it to the end of the list.
  29. this.get('parentNode.parentNode').removeChild(this.get('parentNode'));
  30. wrapper.appendChild(this.get('parentNode'));
  31. }
  32. this.get('parentNode').removeClass('loading');
  33. });
  34. });
  35. //Get all the newly added li's
  36. wrapper.all('li').each(function(node) {
  37. //Plugin the Drag plugin
  38. this.plug(Y.Plugin.Drag, {
  39. offsetNode: false
  40. });
  41. //Plug the Proxy into the DD object
  42. this.dd.plug(Y.Plugin.DDProxy, {
  43. resizeFrame: false,
  44. moveOnEnd: false,
  45. borderStyle: 'none'
  46. });
  47. });
  48. //Create and render the slider
  49. var sl = new Y.Slider({
  50. length: '200px', value: 40, max: 70, min: 5
  51. }).render('.horiz_slider');
  52. //Listen for the change
  53. sl.after('valueChange',function (e) {
  54. //Insert a dynamic stylesheet rule
  55. var sheet = new Y.StyleSheet('image_slider');
  56. sheet.set('#yui-main .yui-g ul li', {
  57. width: (e.newVal / 2) + '%'
  58. });
  59. });
  60. //Remove the DDM as a bubble target..
  61. sl._dd.removeTarget(Y.DD.DDM);
  62. //Remove the wrappers loading class
  63. wrapper.removeClass('loading');
  64. Y.one('#ft').removeClass('loading');
  65. }
  66. });
  67. //Listen for all mouseups on the document (selecting/deselecting images)
  68. Y.delegate(function(e) {
  69. if (!e.shiftKey) {
  70. //No shift key - remove all selected images
  71. wrapper.all('img.selected').removeClass('selected');
  72. }
  73. //Check if the target is an image and select it.
  74. if (e.target.test('#yui-main .yui-g ul li img')) {
  75. e.target.addClass('selected');
  76. }
  77. }, document, 'mouseup', '*');
  78. //Listen for all clicks on the '#photoList li' selector
  79. Y.delegate(function(e) {
  80. //Prevent the click
  81. e.halt();
  82. //Remove all the selected items
  83. e.currentTarget.get('parentNode').all('li.selected').removeClass('selected');
  84. //Add the selected class to the one that one clicked
  85. e.currentTarget.addClass('selected');
  86. //The "All Photos" link was clicked
  87. if (e.currentTarget.hasClass('all')) {
  88. //Remove all the hidden classes
  89. wrapper.all('li').removeClass('hidden');
  90. } else {
  91. //Another "album" was clicked, get its id
  92. var c = e.currentTarget.get('id');
  93. //Hide all items by adding the hidden class
  94. wrapper.all('li').addClass('hidden');
  95. //Now, find all the items with the class name the same as the album id
  96. //and remove the hidden class
  97. wrapper.all('li.' + c).removeClass('hidden');
  98. }
  99. }, document, 'click', '#photoList li');
  100. //Stop the drag with the escape key
  101. Y.one(document).on('keyup', function(e) {
  102. //The escape key was pressed
  103. if ((e.keyCode === 27) || (e.charCode === 27)) {
  104. //We have an active Drag
  105. if (Y.DD.DDM.activeDrag) {
  106. //Stop the drag
  107. Y.DD.DDM.activeDrag.stopDrag();
  108. }
  109. }
  110. });
  111. //On the drag:mouseDown add the selected class
  112. Y.DD.DDM.on('drag:mouseDown', function(e) {
  113. var img = e.target.get('node').one('img');
  114. //If it's a gesture event, then we need to act differently
  115. if (Y.DD.Drag.START_EVENT.indexOf('gesture') === 0) {
  116. if (img.hasClass('selected')) {
  117. img.removeClass('selected');
  118. } else {
  119. img.addClass('selected');
  120. }
  121. } else {
  122. img.removeClass('selected');
  123. }
  124.  
  125. });
  126. //On drag start, get all the selected elements
  127. //Add the count to the proxy element and offset it to the cursor.
  128. Y.DD.DDM.on('drag:start', function(e) {
  129. //How many items are selected
  130. var count = wrapper.all('img.selected').size();
  131. //Set the style on the proxy node
  132. e.target.get('dragNode').setStyles({
  133. height: '25px', width: '25px'
  134. }).set('innerHTML', '<span>' + count + '</span>');
  135. //Offset the dragNode
  136. e.target.deltaXY = [25, 5];
  137. });
  138. //We dropped on a drop target
  139. Y.DD.DDM.on('drag:drophit', function(e) {
  140. //get the images that are selected.
  141. var imgs = wrapper.all('img.selected'),
  142. //The xy position of the item we dropped on
  143. toXY = e.drop.get('node').getXY();
  144.  
  145. imgs.each(function(node) {
  146. //Clone the image, position it on top of the original and animate it to the drop target
  147. node.get('parentNode').addClass(e.drop.get('node').get('id'));
  148. var n = node.cloneNode().set('id', '').setStyle('position', 'absolute');
  149. Y.one('body').appendChild(n);
  150. n.setXY(node.getXY());
  151. new Y.Anim({
  152. node: n,
  153. to: {
  154. height: 20, width: 20, opacity: 0,
  155. top: toXY[1], left: toXY[0]
  156. },
  157. from: {
  158. width: node.get('offsetWidth'),
  159. height: node.get('offsetHeight')
  160. },
  161. duration: .5
  162. }).run();
  163. });
  164. //Update the count
  165. var count = wrapper.all('li.' + e.drop.get('node').get('id')).size();
  166. e.drop.get('node').one('span').set('innerHTML', '(' + count + ')');
  167. });
  168. //Add drop support to the albums
  169. Y.all('#photoList li').each(function(node) {
  170. if (!node.hasClass('all')) {
  171. //make all albums Drop Targets except the all photos.
  172. node.plug(Y.Plugin.Drop);
  173. }
  174. });
  175. });
YUI().use('yql', 'node', 'anim', 'dd', 'dd-plugin', 'dd-drop-plugin', 'slider', 'stylesheet', 'event-delegate', function(Y) {
    //Get a reference to the wrapper to use later and add a loading class to it.
    var wrapper = Y.one('#yui-main .yui-g ul').addClass('loading');
    //Set its height to the height of the viewport so we can scroll it.
    wrapper.setStyle('height', (wrapper.get('winHeight') - 50 )+ 'px');
    Y.on('windowresize', function() { wrapper.setStyle('height', (wrapper.get('winHeight') - 50 )+ 'px'); });
    //Make the YQL query.
    Y.YQL('select * from flickr.photos.search(100) where text="openhacklondon" and safe_search = 1 and media = "photos" and extras = "o_dims" and ((o_width = "1600" and o_height = "1200") or (o_width = "1200" and o_height = "1600") or (o_width = "800" and o_height = "600") or (o_width = "600" and o_height = "800"))', function(e) {
        if (e.query) {
            var photos = e.query.results.photo;
            //Walk the returned photos array
            Y.each(photos, function(v, k) {
                //Create our URL
                var url = 'http:/'+'/static.flickr.com/' + v.server + '/' + v.id + '_' + v.secret + '_m.jpg',
                    //Create the image and the LI
                    li = Y.Node.create('<li class="loading"><img src="' + url + '" title="' + v.title + '"></li>'),
                    //Get the image from the LI
                    img = li.get('firstChild');
                //Append the li to the wrapper
                wrapper.appendChild(li);
                //This little hack moves the tall images to the bottom of the list
                //So they float better ;)
                img.on('load', function() {
                    //Is the height longer than the width?
                    var c = ((this.get('height') > this.get('width')) ? 'tall' : 'wide');
                    this.addClass(c);
                    if (c === 'tall') {
                        //Move it to the end of the list.
                        this.get('parentNode.parentNode').removeChild(this.get('parentNode'));
                        wrapper.appendChild(this.get('parentNode'));
                    }
                    this.get('parentNode').removeClass('loading');
                });
            });
            //Get all the newly added li's
            wrapper.all('li').each(function(node) {
                //Plugin the Drag plugin
                this.plug(Y.Plugin.Drag, {
                    offsetNode: false
                });
                //Plug the Proxy into the DD object
                this.dd.plug(Y.Plugin.DDProxy, {
                    resizeFrame: false,
                    moveOnEnd: false,
                    borderStyle: 'none'
                });
            });
            //Create and render the slider
            var sl = new Y.Slider({
                length: '200px', value: 40, max: 70, min: 5
            }).render('.horiz_slider');
            //Listen for the change
            sl.after('valueChange',function (e) {
                //Insert a dynamic stylesheet rule
                var sheet = new Y.StyleSheet('image_slider');
                sheet.set('#yui-main .yui-g ul li', {
                    width: (e.newVal / 2) + '%'
                });
            });
            //Remove the DDM as a bubble target..
            sl._dd.removeTarget(Y.DD.DDM);
            //Remove the wrappers loading class
            wrapper.removeClass('loading');
            Y.one('#ft').removeClass('loading');
        }
    });
    //Listen for all mouseups on the document (selecting/deselecting images)
    Y.delegate(function(e) {
        if (!e.shiftKey) {
            //No shift key - remove all selected images
            wrapper.all('img.selected').removeClass('selected');
        }
        //Check if the target is an image and select it.
        if (e.target.test('#yui-main .yui-g ul li img')) {
            e.target.addClass('selected');
        }
    }, document, 'mouseup', '*');    
    //Listen for all clicks on the '#photoList li' selector
    Y.delegate(function(e) {
        //Prevent the click
        e.halt();
        //Remove all the selected items
        e.currentTarget.get('parentNode').all('li.selected').removeClass('selected');
        //Add the selected class to the one that one clicked
        e.currentTarget.addClass('selected');
        //The "All Photos" link was clicked
        if (e.currentTarget.hasClass('all')) {
            //Remove all the hidden classes
            wrapper.all('li').removeClass('hidden');
        } else {
            //Another "album" was clicked, get its id
            var c = e.currentTarget.get('id');
            //Hide all items by adding the hidden class
            wrapper.all('li').addClass('hidden');
            //Now, find all the items with the class name the same as the album id
            //and remove the hidden class
            wrapper.all('li.' + c).removeClass('hidden');
        }
    }, document, 'click', '#photoList li');
    //Stop the drag with the escape key
    Y.one(document).on('keyup', function(e) {
        //The escape key was pressed
        if ((e.keyCode === 27) || (e.charCode === 27)) {
            //We have an active Drag
            if (Y.DD.DDM.activeDrag) {
                //Stop the drag
                Y.DD.DDM.activeDrag.stopDrag();
            }
        }
    });
    //On the drag:mouseDown add the selected class
    Y.DD.DDM.on('drag:mouseDown', function(e) {
        var img = e.target.get('node').one('img');
        //If it's a gesture event, then we need to act differently
        if (Y.DD.Drag.START_EVENT.indexOf('gesture') === 0) {
            if (img.hasClass('selected')) {
                img.removeClass('selected');
            } else {
                img.addClass('selected');
            }
        } else {
            img.removeClass('selected');
        }
 
    });
    //On drag start, get all the selected elements
    //Add the count to the proxy element and offset it to the cursor.
    Y.DD.DDM.on('drag:start', function(e) {
        //How many items are selected
        var count = wrapper.all('img.selected').size();
        //Set the style on the proxy node
        e.target.get('dragNode').setStyles({
            height: '25px', width: '25px'
        }).set('innerHTML', '<span>' + count + '</span>');
        //Offset the dragNode
        e.target.deltaXY = [25, 5];
    });
    //We dropped on a drop target
    Y.DD.DDM.on('drag:drophit', function(e) {
        //get the images that are selected.
        var imgs = wrapper.all('img.selected'),
            //The xy position of the item we dropped on
            toXY = e.drop.get('node').getXY();
 
        imgs.each(function(node) {
            //Clone the image, position it on top of the original and animate it to the drop target
            node.get('parentNode').addClass(e.drop.get('node').get('id'));
            var n = node.cloneNode().set('id', '').setStyle('position', 'absolute');
            Y.one('body').appendChild(n);
            n.setXY(node.getXY());
            new Y.Anim({
                node: n,
                to: {
                    height: 20, width: 20, opacity: 0,
                    top: toXY[1], left: toXY[0]
                },
                from: {
                    width: node.get('offsetWidth'),
                    height: node.get('offsetHeight')
                },
                duration: .5
            }).run();
        });
        //Update the count
        var count = wrapper.all('li.' + e.drop.get('node').get('id')).size();
        e.drop.get('node').one('span').set('innerHTML', '(' + count + ')');
    });
    //Add drop support to the albums
    Y.all('#photoList li').each(function(node) {
        if (!node.hasClass('all')) {
            //make all albums Drop Targets except the all photos.
            node.plug(Y.Plugin.Drop);
        }
    });
});

Copyright © 2011 Yahoo! Inc. All rights reserved.

Privacy Policy - Terms of Service - Copyright Policy - Job Openings