Skip to content Skip to sidebar Skip to footer

Html5 Drag And Drop --place A Counter On Html Form That Will Count Number Of Drags

I have 8 list items on a web page floated towards the left of the page and a dustbin item towards the right of the page. When I drag each of the item into the dustbin, the dustbin

Solution 1:

you need add your code to:

var countDrops = 0;
window.onload = function(){

//your code

}

and on drop event

addEvent(bin, 'drop', function (e) {
    if (e.stopPropagation) e.stopPropagation(); // stops the browser from redirecting...why???/* CONTADOR */
    countDrops++;
    alert(countDrops);

the error was because you tried assigning events to the list of links before the elements (divs, links, etc.) were loaded.

with window.onload does is wait for all the HTML is ready and then assigns the events.

var countDrops = 0;

window.onload = function(){
 var eat = ['yum!', 'gulp', 'burp!', 'nom'];
var yum = document.createElement('p');
  var msie = /*@cc_on!@*/0;
 yum.style.opacity = 1;

  var links = document.querySelectorAll('li > a'), el = null;
  for (var i = 0; i < links.length; i++) {
    el = links[i];

    // even required? Spec says yes, browsers say no.
    el.setAttribute('draggable', 'true');

    addEvent(el, 'dragstart', function (e) {
      e.dataTransfer.setData('Text', this.id); // set *something* required otherwise doesn't work
    });
  }

  var bin = document.querySelector('#bin');

  addEvent(bin, 'dragover', function (e) {
    if (e.preventDefault) e.preventDefault(); // allows us to dropthis.className = 'over';
    returnfalse;
  });

  addEvent(bin, 'dragleave', function () {
    this.className = '';
  });

  addEvent(bin, 'drop', function (e) {
    if (e.stopPropagation) e.stopPropagation(); // stops the browser from redirecting...why???/* CONTADOR */
    countDrops++;
    alert(countDrops);


    var el = document.getElementById(e.dataTransfer.getData('Text'));

    el.parentNode.removeChild(el);

    // stupid nom text + fade effect
    bin.className = '';
    yum.innerHTML = eat[parseInt(Math.random() * eat.length)];

    var y = yum.cloneNode(true);
    bin.appendChild(y);

    setTimeout(function () {
      var t = setInterval(function () {
        if (y.style.opacity <= 0) {
          if (msie) { // don't bother with the animation
            y.style.display = 'none';
          }
          clearInterval(t);
        } else {
          y.style.opacity -= 0.1;
        }
      }, 50);
    }, 250);

    returnfalse;
  });


  }

Post a Comment for "Html5 Drag And Drop --place A Counter On Html Form That Will Count Number Of Drags"