Using jQuery to drag a div and drop it to swap out an image in a different

I am looking to implement a drag and drop function where I can move elements from one div to another, each containing different images. However, I want the image displayed in the second div to change based on the element being dragged.

For example: When dragging #element1 into the images's div, I want to display the image with .element1 class and hide the image with .element2 class.

<div id="element1"></div>
<div id="element2"></div>

<div id="images">
<img class="element1" src="1.jpg" />
<img class="element2" src="2.jpg" />
</div>

Is this possible? I came across a method using jQuery for changing background images but I need it for actual img tags.

I tried implementing it here: http://jsfiddle.net/wolfovs/ab0566Lt/1/

If anyone can help me out, I would greatly appreciate it! Thank you!

Answer №1

Make sure to include the jquery and jquery-ui library either in the head section of your HTML or right before closing the body tag.

$("#images").droppable({
  drop: function(e, ui) {
    if((ui.draggable.attr("id")) == 'element1'){
       $('.element2').hide();
       $('.element1').show();
    }else if((ui.draggable.attr("id")) == 'element2'){
       $('.element1').hide();
       $('.element2').show();
    }
});

Check out the DEMO 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

The search functionality for the MongoDB module is not functioning properly within my Next.js application

Working on my nextjs application, I have encountered an issue with using the mongodb node module to find all documents in one of my collections. Despite successful usage of .findOne and .updateOne for other pages like login and password reset, when I use . ...

Menu with a full-width fluid input field using semantic-ui

I am trying to create a fixed top menu with an image on the left, an input to its right, and another input on the far right. My goal is to have the center input stretch to fill all remaining space between the image and the other input. Although I would no ...

Retrieve the image source when clicking on multiple posts that share the same div class and button class

<script src="https://code.jquery.com/jquery-1.11.1.js"></script> <script> $(function(){ $('.like').click(function(e){ e.preventDefault(); // stop the page from reloading alert( $('.post-container&apos ...

Exploring the concepts of closure and scope

It seems that the function inResult always returns false and the loop is not being executed, probably due to a lack of understanding of closures. However, I can confirm that the result variable contains the correct properties. function hasId() {return ...

Error: The callback specified is not a valid function

Here is a function example: reportAdminActions.reportMemberList(project, function(data) { console.log(data); }); This particular function gets called by another ajax operation, similar to the one shown below: reportMemberList: function(projectId, ca ...

Are there any drawbacks to converting all instance methods into arrow functions in order to prevent binding loss?

What are the potential drawbacks of converting all instance methods into arrow functions to avoid the "lost binding" issue? For example, when using ReactJS, the statement onClick={this.foo} can lead to lost binding, as it translates to createElement({ ... ...

The React-loadable alert indicated a discrepancy in the text content

Utilizing react-loadable for dynamic JS module loading is part of my process. With server-side rendering already set up and functioning correctly for react-loadable, I am encountering an issue on the client side. Upon page load, a warning message appears i ...

Identify HTML elements within a textarea or text input using JavaScript while also accommodating the common special characters ">" and "<"

Is there a way to accurately detect HTML tags in textarea or text input fields before submitting a form? While it may seem straightforward to use regular expressions like /<\/?[^>]*>/gi.test(str) for this purpose, the challenge arises when de ...

The ajax call cannot be processed because the request method 'POST' is not supported

I am currently encountering an issue with making an ajax call to my spring controller for creating some data in the database. The code for the ajax call looks like this: function sendDataToController(param1, param2, index1, index2, dataType) { $.ajax( ...

Utilize jQuery to interact with a pair of dropdown menu options

In my web application, I have two identical dropdown lists that contain the same values. These dropdown lists are used for account numbers. I want to prevent users from selecting the same item from both lists. For example, if a user selects item #1 fro ...

The autofill ajax script is unable to populate dynamically added rows

As a newcomer to programming, I am trying to create a table that allows users to add new rows by clicking a button. Each row should have a field for inputting an ID which corresponds to some predefined numbers in another table, and then the other field sho ...

jQuery function not executing after subsequent AJAX request

Can anyone provide some assistance with my AJAX/jQuery setup? I'm attempting to dynamically load code into a jQuery Dialog. There is some jQuery code within the content that initializes buttons and loads tabs. The issue I'm facing is that the c ...

The radio button becomes unchecked when moving to the next fieldset

While developing a dynamic page using PHP and Laravel, I encountered a situation where I needed to add an additional radio button option to each card. Below is the code snippet for the card in question: <div class="card" style="margin:10p ...

Regular intervals and asynchronous JavaScript and XML (AJAX) requests are

There is a simple chat tool in place to ensure the chat room stays updated: setInterval (loadLog, 2500); function loadLog(){ //Scroll height prior to the request var oldScrollHeight = document.getElementById("chatMessages").scrollHeight - 20; ...

Adding TH into a TABLE in Angular 2 by verifying TD elements

I am seeking a way to automatically generate thead and th, using td in the template : <Datatable> <tr #lineSelected *ngFor="let subscription of results"> <td nameColumn="Nom">{{subscription.name}}</td> <td n ...

What methods can I use to design a splash screen using Vue.js?

I am interested in creating a splash screen that will be displayed for a minimum of X seconds or until the app finishes loading. My vision is to have the app logo prominently displayed in the center of the screen, fading in and out against a black, opaque ...

Encountering a challenge with Nuxt where I am unable to navigate back when utilizing the require method

After successfully viewing the image, I encountered an error when trying to navigate back using <NuxtLink :to="{ path: 'About', hash: '#secondNav' }" class="close">, which resulted in a message stating Cannot f ...

Leverage an HTML table to serve as a data source for populating a Kendo UI template

My latest creation is a unique service that generates HTML tables based on request parameters. The current implementation returns the data as an HTML page in string format. Here's a sample output: <!DOCTYPE html> <html> <head> ...

Html elements remain stationary and do not shift positions

I am attempting to customize a web page by repositioning an input text element. Below is the code I'm using: <body> <h1>Shopping List</h1> <input id="search" type="search"> <input id='newItem' type="t ...

What is causing myInterval to not be cleared properly?

const homeButton = document.getElementById('home'); window.myInterval = 0; const showHome = () => { console.log('showHome'); window.myInterval = setInterval(wait, 400) } const wait = () => { console.log('wait'); ...