reoder bootstrap column on click funtion

Issue

I want to switch columns order using bootstrap and jquerry on click. So I’ve done this for the left button, but it doesn’t work:

$("#left").on("click",
    function() {
        $("#A").removeClass('order-1').addClass('order-2');
        $("#B").removeClass('order-2').addClass('order-1');
        console.log("1 done")
    }, 
    function() {
        $("#A").removeClass('order-2').addClass('order-1');
        $("#B").removeClass('order-1').addClass('order-2');
    }
);
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="arrow position-absolute top-50 start-0 translate-middle-y ps-2" id="left">left</div>
<div class="arrow position-absolute top-50 end-0 translate-middle-y pe-2" id="right">right</div>


        <div class="col-6 bg-success d-flex align-items-end order-1" id="A">one
        </div>
        <div class="col-6 bg-primary d-flex align-items-end order-2" id="B">two
        </div>

Solution

Here you go…

There are a few problems.

  1. You tagged this questions as bootstrap-4, but used bootstrap-5 in your code.
  2. Bootstrap classes order-1 and order-2 were not even working because you need to wrap col classes with a row class.
  3. Use jQuery toggleClass to change classes.

See the snippet below.

$(document).ready(function() {
  $(".col-6").click(function() {
    $("#A").toggleClass("order-1 order-2");
    $("#B").toggleClass("order-2 order-1");
  });
});
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="row">
  <div class="col-6 bg-success d-flex align-items-end order-1" id="A">one</div>
  <div class="col-6 bg-primary d-flex align-items-end order-2" id="B">two</div>
</div>

Answered By – Cervus camelopardalis

Answer Checked By – Mildred Charles (AngularFixing Admin)

Leave a Reply

Your email address will not be published.