Tips for inserting an element into a div only if both the element and div share the same id using JavaScript

Looking to drag and drop an element into a div with multiple divs, but only allowing the drop if the IDs of the element and the div match. Trying to retrieve the ID of the div where the image is being dragged, compare it with the ID of the dragged image, and then drop it accordingly. Being new to JavaScript, any assistance would be greatly appreciated!

Check out the code here: jsfiddle.net/8m6982qf

Answer №1

Store the valid data in your div and then compare the image ID with the div's stored data before appending.

HTML

<p>Drag an image into the right Box:</p>
<div>
    <div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)" data-allowed="boy"></div>
    <div id="div2" ondrop="drop(event)" ondragover="allowDrop(event)" data-allowed="man"></div>
    <br>
</div>
<div  class="title"><p><span id="left">Boy</span><span id="right">Man</span></p></div>
<br>
<div class="images">
    <img id="boy" src="http://images.fitpregnancy.mdpcdn.com/sites/fitpregnancy.com/files/styles/width_360/public/toddler-wearing-headphones_600x600_shutterstock_93821278.jpg" draggable="true" ondragstart="drag(event)" width="100" height="100" onclick="reply_click(this.id)">
    <img id="man" src="http://creativestockphoto.com/wp-content/uploads/2014/10/images-of-man-and-woman-in-love.jpg" draggable="true" ondragstart="drag(event)" width="100" height="100" onclick="reply_click(this.id)">
</div>

Javascript

function allowDrop(ev) {
    ev.preventDefault(); 
}
function drag(ev) {
    ev.dataTransfer.setData("text", ev.target.id);
}
function reply_click(clicked_id)
{
    alert(clicked_id);
    return clicked_id;
}
function drop(ev) {
    ev.preventDefault();
    var data = ev.dataTransfer.getData("text");
    if(ev.target.getAttribute("data-allowed")==data)
        ev.target.appendChild(document.getElementById(data));
}

View the fiddle here

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

Issue: unable to inject ngAnimate due to uncaught object error

Whenever I attempt to inject 'ngAnimate' into my app, I encounter issues with instantiation. Here is the code snippet in question: var app = angular.module('musicsa', [ 'ngCookies', 'ngResource', 'ngSanit ...

Changing the color of HTML text based on a variable in Vue JS can be achieved by altering the CSS styles dynamically

I have developed a website that shows values with a set threshold. I now want to change the color of the values when they exceed the threshold, but I am unsure of how to proceed. I want to display consultation.indicateurs.TRS in red when it exceeds the va ...

Tips for employing duplicated HTML on a webpage

I have developed a main menu for my website using html and css. It seems cumbersome to manually copy and paste this menu into every single file or page on the website whenever I make edits. Is there a way for this main menu to automatically appear on every ...

Discover the technique for determining the XPath location of an element through Javascript

Imagine you have a lengthy HTML file filled with various tags, much like the layout of Stack Overflow. If you were to click on a specific element on the page, what would the Javascript function look like to determine the simplest XPath that points to that ...

Leverage Redis to facilitate memory sharing among node.js instances in RxJS

We are currently developing a project that involves creating an event processor using RxJS. The system relies on specific rules where input is collected from various sources and output is generated based on the frequency of inputs exceeding a certain thres ...

Alter the class when $dirty occurs in Angular

I've recently started working with angular js and am attempting to incorporate animations into my login page. I have created a controller that will modify the class of the input field when clicked and when blurred. app.controller("con", function($sc ...

Checking the validity of a username through regex

I have implemented a Username field validation in Vue using regex. A key down event triggers the method below with each keystroke: userNameValidation(event) { if (!event.key.match(/^[a-zA-Z0-9._]+$/)) { event.preventDefault(); } ...

Display the text area when the "Yes" radio button is clicked, while it remains hidden either by default or when the "No" radio button is selected

I am currently working on an html code and I am looking for a way to use java script in order to create a text area box only when the "Yes" radio button is selected. This text area should be hidden by default or when selecting "NO". <table class="tab ...

Utilizing Vue.js i18n for a multi-line text display

Currently, I am implementing i18n single file component in order to provide translation support for my application. In order to achieve this, I have been utilizing the i18n tag as shown below: <i18n> { "fr": { "text": "Lore ...

Looking to pass multiple props and run a function for each one? Here's how!

There is a scenario where I have two separate times in minutes format that need to be converted to 24-hour format without separators. I am currently using a function for this conversion and then using momentjs to transform it into the required format. Whil ...

React DOM's offsetHeight prior to rendering

I am struggling to figure out how to position a React DOM element based on its offsetHeight. The issue is that I cannot determine the offsetHeight of an element that hasn't been created yet (so the height cannot be passed as a parameter to the render ...

Choose every fourth row in the table

Is there a way to alternate the background colors of selected groups of 4 rows in a table? I want to make one group red and the next group blue. Any suggestions or ideas on how to achieve this? <table> <tr style="background-color: red;"> ...

Using Inline Styling to Showcase a Background Image in a REACTJS Component

import React from 'react'; import Slick from 'react-slick'; import style from './Slider.module.css'; import {Link} from 'react-router-dom'; const SliderTemplates = (props) => { let template = null; const ...

Make the minimum height of one div equal to the height of another div

My query is somewhat similar to this discussion: Implementing a dynamic min-height on a div using JavaScript but with a slight twist. I am working on a dropdown menu within a WordPress site, integrated with RoyalSlider. The height of the slider div adjust ...

Is there a way to adjust a 5-minute countdown interval timer by 1 minute in a react JS application?

I am in need of creating a 5-minute interval timer using react JS, with a 1-minute offset. The current timer I have functions like this: 1:00 => 1:05 => 1:10 => 1:15 => 1:20. However, I require it to be adjusted to display: 1:01 => 1:0 ...

Can you explain the role of the %GetOptimizationStatus function within a JavaScript file executing in Node.js?

Currently, I am delving into an article that discusses optimization strategies and includes the following code snippet: //Function that contains the pattern to be inspected (using an `eval` statement) function exampleFunction() { return 3; eval(&a ...

How to Retrieve the Current div's ID in VueJS

When using the v-for directive to dynamically generate an id for my div, I need to pass this unique id to a specific function. <div v-for="(item, index) in items" :key="index" :id="'form' + index" > ...

Encountered an issue while trying to register a service worker: "[ERROR] Cannot import statement outside

With the utilization of register-service-worker, the boilerplate for registerServiceWorker remained untouched. /* eslint-disable no-console */ import { register } from 'register-service-worker'; if (process.env.NODE_ENV === 'production&ap ...

How to bind parent object scope to MySQL query's anonymous callback in Node.js

As a newcomer to node.js, I am still working on understanding the concept of scoping anonymous functions. I have created an object with multiple methods and within one of my methods, I retrieve a MySQL connection from a pool and then execute a query on tha ...

Add information to the Database seamlessly without the need to refresh the page using PHP in combination with JQuery

Check out my code below: <form action='insert.php' method='post' id='myform'> <input type='hidden' name='tmdb_id'/> <button id='insert'>Insert</button> <p i ...