Make sure to insert your code into the following section:
var countDrops = 0;
window.onload = function(){
//your code
}
Additionally, for the drop event, use the following code snippet:
addEvent(bin, 'drop', function (e) {
if (e.stopPropagation) e.stopPropagation(); // prevents browser redirection
/* COUNTER */
countDrops++;
alert(countDrops);
The error occurred because you were trying to assign events to the list of links before the elements such as divs and links were loaded.
By using window.onload, the script waits for all HTML content to be ready before assigning 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];
// is 'draggable' even required? Specification says yes, but 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 drop
this.className = 'over';
return false;
});
addEvent(bin, 'dragleave', function () {
this.className = '';
});
addEvent(bin, 'drop', function (e) {
if (e.stopPropagation) e.stopPropagation(); // stops the browser from redirecting...why???
/* COUNTER */
countDrops++;
alert(countDrops);
var el = document.getElementById(e.dataTransfer.getData('Text'));
el.parentNode.removeChild(el);
// animate nom text with 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) { // omit animation
y.style.display = 'none';
}
clearInterval(t);
} else {
y.style.opacity -= 0.1;
}
}, 50);
}, 250);
return false;
});
}