Ad
Order By Random A List Of Div Elements With JS
I have a category that contains more than 200 newsitems, on the homepage I display the last 20 newsitems.
<div class="container-category">
<div class="col-3">item 1</div>
<div class="col-3">item 2</div>
<div class="col-3">item 3</div>
<div class="col-3">item 4</div>
<div class="col-3">item ..n</div>
</div>
How to make the list of <div class="col-3">
appear randomly with Javascript ?
OrderBy = random
Ad
Answer
The ideal way to shuffle the categories is through the backend. But incase you can't, we can borrow the shuffle functionality here.
Use jQuery get()
to get the array of category divs. Use the function to shuffle the array and use html()
to update the content.
function shuffle(array) {
var currentIndex = array.length,
temporaryValue, randomIndex;
// While there remain elements to shuffle...
while (0 !== currentIndex) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
var categories = shuffle($(".container-category>div").get());
$(".container-category").html(categories);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container-category">
<div class="col-3">item 1</div>
<div class="col-3">item 2</div>
<div class="col-3">item 3</div>
<div class="col-3">item 4</div>
</div>
Ad
source: stackoverflow.com
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
Ad