JavaScript Drag-and-Drop Statement Issues

Currently working on a JavaScript game that utilizes the drag and drop feature of HTML. The goal is to make randomly generated fruit images draggable and droppable onto a jelly image. When the dragged image matches a certain condition (e.g., when the number image array index == x and the fruit image index == y), it should be allowed to drop. To declare this conditional statement, I am retrieving values from the background image (i.e., if the background image of the number is x and the background image of the fruit is y). The code was functioning properly until I introduced a condition, and now the images won't display.

Edit: Attempted to use === instead of =, but still unresponsive.

Edit: After removing the semicolon in a comment, the rest of the code works fine. However, the drag and drop functionality is not responding.

Edit: Tried declaring variables for image URLs instead of using URLs directly in the on drop function, but drag and drop functionality remains non-functional.

// JavaScript code for handling number and fruit images
// Arrays for different images
var myNumber = new Array(9);

// Initialize number images
myNumber[0] = '1.png';
myNumber[1] = '2.png';
...
myNumber[8] = '9.png';

// URLs for number images
var numberImage1 =  "url(" + numberAddress + myNumber[0] + ")";
var numberImage2 =  "url(" + numberAddress + myNumber[1] + ")";
...

// Different fruit arrays for different conditions
var fruitCloudOne = new Array(15);

fruitCloudOne[0] = '3apple.png';
fruitCloudOne[1] = '3banana.png';
...
fruitCloudOne[14] = '8strawberry.png';

// URLs for fruit images
var apple3 = "url(" + fruit1Address + fruitCloudOne[0] + ")";
var banana3 = "url(" + fruit1Address + fruitCloudOne[1] + ")";
...

// Functions for refreshing and starting the game
function refreshFruits() {
    // Refresh the fruit images
}

function startGame() {
    // Start the game by displaying number and fruit images
}

// Drag and drop functionality
function dragOver(ev) {
    // Drag over event handling
}

function dragStart(ev) {
    // Drag start event handling
}

function onDrop(ev) {
    // Drag and drop dropping event handling
}

// CSS code for styling
// Body CSS
body {
    // CSS properties
}

// Other CSS classes and IDs
#background {
    // CSS properties
}

#startGame {
    // CSS properties
}

...

// HTML code
<!DOCTYPE html>
<html>
    
<head>
    
    <meta charset="UTF-8">
    <link rel="stylesheet" type="text/css" href="stylesheet.css">
    <script type="text/javascript" src="script.js"></script>
    <title>This is an experiment.</title>
    
</head>
    
<body>
    
<button id="startGame" onclick="startGame()"></button>
<button id="refreshFruits" onclick="refreshFruits()"></button>

<div id="number"></div>
    
<div id="jelly" ondrop="onDrop(event)" ondragover="dragOver(event)"></div>

<div class="fruit" id="fruitCloud1">
    <div id="fruit1" draggable="true" ondragstart="dragStart(event)"></div>
</div>

...

</body>
    
</html>

Answer №1

Successfully implemented the code after making some adjustments to the if statement. Discovered a type error within it, so I included console log statements for better visibility of the output. The drag and drop functionality works when conditions align, but due to random generation, screen refreshing was necessary during testing to achieve the drop. The concept is innovative but may require refactoring for code minimization and improved readability. To view the example properly, it's recommended to display it in full-screen mode to prevent content compression. Thank you for sharing this, hope it benefits you!

var myNumber = new Array(9);

myNumber[0] = '1.png';
myNumber[1] = '2.png';
myNumber[2] = '3.png';
myNumber[3] = '4.png';
myNumber[4] = '5.png';
myNumber[5] = '6.png';
myNumber[6] = '7.png';
myNumber[7] = '8.png';
myNumber[8] = '9.png';

// Remaining code remains untouched.
body {
    width: 100%;
    max-width: 100%;
    margin: 0;
    overflow: hidden;
    padding: 0;
    background-color: black;
  }
  
  // CSS styling code remains the same.
  
  
<html>

<head>

  // HTML head code remains the same.

</head>

<body>

  // HTML body code remains the same.

</body>

<html>

Answer №2

My innovative approach to testing this involved utilizing the if condition to compare the dragged data's id with the desired div's id, rather than testing background images. This required organizing all images into a single array and adjusting the random generation process for fruit images to guarantee the correct image is always selected for each stage.

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

Unable to fetch the data from HTML input field using autocomplete feature of jQuery UI

I am facing an issue with my html autocomplete textbox. Whenever I try to enter an address like "New York" and click on the submit button, it does not retrieve the input value and returns no value. Test.aspx <!--Address--> <div class="form-g ...

Exploring the JSON data in Javascript using Ajax

