Search code examples
javascriptfunctiondrag-and-dropself-invoking-function

2 self-invoking javascript functions running


I have a container which contains a primary image and 2-3 thumbnails each. I wanted the user to be able to change the image by clicking on the thumbnail of its parent. Aside from that, I want the containers to be draggable/sortable so that users can be able to compare them easily.

This is why I made these 2 self invoking functions in my javascript file.

This one is to change the primary image into the image of the thumbnail.

$(document).ready(function(){
  $('.thumb-img').on('click', function(){
    var url = $(this).attr('src');
    $(this).closest('.item-container').find('.primary-img').attr('src', url);
  });
});

While this one is used to drag and drop the containers to interchange positions.

(function() {
  "use strict";
  var dragAndDropModule = function(draggableElements){

    var elemYoureDragging = null
        , dataString        = 'text/html'    
        , elementDragged = null  
        , draggableElementArray = Array.prototype.slice.call(draggableElements) //Turn NodeList into array
        , dragonDrop = {}; //Put all our methods in a lovely object 

        // Change the dataString type since IE doesn't support setData and getData correctly. 
        dragonDrop.changeDataStringForIe = (function () {
            var userAgent = window.navigator.userAgent,
                msie = userAgent.indexOf('MSIE '),       //Detect IE
                trident = userAgent.indexOf('Trident/'); //Detect IE 11

            if (msie > 0 || trident > 0) {
                dataString = 'Text';
                return true;
            } else {
                return false;
            }
        })();


        dragonDrop.bindDragAndDropAbilities = function(elem) {
          elem.setAttribute('draggable', 'true');
          elem.addEventListener('dragstart', dragonDrop.handleDragStartMove, false);
          elem.addEventListener('dragenter', dragonDrop.handleDragEnter, false);
          elem.addEventListener('dragover',  dragonDrop.handleDragOver, false);
          elem.addEventListener('dragleave', dragonDrop.handleDragLeave, false);
          elem.addEventListener('drop',      dragonDrop.handleDrop, false);
          elem.addEventListener('dragend',   dragonDrop.handleDragEnd, false);
        };

        dragonDrop.handleDragStartMove = function(e) {
          var dragImg = document.createElement("img");
          dragImg.src = "http://alexhays.com/i/long%20umbrella%20goerge%20bush.jpeg";

          elementDragged = this;

          e.dataTransfer.effectAllowed = 'move';
          e.dataTransfer.setData(dataString, this.innerHTML);
          //e.dataTransfer.setDragImage(dragImg, 20, 50); //idk about a drag image 
        };

        dragonDrop.handleDragEnter = function(e) {
          if(elementDragged !== this) {
            this.style.border = "2px dashed #3a3a3a";
          }
        };

        dragonDrop.handleDragOver = function(e) {   
          e.preventDefault();
          e.dataTransfer.dropEffect = 'move';     
        };

        dragonDrop.handleDragLeave = function(e) {
          this.style.border = "2px solid transparent";
        };

        dragonDrop.handleDrop = function(e) {
         if(elementDragged !== this) {
            var data = e.dataTransfer.getData(dataString);
            elementDragged.innerHTML = this.innerHTML;
            this.innerHTML = e.dataTransfer.getData(dataString);
          }
          this.style.border = "2px solid transparent";
          e.stopPropagation();
          return false;
        };

        dragonDrop.handleDragEnd = function(e) {
          this.style.border = "2px solid transparent";
        };

        // Actiavte Drag and Dropping on whatever element
        draggableElementArray.forEach(dragonDrop.bindDragAndDropAbilities);
  };

  var allDraggableElements = document.querySelectorAll('.draggable-droppable');
  dragAndDropModule(allDraggableElements);

})();

The two functions work but when I drag the container and change its position, the first function doesn't work anymore.


Solution

  • It's probably because you drag it and recreate the element node.

    you can use Event to solve the problem.

    $(document).ready(function(){
      // It delegate thumb-img event to body, so whatever you recreate thumb-img,is all right
      $('body').on('click', '.thumb-img', function(){
        var url = $(this).attr('src');
        $(this).closest('.item-container').find('.primary-img').attr('src', url);
      });
    });