How to switch around div elements using CSS

There are two unordered list items in a container div and one swap button. When the swap button is clicked, the order of items needs to change. This functionality can be achieved using the following swap function.

var ints = [ "1", "2", "3", "4" ],
    chars = [ "A", "B", "C", "D"],
    list1 = document.getElementById("list1"),
    list2 = document.getElementById("list2"),
    toggle = 0;

setList(list1, ints);
setList(list2, chars);

function setList(element, data) {
  for (var i in data) {  
    var elem = document.createElement("li");
    elem.innerText = data[i];
    element.appendChild(elem);
  }
}

function swap() {
  list1.innerHTML = "";
  list2.innerHTML = "";
  if(toggle==0) {
    setList(list1, chars);
    setList(list2, ints);
    toggle=1;
  } else {
    setList(list1, ints);
    setList(list2, chars);
    toggle=0;
  }  
}
.box {
  display: flex;
  align-items: center;
  position: absolute;
  top: 20px !important;
}
<div class="box">
<ul id="list1"></ul>
<ul id="list2"></ul>
</div>

<button id="btn" onclick="swap()">Swap</button>

I am curious if this functionality could be achieved using CSS alone. Feel free to test the code on Codepen at https://codepen.io/imjaydeep/pen/EBvaxG?editors=1111

Answer №1

Implemented through the utilization of CSS order property.

var nums = [ "5", "6", "7", "8" ],
    letters = [ "E", "F", "G", "H"],
    listOne = document.getElementById("listOne"),
    listTwo = document.getElementById("listTwo"),
    switcher = 0;

setList(listOne, nums);
setList(listTwo, letters);

function setList(item, data) {
  for (var j in data) {  
    var element = document.createElement("li");
    elem.innerText = data[j];
    item.appendChild(element);
  }
}

function toggle() {
  if (switcher == 0) {
    listOne.classList.remove('listOne');
    listTwo.classList.add('listTwo');
    switcher = 1;
  } else {
    listTwo.classList.remove('listTwo');
    listOne.classList.add('listOne');
    switcher = 0;
  }  
}
.container {
  display: flex;
  align-items: center;
  position: absolute;
  top: 20px !important;
}

.listOne {
  order: 1;
}

.listTwo {
  order: 1;
}
<div class="container">
<ul id="listOne"></ul>
<ul id="listTwo"></ul>
</div>

<button id="button" onclick="toggle()">Switch</button>

Answer №2

One approach could be to switch out the button for a checkbox, which can be used to toggle the row order of the container div.

div {
  display: flex;
  align-items: center;
  position: absolute;
}

#swap:checked + div {
  flex-direction: row-reverse;
}
 <label>Swap</label>
 <input type="checkbox" id="swap" />
  <div>
    <ul id="list1">
      <li>1</li>
      <li>2</li>
      <li>3</li>
    </ul>
    <ul id="list2">
      <li>a</li>
      <li>b</li>
      <li>c</li>
    </ul>
  </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

The function insertAdjacentHTML does not seem to be functioning properly when used with a

I am working with a parent element that contains some child elements. I create a DocumentFragment and clone certain nodes, adding them to the fragment. Then, I attempt to insert the fragment into the DOM using the insertAdjacentHTML method. Here is an ex ...

What is the process for retrieving data from mongoDB and displaying it by year in a single row?

I have received an array of data from MongoDB, which includes id, userName, and date. The date consists of years and months. My goal is to display this data categorized by years. How can I construct a query to the database that will show the data for all y ...

Concealing scroll bars while still maintaining the ability to scroll by using overflow:scroll

Similar Question: How to hide the scrollbar while still allowing scrolling with mouse and keyboard I have created a sidebar for a web application that needs to enable users to scroll through it without displaying a scrollbar. The content is 500px high ...

Troubling inconsistency in jQuery's .css function performance

I'm facing a problem with the jquery .css function. I am using it to retrieve the actual height of elements that have their height set to auto. The code I am currently using is as follows: $(this).css({ height: $(this).css("height"), width: $(this).c ...

What is the best way to preserve an apostrophe within a variable in JavaScript without it being replaced?

