Changing the Order of Elements

Switching the order of block elements with CSS

As has already been suggested, Flexbox is the answer - particularly because you only need to support a single modern browser: Mobile Safari.

See: http://jsfiddle.net/thirtydot/hLUHL/

You can remove the -moz- prefixed properties if you like, I just left them in for future readers.

    #blockContainer {        display: -webkit-box;        display: -moz-box;        display: box;                -webkit-box-orient: vertical;        -moz-box-orient: vertical;        box-orient: vertical;    }    #blockA {        -webkit-box-ordinal-group: 2;        -moz-box-ordinal-group: 2;        box-ordinal-group: 2;    }    #blockB {        -webkit-box-ordinal-group: 3;        -moz-box-ordinal-group: 3;        box-ordinal-group: 3;    }
    <div id="blockContainer">        <div id="blockA">Block A</div>        <div id="blockB">Block B</div>        <div id="blockC">Block C</div>    </div>

Changing order of list elements

I know a crude way of doing things.

  1. First, make sure your elements are in a list.
  2. Then, allow selecting a single element.
  3. Only show the Move buttons if there's a selection.
  4. Update the index of both the current and previous or next element, swapping them.
  5. Due to the state update, the app gets re-rendered in the right way.

Here's a demo.

import React, { Component } from "react";
import "./styles.css";

export default class App extends Component {
state = {
items: ["Milk", "Curd", "Yogurt"],
currentSelection: -1
};
selectHandler = (idx) => {
let currentSelection = -1;
if (this.state.currentSelection !== idx) {
currentSelection = idx;
}
this.setState({
currentSelection
});
};
handleMove = (dir) => {
const { currentSelection } = this.state;
const items = [...this.state.items];
if (dir === "up") {
// Swap the currentSelection value with the previous one.
let a = items[currentSelection];
items[currentSelection] = items[currentSelection - 1];
items[currentSelection - 1] = a;
} else if (dir === "down") {
// Swap the currentSelection value with the next one.
let a = items[currentSelection];
items[currentSelection] = items[currentSelection + 1];
items[currentSelection + 1] = a;
}
this.setState({
items,
currentSelection: -1
});
};
render() {
const { items, currentSelection } = this.state;
return (
<div>
<p>Click to select and again click to deselect.</p>
<ul>
{items.map((item, key) => (
<li
key={key}
className={currentSelection === key ? "active" : undefined}
onClick={() => this.selectHandler(key)}
>
{item}
</li>
))}
</ul>
{currentSelection !== -1 && (
<div>
<p>What do you wanna do?</p>
<button
disabled={currentSelection === 0}
onClick={(e) => {
e.preventDefault();
this.handleMove("up");
}}
>
Move Up
</button>
<br />
<button
disabled={currentSelection === items.length - 1}
onClick={(e) => {
e.preventDefault();
this.handleMove("down");
}}
>
Move Down
</button>
</div>
)}
</div>
);
}
}

Demo: https://uiyq8.csb.app/

Preview

preview

How to change order of list based on common element in python?

Assuming that each element in l1 is a superstring of some element in l2, you could use next to sort by the index of the first matching element.

>>> l1 = ['foo_x', 'bar_x', 'xyz_x', 'foo_y', 'bar_y', 'xyz_y']    
>>> l2 = ['foo', 'bar', 'xyz']
>>> sorted(l1, key=lambda x: next(i for i, e in enumerate(l2) if e in x))
['foo_x', 'foo_y', 'bar_x', 'bar_y', 'xyz_x', 'xyz_y']

The next means linear complexity (in size of l2) for each element in l1. If the _ is significant, i.e. if the elements in l2 are always the part before the _, you can create a dictionary mapping each element to its index and then look up that index directly using that substring.

>>> l2_idx = {e: i for i, e in enumerate(l2)}
>>> sorted(l1, key=lambda x: l2_idx[x[:x.index("_")]])
['foo_x', 'foo_y', 'bar_x', 'bar_y', 'xyz_x', 'xyz_y']

Both ways, in this form, would fail if there is no matching element in l2, but you can provide both with a default element to be used in that case, e.g. len(l2).

Changing the order of elements

For this simple case (swapping the only two elements), you can just use appendChild():

(() => {  const list = document.querySelector("ul");  list.appendChild(list.firstElementChild);})();
<ul>  <li>List-item #1</li>  <li>List-item #2</li></ul>

