Click on the grid in JavaScript to rearrange it with a simple tap

I've hit a roadblock while working on my project, specifically with reorganizing my grid using JQuery. To better illustrate the issue, I've simplified it into a fiddle: http://jsfiddle.net/tylerbuchea/QgAqV/

$('div').bind('click', function() {
   var pitcher = $('.selected')[0];
   var catcher = this;

  if (catcher.offsetTop < pitcher.offsetTop || catcher.offsetLeft > pitcher.offsetLeft) {
    $(pitcher).before(catcher);
    console.log('before');
  } 

   else 
     if (catcher.offsetTop > pitcher.offsetTop || catcher.offsetLeft < pitcher.offsetLeft) {
       $(pitcher).after(catcher);
       console.log('after');
     }
});​

The goal is to move the "selected" div to the clicked div's location, pushing all other divs down or up accordingly. While the current code accomplishes this for single moves, the problem arises when attempting multiple movements. Perhaps the use of .before and .after functions needs reconsideration?

Answer №1

Check out the revised code example I've provided with My Version:

$('div').bind('click', function() {
   var $currentlySelected = $('.selected'),
       $newlyClicked = $(this),
       currentlySelectedIndex = $currentlySelected.index(),
       newlyClickedIndex = $newlyClicked.index();

    if (currentlySelectedIndex > newlyClickedIndex) {
        $currentlySelected.insertBefore($newlyClicked);
        console.log('is greater, so put it after');
    } else {
        $currentlySelected.insertAfter($newlyClicked);
        console.log('is less, so put it after');
    }
});​

Take a look and let me know if this aligns with your expectations. I made some alterations to the logic. Instead of comparing offsets, I utilized .index() to determine an element's position in relation to its siblings.

If the clicked element has a lower index than the currently selected element, then I move the currently selected element to be placed BEFORE the clicked element. Conversely, if the clicked element has a higher index, I move the currently selected element AFTER the clicked element.

Regarding the issue where elements were moving one by one, my hunch is that you may have been manipulating raw DOM elements instead of jQuery objects at times. Using IDs might have yielded different results. By working with jQuery objects, the functionality now operates as intended.

Please confirm if this suits your requirements!

Answer №2

It seems like you're asking about a specific scenario, so here's my take on what you might be looking for:

$('div').on('click', function() {
   var source = $('.selected')[0];
   var target = this;

  if (target.offsetTop < source.offsetTop || target.offsetLeft > source.offsetLeft) {
    $(target).after(source);
    console.log('before');
  } 

   else 
     if (target.offsetTop > source.offsetTop || target.offsetLeft < source.offsetLeft) {
        $(target).before(source);
       console.log('after');
     }
});​

Best regards, Romén

Answer №3

$('div').bind('click', function() {
   var pitcher = $('.selected')[0];
   var catcher = this;

  if (catcher.offsetTop < pitcher.offsetTop || catcher.offsetLeft > pitcher.offsetLeft) {
    $(catcher).after(pitcher);
    console.log('before');
  }

   else
     if (catcher.offsetTop > pitcher.offsetTop || catcher.offsetLeft < pitcher.offsetLeft) {
        $(catcher).before(pitcher);
       console.log('after');
     }
});

You have switched around both the conditions and usage of the functions. Take a look at this resource to understand how to properly use before()/after().

The code may fail when dealing with multiple rows due to a logical flaw: you need to determine if the catcher is before/after the pitcher based on logic.

When does one tile come before another?

  • when it is on a higher row
  • OR
  • when it is on the same row AND positioned to the left

This exercise is meant for you to figure out the rest.

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

How can I animate a vertical line while scrolling down the page?

I'm attempting to create a dynamic vertical line that adjusts based on the position of elements on the webpage. Check out this example of what I'm aiming for: https://i.sstatic.net/JpK3FQI2.gif My attempt at achieving this looks something like: ...

Tips for maintaining fixed div sizes when resizing the window while preserving aspect ratio

Is there a way to maintain the same aspect ratio and keep the left and right divs side by side when resizing the window? I want them to stay consistent without changing no matter how much I resize the window. Here is an example of what I am looking for: ...

Is There a Sparse Array Element in JavaScript?

Is there a more efficient method to check for the presence of an array element within multiple layers of a structure? For example: if (typeof arr[a][b][c] === 'undefined') { ...do something... } If [a] or [b] are missing, we cannot accurately t ...

Angular - Utilizing Mat Paginator with Multiple Tables within a Single Component

