skip to Main Content

Here is my code. At the moment when you click on a checkbox, it automatically moves to the top of the list.
I want to do this by clicking on a button.
By default the order is normal and when you click on the order button, the checked items should go to the top.

One approach would be using –var to change the value of order dynamically, but I could not implement it.

div { display: flex; flex-direction: column; }
label:has(input:checked) { order: -9999; }
<h3>Topic</h3>
<div>
  <label> <input type=checkbox> q </label>
  <label> <input type=checkbox> w </label>
  <label> <input type=checkbox> e </label>
</div>
 <button id="alertButton">Click me</button>
<script>
    document.getElementById("alertButton").addEventListener("click", function() {
        
    });
</script>

2

Answers


  1. You’ll need some Javascript to toggle the order once you press a button.

    Once way is to use querySelectorAll() to find all checked boxes, then insertBefore it on the second parent (to include the label).

    Small demo, when you press Click me, the checked boxes will be places as first childs of the parent div.

    document.getElementById("alertButton").addEventListener("click", function() {
        const checkedBoxes = document.querySelectorAll('input:checked');
        checkedBoxes.forEach(b => {
            const parentDiv = b.parentNode.parentNode;
            parentDiv.insertBefore(b.parentNode, parentDiv.firstChild);
        });
    });
    div { display: flex; flex-direction: column; }
    <h3>Topic</h3>
    <div>
      <label> <input type=checkbox> q </label>
      <label> <input type=checkbox> w </label>
      <label> <input type=checkbox> e </label>
    </div>
    <button id="alertButton">Click me</button>
    Login or Signup to reply.
  2. CSS Only :
    Setting the default order for labels as 100 and everytime input is checked we are changing the order from 100 to 1.

    div { 
     display: flex; 
     flex-direction: column;
    }
    label{
     order:100;
    }
    label:has(input:checked) {
     order: 1; 
    }
    <h3>Topic</h3>
    <div>
      <label> <input type=checkbox> q </label>
      <label> <input type=checkbox> w </label>
      <label> <input type=checkbox> e </label>
    </div>
     <button id="alertButton">Click me</button>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search