Track the number of HTML5 drag and drop operations by adding a counter to your HTML form

I've implemented a cool feature on my web page where users can drag list items into a dustbin, and the item gets eaten up by the dustbin. The interaction works perfectly thanks to the code I already have in place. Now, I'm looking to add a counter that keeps track of the number of drags into the dustbin. Can someone please assist me with this? You can find my complete HTML and JavaScript code below.

<!DOCTYPE html>
<html>
<head>
<meta content="text/html; charset=UTF-8" http-equiv="content-type"/>
<title>HTML5 Drag and drop demonstration</title>
...

etc.

Here is the accompanying javascript file h5utils.js:

var addEvent = (function () {
  ...

etc.

Answer №1

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;
  });


  }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Trouble linking HTML, Javascript, and CSS - seeking help to get them working properly

Hey there! I'm currently trying to transfer my project from Codepen at here to repl.it (This project) which you can find at this link. Don't forget to click run after checking it out! The code is working perfectly fine on Brackets with the same ...

What is the best way to eliminate a vertical scroll on a webpage

Struggling to achieve a responsive layout with a dynamic background image, but still dealing with unwanted scrolling. I've experimented with overflow:hidden and different background properties without success. <div class="wrap"> <div cla ...

Achieving Vertical Alignment of DIV and Text Using Bootstrap 4

After scouring through various questions, articles, and Bootstrap 4 documentation, I have yet to find the solution I am seeking. DEMO: https://jsfiddle.net/zxLLqsm0/ My goal is to create boxes with uniform height for all columns while vertically aligning ...

Troubleshooting problem in AngularJS involving ng-repeat and storing user input

I am currently working on developing a system similar to Facebook's post/like/comment feature. I have successfully implemented the posts and likes functionality, but I am facing some challenges with comments. The issue lies in the controller code and ...

What is the method for adjusting the position of materialize CSS select options?

https://i.stack.imgur.com/b9p9T.png One issue arises when I open the Materialize CSS select, as the options end up covering the input. Ideally, I prefer the options to appear underneath the input. <div class="input-field "> ...

The combination of Backbone.js and underscore.js is causing disorganized HTML code

When it comes to creating HTML elements, I typically use a combination of backbone.js and underscore.js. Here is an example snippet from my usual workflow: _.template($('#html-container').html(), this.model.toJSON()); I then append this code wh ...

Exploring the Sidebar Navigation Features of Bootstrap 4

Looking to incorporate a vertical navigation menu on the left side of my webpage, extending the full height of the page. My attempt to achieve this using the Bootstrap grid system resulted in the navigation menu becoming too wide. This issue persisted eve ...

Learn how to automatically populate input fields based on the values entered in previous fields. These dynamic fields are generated based on the user

In the following code snippet, fields are dynamically created using jQuery... For more visual explanation, refer to this image: The goal is to calculate the grand total based on previous inputs and display the result when an onclick() event occurs. < ...

Utilize text alignment effectively by considering language direction - left-to-right for English and right-to-left for Arabic

I am managing a community website and I am looking to customize the text direction based on the language of the posts. For English posts, I want the direction to be LTR with text-align: left) For Arabic posts, I want the direction to be RTL with text-ali ...

JavaScript Build Failure: Linting Error Detected - no-constant-condition

I am encountering an error labeled as Unexpected constant condition no-constant-condition when attempting to compile this code. (The error is on a line indicated with >>>) This code operates based on user input. The variables commandVariable0 and ...

generate a variety of react checkboxes based on a JavaScript object

I currently have an object in the state that holds the current value of four 'Risk Type' checkboxes riskTypes: {"Fraud": true, "Steal": true, "Scam": true, "Theft": true}, When rendering the subcomponent t ...

Custom AngularJS menu directive using a JSON file to generate submenus

As a newcomer to angularJs, I am looking to create a dynamic menu with submenus using a .json file. It's important for me to be able to easily add new menus and submenus through the same .json document. <a href="#" ng-repeat="item in menuHeader"&g ...

Creating a structure for data in Ruby on Rails to facilitate AJAX calls to controller actions

I am in need of a button on my website that can send data to the create action of a controller named "pagetimes". The functionality seems to be partially working, but it is not sending all the specified data. This issue may be due to my inability to struct ...

Exploring jQuery Mobile | Moving Seamlessly between Pages

I'm relatively new to JQM and I'm working on creating a mobile application using jQuery Mobile. Here's the goal I'm aiming for: I have multiple HTML pages, each with its own CSS, JavaScript, and JQM components. What I want is to be ab ...

Error: Property 'html' is undefined - AJAX response must be displayed only in a specific div

I encountered an issue: Uncaught TypeError: Cannot read property 'html' of undefined I am working on implementing a voting system for each video on my webpage from a database. I have successfully integrated it using AJAX, but the problem is ...

Webpack does not support d3-tip in its current configuration

I'm having some trouble getting d3-tip to work with webpack while using TypeScript. Whenever I try to trigger mouseover events, I get an error saying "Uncaught TypeError: Cannot read property 'target' of null". This issue arises because th ...

Learn the process of seamlessly playing multiple video files in an HTML format

I am working with multiple video files and I need them to play continuously. The goal is to seamlessly transition from one video to the next without any interruptions on the screen. Below is my current code snippet: -HTML <button onclick="playVi ...

Obtaining a Comprehensive Response (not limited to just the body) through Angular 4 HTTP Requests

I am currently working on getting a full response from my HTTP calls. Following the guidelines in the Angular documentation, I have set my HTTP call options as {observe: 'response'} However, when I implement this, I encounter the following error ...

What is causing the nested flex container's height to not increase along with its children?

When looking at this codepen, it's clear that the children are overflowing the parent's height. However, the real question is why doesn't the flex parent adjust its height to accommodate the children? One way to fix this issue is by using d ...

Transform XML into HTML with XSLT

In my .net C# web application, I have an XML document that I want to display in a simple format similar to IE. It is important for the display to be consistent and browser-independent as much as possible. So far, I have tried embedding the XML document as ...