Reordering div elements with JavaScript

Let's say we have the following structure:

   <div id="left">
          <div id="1"></div>
          <div id="2"></div>
          <div id="3"></div>
          <div id="4"></div>
          <div id="5"></div>
          <div id="6"></div>
          <div id="7"></div>
          <div id="8"></div>
          <div id="9"></div>

    </div>


    <div id="right">
          <div id="r1"></div>
          <div id="r2"></div>
          <div id="r3"></div>
          <div id="r4"></div>
          <div id="r5"></div>
          <div id="r6"></div>
          <div id="r7"></div>
          <div id="r8"></div>
          <div id="r9"></div>
    </div>

I have utilized css sprite to display an image for the left and right divs.

For instance, the image for the left div could be like this:

Photo

I am trying to swap a child div from the left with a child div from the right, or at least the images within those divs. For example swapping 1 and r1.

I attempted something like this:

function swapElements(obj1, obj2) {
    var parent2 = obj2.parentNode;
    var next2 = obj2.nextSibling;
    if (next2 === obj1) {
        parent2.insertBefore(obj1, obj2);
    } else {
        obj1.parentNode.insertBefore(obj2, obj1);

        if (next2) {
            parent2.insertBefore(obj1, next2);
        } else {
            parent2.appendChild(obj1);
        }
    }
}

However, it only works when swapping divs within the same parent div, not between left and right. Swapping 1 with 2 works, but r1 with 1 does not work.

I hope this explanation is clear. Any assistance would be greatly appreciated.

Later edit; additional code as requested:

All divs within left and right have an attribute onclick="select((divs id))"

The function looks similar to this:

var selected = null;

function select(cellID){

    if (selected == null){  //if this is the first time selecting
        selected = cellID;
        cell = document.getElementById(selected);
        cell.setAttribute("class", "selected");
        return;
    }



    if (selected == cellID){ // if selected same cell
        document.getElementById(selected).setAttribute("class", "");
        selected = null;
        return;
    }
    if (selected){
        document.getElementById(selected).setAttribute("class", "");
        swapElements(document.getElementById(cellID), document.getElementById(selected));
        selected = null;
        return;
    } 

}

The selected attribute is set for

  .selected {
            transform: scale(0.95, 0.95);
        }

Answer №1

Your use of the insertBefore method is definitely on the right track.

Check out this functional demonstration that employs insertBefore:

var leftDiv = document.getElementById('left');
var rightDiv = document.getElementById('right');
var divs = [... document.querySelectorAll('div div')];

function swapDivs() {
    var divIndex = (parseInt(this.id.substr(-1)) - 1);

    var leftBefore = rightDiv.getElementsByTagName('div')[divIndex];
    var leftAfter = leftDiv.getElementsByTagName('div')[(divIndex + 1)];

    leftDiv.insertBefore(leftBefore, leftAfter);

    var rightBefore = leftDiv.getElementsByTagName('div')[divIndex];
    var rightAfter = rightDiv.getElementsByTagName('div')[divIndex];

    rightDiv.insertBefore(rightBefore, rightAfter);
}

divs.forEach(function(div){
    div.addEventListener('click', swapDivs, false);
});
#left, #right {
float: left;
width: 180px;
background-color: rgb(127, 127, 127);
border: 2px solid rgb(0, 0, 0);
}

div div {
height: 24px;
text-align: center;
color: rgb(255, 255, 255);
background-color: rgb(255, 0, 0);
border: 2px solid rgb(255, 255, 255);
border-top-width: 1px;
border-bottom-width: 1px;
}

div div:hover {
background-color: rgb(163, 0, 0);
cursor: pointer;
}
<div id="left">
          <div id="l1">Left 1</div>
          <div id="l2">Left 2</div>
          <div id="l3">Left 3</div>
          <div id="l4">Left 4</div>
          <div id="l5">Left 5</div>
          <div id="l6">Left 6</div>
          <div id="l7">Left 7</div>
          <div id="l8">Left 8</div>
          <div id="l9">Left 9</div>
    </div>


    <div id="right">
          <div id="r1">Right 1</div>
          <div id="r2">Right 2</div>
          <div id="r3">Right 3</div>
          <div id="r4">Right 4</div>
          <div id="r5">Right 5</div>
          <div id="r6">Right 6</div>
          <div id="r7">Right 7</div>
          <div id="r8">Right 8</div>
          <div id="r9">Right 9</div>
    </div>

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

Using jQuery to toggle visibility based on data equivalence

I created a code snippet in which I am implementing jQuery show/hide functionality when the data attribute matches. Here is the HTML structure: <div class="container"> <div class="item" data-item="1">1 <div class="inside" data-c ...

Is there a way to incorporate a variable into a JSON URL?

I'm attempting to incorporate a variable I have defined into the JSON URL: var articleName = "test"; $.getJSON( "https://www.googleapis.com/customsearch/v1?key=API_MY&cx=CX_MY&q='+articleName+'&searchType=image&fileType= ...

