Exchange the position of two divs using the x-y coordinates with javascript

I need help, I would like to exchange the position of two divs using the x-y coordinates and using a button with javascript only

Hi there ohhstunts,

Here is a possible alternative solution…

<!DOCTYPE HTML>
<html lang="en">
<head>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width,height=device-height,initial-scale=1">

<title>untitled document</title>

<link rel="stylesheet" href="screen.css" media="screen">

<style media="screen">
body {
    background-color: #f9f9f9;
    font: 100% / 162% verdana, arial, helvetica, sans-serif;
 }
h1, h2 {
    text-align: center;
 }
#div1, #div2, #content {
    max-width: 60em;
    padding: 1em;
    margin: 0.5em auto;
    border: 1px solid #999;
    background-color: #eef;
 }
#div2 {
    border-radius: 1em;
    background-color: #fee;
    box-shadow: 0 0 1em rgba( 0, 0, 0, 0.5 ), 
	        0.25em 0.25em 0.25em rgba(0, 0, 0, 0.3 ); 
}
#content {
    background-color: #fff;
}
</style>

</head>
<body>
<h1>swap stuff</h1>

<button id="swap">swap divs</button>
 
<div id="div1">
<h2>Div one</h2>
 <p>
  Lorem ipsum dolor sit amet, consectetur adipiscing elit.  
  Curabitur sit amet sem sed libero bibendum tempus faucibus       
  quis mi. Nulla rhoncus vel ipsum in volutpat. Nam tortor 
  nibh, posuere ac lorem ut, suscipit tincidunt leo. Duis 
  interdum justo ac justo vehicula consequat. Curabitur et 
  volutpat nibh.
 </p>
</div>

<div id="content">
 <p>
  Donec vehicula diam non leo efficitur, id euismod odio 
  tincidunt. Vivamus auctor viverra purus vitae lobortis. Sed 
  et libero non diam tempor sagittis. Quisque vel egestas 
  ipsum. Integer sed elit eu orci blandit commodo in in erat.
 </p>
</div>

<div id="div2">
<h2>Div two</h1>
 <p>
  Nam venenatis diam ante, et cursus elit porttitor at. Morbi 
  mattis leo at ex vehicula, non vestibulum ligula aliquam. 
  Maecenas non nibh sollicitudin, porttitor odio in, elementum 
  arcu. Donec pulvinar orci enim. In pulvinar congue ante, ac 
  rutrum odio bibendum volutpat. Phasellus ac sem consequat 
  lorem congue malesuada vitae vitae diam. Donec eu imperdiet 
  augue.
 </p>
</div>

<script>
(function( d ) {
   'use strict';
   var div1 = d.getElementById('div1'),
       div2 = d.getElementById('div2'),
       temp1 = div1.id,
       temp2 = div2.id,
       temp3 = div1.innerHTML,
       temp4 = div2.innerHTML,
       test = true;
	   
   d.getElementById('swap').addEventListener( 'click',
      function() {
         if ( test === true ) {
            div1.id = temp2;
            div2.innerHTML = temp3
            div2.id = temp1;
            div1.innerHTML = temp4;
            test = false;
            this.innerHTML = 'swap divs back';
          }
         else	{
            div1.id = temp1;
            div2.innerHTML = temp4
            div2.id = temp2;
            div1.innerHTML = temp3;
            test = true
            this.innerHTML = 'swap divs';
		  }
       }, false );
}( document ));
</script>

</body>
</html>

coothead

Here’s a way to do it using JavaScript only.

The HTML elements being worked with are:

<button id="switch">Switch</button>
<div id="one">One</div>
<div id="two">Two</div>

The JavaScript code sets the parent of those divs as the relative reference, and tells the divs to have absolute position.

var one = document.querySelector("#one");
var two = document.querySelector("#two");
one.parentNode.style.position = "relative";

one.style.position = "absolute";
two.style.position = "absolute";
one.style.top = "25px";
one.style.left = "0";
two.style.top = "50px";
two.style.left = "50px";

We can then watch for a click event on the button, and swap the top and left values of the divs.

document.querySelector("#switch").addEventListener("click", function (evt) {
    var temp = one.style.top;
    one.style.top = two.style.top;
    two.style.top = temp;
    temp = one.style.left;
    one.style.left = two.style.left;
    two.style.left = temp;
});

You can explore the working code at https://jsfiddle.net/coprtqhm/

Hi there Paul,

there may be a problem with “position: absolute” if there is other content.

coothead

That’s because absolutely positioned elements always ignore anything else that’s on the screen. That’s a fundamental aspect of absolutely positioned elements. You have the freedom of where they’re placed, and with freedom comes responsibility.

Hi there Paul,

I am very aware of how absolutely positioned elements behave. :winky:

That was why I questioned their use.

Responsively, it is bound to cause problems if the content starts
to take up more that one line. :wonky:

coothead

You’re not really taking into account the positions of the elements here though, you’re just swapping the contents; so depending on the layout, the actual positions may change if those wrapper divs are not absolutely positioned. But for all intents and purposes, I’d say that this is indeed the cleanest solution here – the actual positioning is now entirely done with CSS.

Anyway another thing to note is that by copying the .innerHTML, you’re actually replacing the child elements with new ones; this may have undesired consequences, such as losing any previously added event listeners. Instead, I’d suggest to swap the elements directly:

const div1 = document.getElementById('div1')
const div2 = document.getElementById('div2')
const swap = document.getElementById('swap')

swap.addEventListener('click',  () => {
  const tmp = [...div1.children]

  div1.append(...div2.children)
  div2.append(...tmp)
})
2 Likes

Can we find out from the OP the actual use-case situation that this will be happening with. For then, solutions can be provided that take into account the most likely issues to be faced in that situation.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.