Bootstrap - change the order of element

Try using "order" property of flexbox in CSS.

Flex items are displayed in the same order as they appear in the source document by default. The order property can be used to change this ordering.

Sample code to help you understand this : https://jsfiddle.net/bhyqeq5x/

In the above JS fiddle , above 700px , it is rendered as A B (normal behaviour)but below 700px , I am changing the direction of flex box to column so that it appears one below the other and changing the order of A and B as per your requirement.

@media only screen and (max-width: 700px) {  
.container {
flex-direction : column;
}
.A {
order : 2;
}
.B {
order : 1;
}
}

Let me know in comments below if this doesnt help you.

Converting a list to a set changes element order

  1. A set is an unordered data structure, so it does not preserve the insertion order.

  2. This depends on your requirements. If you have an normal list, and want to remove some set of elements while preserving the order of the list, you can do this with a list comprehension:

    >>> a = [1, 2, 20, 6, 210]
    >>> b = set([6, 20, 1])
    >>> [x for x in a if x not in b]
    [2, 210]

    If you need a data structure that supports both fast membership tests and preservation of insertion order, you can use the keys of a Python dictionary, which starting from Python 3.7 is guaranteed to preserve the insertion order:

    >>> a = dict.fromkeys([1, 2, 20, 6, 210])
    >>> b = dict.fromkeys([6, 20, 1])
    >>> dict.fromkeys(x for x in a if x not in b)
    {2: None, 210: None}

    b doesn't really need to be ordered here – you could use a set as well. Note that a.keys() - b.keys() returns the set difference as a set, so it won't preserve the insertion order.

    In older versions of Python, you can use collections.OrderedDict instead:

    >>> a = collections.OrderedDict.fromkeys([1, 2, 20, 6, 210])
    >>> b = collections.OrderedDict.fromkeys([6, 20, 1])
    >>> collections.OrderedDict.fromkeys(x for x in a if x not in b)
    OrderedDict([(2, None), (210, None)])

change the order of elements to the top

var _4th = document.getElementById('4'); // BTW. numeric IDs are not valid
var parent = _4th.parentNode;
var _1st = parent.firstChild;

parent.insertBefore(_4th, _1st);

a JSFiddle example

How to change order of elements in html using javascript

Keeping Your Animals Contained

Consider creating a container for all of your game elements as you only want to randomize their order as you don't want to get the title mixed up in all of this :

<div class='game-container'>
<div class="penguin1"></div>
<div class="penguin2"></div>
<div class="penguin3"></div>
<div class="penguin4"></div>
<div class="penguin5"></div>
<div class="penguin6"></div>
<div class="penguin7"></div>
<div class="penguin8"></div>
<div class="yeti">
</div>

Shuffling Them Around

This should make them easier to randomize through a simple jQuery extension function like this one mentioned in this related thread :

$.fn.randomize = function(selector){
(selector ? this.find(selector) : this).parent().each(function(){
$(this).children(selector).sort(function(){
return Math.random() - 0.5;
}).detach().appendTo(this);
});
return this;
};

You can combine these two approaches by then simply calling the following when your page has loaded :

$(document).ready(function(){
// Define your randomize function here

// Randomize all of the elements in your container
$('.game-container').randomize('div');
});

Example

Sample Image

$.fn.randomize = function(selector){    (selector ? this.find(selector) : this).parent().each(function(){        $(this).children(selector).sort(function(){            return Math.random() - 0.5;        }).detach().appendTo(this);    });
return this;};// Randomize all of the <div> elements in your container$(".game-container").randomize('div');
.game-container { width: 300px; }
.penguin { background: url('http://vignette1.wikia.nocookie.net/farmville/images/b/be/Baby_Penguin-icon.png/revision/latest?cb=20110103080900'); height: 100px; width: 100px; display: inline-block; }.yeti { background: url('http://www.badeggsonline.com/beo2-forum/images/avatars/Yeti.png?dateline=1401638613'); height: 100px; width: 100px; display: inline-block; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script><div class='game-container'>  <div class='penguin'></div>  <div class='penguin'></div>  <div class='penguin'></div>  <div class='penguin'></div>  <div class='penguin'></div>  <div class='penguin'></div>  <div class='penguin'></div>  <div class='yeti'></div>  <div class='penguin'></div></div>


Related Topics



Leave a reply



Submit