How can I send the value of NewText in its original form from .cs code using an ajax call? **var NewText ="D'souza";** $.ajax({ type: "POST", contentType: "application/json; charset=utf-8", url: " ...

retrieving the webpage's HTML content from the specified URL using AngularJS

Utilizing the $http.get('url') method to fetch the content located at the specified 'url'. Below is the HTML code present in the 'url': <html> <head></head> <body> <pre style = "word-wrap: break ...

Objective-C and the World of WebSockets

Possible Duplicates: Comparison of WebSockets, TCP/IP, and JavaScript/AJAX for iPhone chat Integrating WebSockets into a Cocoa application Hello all, our team is embarking on creating a bespoke iPhone chat app and deliberating the use of WebSocket ...

Using Symfony2 Knp-snappy library for PDF generation, the CSS styling is not being properly imported

Attempting to create a PDF from an html.twig template, but facing some issues... Although the content is correct in the PDF, the layout is missing. It appears that the CSS files are not being imported... Bootstrap from Twitter is being used to handle the ...

Having Trouble with Shopify's Asynchronous Ajax Add to Cart Feature?

I have developed a unique Shopify page design that allows users to add multiple items to their cart using Shopify's Ajax API. I've created a test version of the page for demonstration: Below is the current javascript code I am using to enable as ...

Display images that have been uploaded on the page either as a grid view or a list of

In my Reactjs application, I am uploading multiple images to Azure Blob Storage. On a page, there is a button to open the upload form. Once the upload completes, I want to display all these images on the same page. Since the images have different aspect ...

Tips for customizing the appearance of a mat-select chosen item?

Is there a way to modify the color of the selected option text in a mat-select component within an Angular 15 project? .html <mat-form-field> <mat-label>From</mat-label> <mat-select panelClass="mat-select-red"> ...

Experiencing an inexplicable blurring effect on the modal window

Introduction - I've implemented a feature where multiple modal windows can be opened on top of each other and closed sequentially. Recently, I added a blur effect that makes the background go blurry when a modal window is open. Subsequently opening an ...

What is the process for generating Json using information from a form?

Recently, I embarked on a project that involves creating online tours via a form filled out by the administrator. The data submitted through the form is then mapped into a Mongoose Schema and transformed into JSON. In the createcontent.js file, I utilized ...

Where do JQuery and framesets vanish to?

Whenever I attempt to use the console to create an element with the tag frameset, it returns no result: $('<div id="content" data-something="hello" />') => [<div id=​"content" data-something=​"hello">​</div>​] $(&apo ...

Guide on automatically logging in to a specific website using Selenium with Kakao, Google, or Naver credentials

I encountered an issue with my selenium login code for a particular website, where the keys seem to be generating errors. https://i.stack.imgur.com/wJ3Nw.png Upon clicking each button, it brings up the login tab. However, I keep encountering this error ...

Using the Google Chrome console, execute a command on each page within a specified website

While browsing a website, I noticed a bug that required me to manually run a JavaScript function each time I navigated to a different page in order for the site to work smoothly. Is there a way to automate this process upon page load? I am using Google C ...

The rounded corners feature of PIE.htc does not seem to be functioning properly on Internet Explorer

Check out my code below: http://jsfiddle.net/parag1111/s5RLb/ Make sure to place PIE.htc in the CSS folder. I've already included the necessary JS and behavior for PIE.htc. Please provide any additional suggestions to ensure compatibility with IE8 a ...

Ways to retrieve my PHP output and display it on a page using Ajax

I'm struggling to combine the functionalities of a PHP script and Ajax on my website. I want to update content without reloading the page but facing issues. Although I can send input data through Ajax, I'm unable to retrieve the results effectiv ...

Creating a multi-column layout with HTML and CSS

I'm currently exploring the most effective method to design this concept: https://i.stack.imgur.com/SOQp4.png The black square symbolizes small icons, accompanied by a heading and paragraph for each specific section. The icons need to align with the ...

Switch out the image in the dropdown and update the button once it is selected

In this scenario, I am looking to dynamically change the image in a button dropdown when it is clicked. The goal is for the dropdown image to swap and replace with the actual one upon clicking. For reference, here's the fiddle: https://jsfiddle.net/32 ...