Completely new to Javascript, I am just trying to grasp the basics of the language. Currently, I have a JSON request set up with the following code: function request(){ $.ajax({ dataType: "jsonp", type: 'GET', url: "getWebsite", ...

The getUserMedia() function fails to work properly when being loaded through an Ajax request

When the script navigator.getUserMedia() is executed through regular browser loading (not ajax), it works perfectly: <script> if(navigator.getUserMedia) { navigator.getUserMedia({audio: true}, startUserMedia, function(e) { __ ...

Tips for removing border highlight from an <select> element after being clicked

Is there a way to remove the border highlight (outline) of the <select> element after it is focused? I have successfully removed it for other elements like <input>, <textarea>, and <button>, but I'm struggling with the <sele ...

What is the best way to use AJAX to update multiple items with a common customer number on a SharePoint list?

Currently, I am facing an issue while attempting to update a SharePoint list using JavaScript/ajax. The script is running smoothly until it reaches the ajax function, where it encounters a failure. Specifically, it mentions that the ItemID is not defined, ...

Navigating through pages in a server component using Next.js

I am currently working on a project that involves implementing pagination using the NextJS 13 server component without relying on the use client. The goal is to ensure that when a button is clicked, new entries are added to the screen in a sequential order ...

Struggle with typescript integration with emotion and styled components

Issue Description: I encountered an issue while working with typescript and emotion/styled libraries. When attempting to specify the type of the parent component that wraps a styled component, I faced difficulties. The scenario involves a parent componen ...

New feature incorporated at the end of choices in MUI auto-suggest widget

Currently, I'm working on enhancing a category adder feature. Previously, I had limited the display of the "add category chip" to only appear for the no-options render scenario. However, I came across an issue where if there was a category like "softw ...

How can you transform a nested array into a flat JavaScript map?

If we consider a JavaScript Map structured like this: [ { id: 1, name: "Foo", contents: [1,2,3], morecontents: ["a","b"], }, { id: 2, name: "Bar", c ...

Execute a Python script using an Ajax jQuery call

Recently, I encountered an issue when attempting to execute a python file via jQuery. To address this problem, I conducted research online and came across a specific code snippet designed to call and run a python script. Below is the AJAX code utilized fo ...

My Angular7 app.component.html file is not displaying the routing. What could be the issue?

After implementing the code in app.component.html in Angular 7 like this: <div id="wrapper"> <header id="header-container" class="fullwidth"> <div id="header"> <div class="container"> <div class="left- ...

change the css style with the !important rule to muiStyle

Currently implementing the latest Material-UI library in my project. I am in the process of migrating old CSS files to new MuiStyles. I am converting it within my MuiStyle object using JavaScript as shown below: const muiStyle = { fabStyle: { displ ...

Using JavaScript to print radio type buttons

Currently working on a web page and I've encountered a problem that's got me stumped. There are two sets of radio buttons - the first set for package dimensions and the second set for weight. The values from these buttons are assigned to variable ...

JavaScript code that deletes text from a document - Script eradication

I am trying to display the message "Todays Beer Style is: "Beer Style". However, when I add the javascript code, the "Todays Beer Style is:" text disappears. I'm not sure why this is happening. Below is the HTML code for reference. HTML Code <!DO ...

Vue allows you to easily generate child div elements within a parent

Having some issues creating a child div with Vue. The code is being placed correctly, but it's being stored as an array. <template> <div class="containers" v-bind:style="{ backgroundColor: pageStyle.backgroundColor, paddingLeft:'5%& ...

Utilize Angular2 data binding to assign dynamic IDs

Here is the JavaScript code fragment: this.items = [ {name: 'Amsterdam1', id: '1'}, {name: 'Amsterdam2', id: '2'}, {name: 'Amsterdam3', id: '3'} ]; T ...

Overriding table styling with Bootstrap in a custom stylesheet

Recently, I made the switch from bootstrap v4 to v5 and I am in the process of identifying and fixing any issues that may have arisen. One particular issue that I am stuck on is the <th> tag not displaying correctly in the table. It seems like my tab ...

Issue with making requests across origins in Vuejs using axios

Currently, I am utilizing Vuejs and axios for handling web requests. So far, I have successfully managed to perform GET, POST, and PUT operations. However, the new challenge that I am facing is uploading media to the server. The server necessitates sending ...

How can I center a <a> vertically within a list that has varying heights?

Help Needed: Alignment Issue with Anchor Tags in List I am facing a challenge with vertically aligning the anchor tags inside my list. The number of list items varies based on the pages of my website, so I have used display flex on the list and flex: 1 on ...

Troubleshooting 404 errors on Firebase hosting with dynamic routes

My next.js app is deployed on firebase. The app has been deployed and in use for some time now. I created a dynamic route page Redeployed the app While I could access the dynamic page via a router, I encountered a 404 page not found error upon refreshing ...