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 combination of list-style-type and display:inline is ineffective

Many questions have been asked in different areas about this issue, but none of the answers I found were able to solve my problem. My challenge lies in creating a navigation menu where I can't remove the list style or display it inline. Here is the HT ...

Can default query parameters be predefined for a resource in AngularJS?

When working with a simple resource like the one defined below, it is possible to utilize the Receipt.query() method to retrieve a collection from the server. In addition, by calling Receipt.query({freightBill: 123}), a query parameter such as freightBill ...

dirpagination fails to display all rows in the dataset

I've been working on creating tables with 3 divs, as shown in the link below:- https://github.com/anirbanmishra/congress.php/blob/master/web_test Additionally, I have a javascript file available here:- https://github.com/anirbanmishra/congress.php/bl ...

Eliminate the empty choice for Angular when dealing with dynamic option objects

Looking for assistance with this code snippet: <select ng-model='item.data.choice' > <option ng-if='item.data.simple_allow_blank == false' ng-show='choice.name' ng-repeat='choice in item.data.simple_choices&ap ...

An issue is being caused by altering the custom.scss.css file in Rails

After following the tutorial by Michael Hartl (), I encountered an issue when trying to modify some CSS functions in the custom.scss.css stylesheet. Every time I make a change, such as adjusting the margin from 10 px to 11 px, I receive this error in my br ...

Adjust the color of the paper in Material-UI

I'm in the process of creating a React project using the material-ui library. Currently, I am facing an issue with customizing the drawer component's background color. After some research, I learned that modifying the paper attribute of the drawe ...

JSON Eval function encountered an identifier that was not anticipated

Here is a code snippet that I found for rating a page. It works perfectly on my local machine, but once I upload it to the server, it throws a syntax error. function rtgAjax(elm, ratev) { var cerere_http = get_XmlHttp(); // get XMLHttpRequest object ...

What is the best way to create a clickable image with a box-shadow when a z-index of -1 is applied?

Is there a way to make an image clickable while still retaining the box shadow effect created using CSS3? Currently, I have set the z-index of -1 for the img tag to apply the box shadow. However, this makes the image not clickable when an href tag is added ...

Prevent the <a> tag href attribute from functioning with jQuery

I came across this code snippet: <script type="text/javascript"> $(document).ready(function() { $("#thang").load("http://www.yahoo.com"); $(".SmoothLink").click( function() { $("#thang").fadeOut(); $("#thang").load( ...

What is the best way to swap out text for an image in CSS?

I came across a website that I am working on: The site features a slider with 2 tabs named "TAB1" and "tab2" My goal is to replace the text with unique images for each tab Below is the CSS code snippet: .dnd-tabs.dnd-tabs-style1 .ui-tabs-nav li.ui-tabs ...

Set the color of the text in the Material UI pagination component to a subtle shade

I would like to customize the color of the text in Material UI's pagination component. Specifically, I want the action button to be white and the text portion to be grey, similar to the left action arrow in the image below. Is there a way for me to ac ...

pull information from mongodb into angular

I am attempting to retrieve data from MongoDB, but I keep seeing [object] [object]. How can I transfer array data from MongoDB to Angular? Here is the code snippet: import { Component, OnInit } from '@angular/core'; import {HttpClient} from &quo ...

Issue with debugging capabilities in Javascript on VSCode has been detected

UPDATE: I'm seeking guidance on configuring VSCode for debugging Javascript. While I'm familiar with JavaScript functioning in a browser, I find it tedious to rely solely on console.log(). I am looking to debug and step through my code effectivel ...

Selecting CSS Properties with jQuery

I am trying to make an image change color to blue and also change the background color to blue when it is clicked inside a div. However, my code doesn't seem to be working as expected. Is there a more efficient way to apply CSS to elements? FIDDLE v ...

"Scrolling with Bootstrap Scroll Spy is causing incorrect sections to be

Can anyone help me with my issue regarding Bootstrap scrollspy settings? It seems to be highlighting the wrong div id, always the last one. Here is the code snippet: Content: <body style="heigt: 100%" data-spy="scroll" data-target="#side-menu"> ...

What is the hierarchy for displaying elements depending on the props?

I have developed a search input component that includes an icon which I want to reposition (either on the left or right side) depending on different scenarios. This input is part of a bootstrap input-group, so modifying the order of elements within my di ...

Why is my nested React Router component failing to load upon page refresh?

Lately, I have been delving into learning react and for the past few weeks. However, I've encountered an issue where when I try to reload the page using the browser's reload button, instead of reloading the component, it simply disappears (turnin ...

Incorporating the Material UI App Bar alongside React Router for an enhanced user

For my web development course project, I am venturing into the world of JavaScript and React to create a website. Utilizing Material UI's appbar for my header design, I have successfully incorporated react router to enable navigation on my site. Howev ...

Steps to convert a phone number into JSON format

The primary focus Upon receiving an MQTT packet, it is displayed as an ASCII array in the buffer after being printed using stringify: packet = { "cmd": "publish", "retain": true, "qos": 1, "dup& ...

Resolving the issue: "How to fix the error "Credentials are not supported if the CORS header 'Access-Control-Allow-Origin' is '*' in React?"

Recently, I encountered some CORS issues while using a third party API in my front-end application. After reaching out to the API maintainers, they lifted the CORS control by adding a * to Access-Control-Allow-Origin, which seemed like the perfect solution ...