I've been struggling with an issue for quite some time now, trying to find a solution but nothing seems to be working. Currently, I am facing an obstacle while rendering five tables on the screen. The data for these tables is fetched using a GET call ...

Verify your credentials in Geoserver using ASP.NET and IIS

Is it possible to integrate asp.net authentication with openlayers? I have created a Login page for authenticating in openlayers using C# on the server side. Here is an example of my code: Uri uri = new Uri("http://"+username+":"+password+"@localhost:197 ...

Using the same marker in React-Leaflet across different layers

Is there a way to add the same marker in multiple Layers using react-leaflet? For instance: In my restaurant search app built with react leaflet, each marker represents a different restaurant. I am looking to have a LayerControl that allows filtering by ...

Ways to stringify a JavaScript new date object using JSON

Extracting information from the form's JSON as users input data on the calendar const data = JSON.stringify(orderForm.informationDate)); At present, I am retrieving JSON data to generate a PDF document: {"year":2023,"month":12,&qu ...

Is your window.location.hash malfunctioning?

I am facing an issue with changing the background color of a <div id="services> when a specific link (index.html#services) is clicked. I have attempted to use the latest jQuery along with the jQuery Color plugin from jQuery Color. The code snippet I ...

What is the best way to align an image with the position of a div?

Looking for assistance on positioning an image to a div's position after it has been cloned. $(".raindrop1").clone().removeClass("raindrop1").appendTo("body"); $("img").css({"left": "div".x, "top": "div".y}); .shape{ border-radius: 50px; width: 10p ...

What is the best way to display the outcome of shuffling a deck of blackjack cards?

Looking to improve my blackjack game, I've implemented a card shuffle function. However, I'm struggling with getting the shuffled card results to display in the innerText after clicking the new game button. Despite reviewing and fine-tuning the ...

What is the best way to transform an array of different sizes into a JSON object?

Looking at the object array below, it's clear that the size and members of the array can vary. So, how can I efficiently convert all this data into a JSON object? Array: [0] =>{ "Name": XYZ } [1] =>{ "Gender":M } [2] =>{ "DOB":09085672 } [ ...

Tutorial: Using Three.js to Assign a Unique Random Image to Each Side of Multiple Cubes

I am currently working on integrating a feature similar to the one demonstrated in this example: While I have successfully implemented cubes, I am facing a challenge in applying different images to each cube. My goal is to assign a "Blogger" icon to one ...

I have noticed that the require.js define object is mysteriously appearing in my code within gulp.js

I have a gulp-concat script set up to concatenate jquery, slick-carousel, t.js, and my index.js files. const pack = () => { return gulp.src(['./node_modules/jquery/**/jquery.js', './node_modules/slick-carousel/**/slick.js', &apos ...

Error message displayed: MUI Textfield does not support input of decimal values

I have a textfield where users can enter the unit price const [unitPrice, setUnitPrice] = useState(0); <TextField label="Unit Price" variant="outlined" margin="normal" value={unitPrice.toString ...

Having trouble transferring sound files to Cloudinary API through javascript

I have successfully implemented a function in my React Native application to upload images to Cloudinary. Now, I am trying to modify the function to upload audio files as well. Despite specifying the "resource_type" parameter as "raw", "video", or "auto", ...

Use React to insert a leading zero next to a number in the input field if the number is greater than 10

I have scoured the web and consulted resources like this one but haven't found a solution that addresses my specific issue with adding padding to input numbers. My goal is to automatically add a leading zero whenever the number inside an input field i ...

Tips for running two elixir tasks consecutively?

Check out this piece of code: var gulp = require('gulp'), fs = require('fs'); gulp.task('taskOne', function() { return gulp.src('folder1/file1.js') .pipe(gulp.dest('folder2')); }); gulp.t ...

Having issues with retrieving latitude and longitude data from the Geocoding API in Node.js when using the OpenWeather API

I attempted to create a program in node.js that utilizes the openweather API. The idea was for the user to input a city name, then use the Geocoding API to extract the latitude and longitude coordinates, and finally retrieve weather data from the current w ...

What is the best way to execute the app functions, such as get and post, that have been defined

After creating a file that sets up an express middleware app and defines the app function in a separate file, you may be wondering how to run the app function. In your app.js file: const express = require('express') const cors = require('c ...

What is the process for adjusting the position following the modification of a table value in React?

In my React UI, I have set up two text fields for entering values. After saving the values, they are displayed in a table below (designed with antd). When I click on a record in the table to edit it, I want the data from that record to populate the text f ...