What is the best way to create a horizontally scrolling row of squares in a mobile view using html and css?

Below is a screenshot that I have replicated in the code snippet. The code snippet contains a parent div with two rows mentioned: <div class="product-all-contents"> <div class="product-contents"> </div> <div class="product-contents" ...

Ensuring the timely execution of Javascript functions with Selenium before moving on

While working on creating test cases using Selenium, I encountered an issue. In one of my test cases, there is a small form and a search button on the website I'm testing. Filling the form and clicking the button are not the problem. The issue arises ...

Tips for handling the !important declaration when creating a customized bootstrap theme

Exploring the Color Dilemma After creating a simple website in Bootstrap 4.1 with a distinct shade of purple, I encountered an issue with specificity when it came to customizing button states. To address this, I introduced a CSS class called .btn-purple ...

Tips for changing an angular variable string before sending it to a PHP function

When working with AngularJS, I can access form variables within my function like this (for example: s1 = Joe Smith). However, I have a need to update the Indata variable by replacing the a_searchvalue1 with the value stored in s1 but wrapped in quotes. O ...

Actions for jQuery's mouseenter and mouseleave events

I've implemented a jQuery script that controls the visibility of elements based on mouse events: $("#divid").mouseenter(function() { $('#divid').show(1000); }).mouseleave(function() { $('#divid').hide(1000); }); $("#hldiv" ...

Ways to swap out an img element with an almost identical gif element while maintaining its precise placement consistently

I am facing an issue in my code where a random element is generated within the body and when clicked, it is replaced with another gif element. I am using offset() to obtain the top and left values of the original image, and then using replaceWith() to swap ...

Sending form data after a successful AJAX request with jQuery in ASP.NET MVC 5

Within my Asp.net MVC 5 project, there exists a form equipped with a Submit button. Upon clicking this Submit button, the following tasks are to be executed: Client-side validation must occur using jQuery on various fields (ensuring required fields are ...

Eliminate the margin on the subnavigation menu

Hey there, I'm looking to adjust the layout of my menu buttons by removing the left and right "margins" (if that's the correct term), so they all fit neatly inside the navigation bar. https://i.sstatic.net/udes8.png I want to ensure that all th ...

What is the best way to display content next to an image, as well as below the image once it finishes?

Currently, I am working on customizing my blog posts in WordPress. My goal is to have the content of each post displayed next to the post thumbnail, and once the image ends, the content should seamlessly flow underneath it from the left side. I have imple ...

Displaying a div when a radio button is clicked in React

I am attempting to create a functionality where clicking on one radio button will display another div in React. As a beginner in React, I have tried implementing the code below but encountered issues with hiding and displaying the content based on user inp ...

Encountering the error "Cannot access property 'stroke' of undefined" when utilizing constructors in React and p5

Hi there, I'm having trouble with my React code and could really use some assistance. Being new to React, I'm trying to create a collision system between multiple bubbles in an array, but I keep running into this undefined error: https://i.sstat ...

Can access parent refs when exporting a child component with withStyles by following these steps:

For example: Child Component Code // Assume there is a styles object 's' being used in this component class Child extends Component { render() { return ( <h1 ref={(ref)=>{this.ref = ref}}>Hello</h1> ); } } export defau ...

We were unable to locate the module: Unable to locate './components/counter' in 'C:/...democounter-appsrc'

I'm completely new to React and currently following tutorials by MOSH on YouTube. However, I've encountered an error that I can't seem to resolve even after searching for similar questions. index.js import React from 'react'; imp ...

"Utilizing Bootstrap 4: Understanding the Optimal Times to Implement the 'Row

After studying the fundamental guidelines for Bootstrap 4, a question has arisen in my mind: Under what circumstances should we utilize the .row class in our layout? I came across this example where the .row class was not used in the code. However, the ba ...

Preloaded background images are loaded twice

I have a background image that I am preloading and caching, but my code is not reading it from the cache. It keeps loading the image as if it is not cached. Even though I have 8 images in the "imgSrcArray," I have simplified this example by hard coding jus ...

Difficulty encountered while setting up jQuery slider

I am struggling to set up a jquery slider (flexslider) It seems like I am overlooking something very fundamental, but for some reason I just can't figure it out. Any assistance would be greatly appreciated. Please check out the link to the test site ...

Is it possible to recognize when the mouse button is held down and the cursor is outside the viewport by using mouseleave detection?

Is there a way to detect when a user moves the mouse outside of the view-port, even if they are holding down the mouse button (for example, if the mouse is on the browser address bar)? In the code below, I am currently using mouseout and mouseleave to det ...

Can the hexadecimal code for a particular color name be identified?

Similar Question: Javascript function to convert color names to hex codes Is there a way to determine the hexadecimal value of a named color that is currently being used by the browser? For example, I would like to achieve something similar ...