JavaScript - Random Order Content Using jQuery
Submitted by razormist on Sunday, August 11, 2019 - 10:03.
In this tutorial we will create a Random Order Content using jQuery. This code will automatically randomize the web content when user load the webpage. The code itself use onclick function to call a function that randomize the html div content by using Math.floor() in order to change the index position of each content. This is a user-friendly program feel free to modify it.
We will be using jQuery a JavaScript framework that design to simplify HTML DOM tree traversal and manipulation. It can do more in a single line of code than JavaScript can do in a whole function.
There you have it we successfully created a Random Order Content using jQuery. I hope that this simple tutorial help you to what you are looking for. For more updates and tutorials just kindly visit this site. Enjoy Coding!
Getting Started:
This is the link for the bootstrap that i used for the layout design https://getbootstrap.com/. And this is the link for the jquery that i used in this tutorial https://jquery.com/.The Main Interface
This code contains the interface of the application. To create this just write these block of code inside the text editor and save this as index.html.- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1" />
- <link rel="stylesheet" type="text/css" href="css/bootstrap.css" />
- </head>
- <body onload="displayRandom();">
- <nav class="navbar navbar-default">
- <div class="container-fluid">
- </div>
- </nav>
- <div class="col-md-6 well">
- <hr style="border-top:1px dotted #ccc;"/>
- <div class="content alert alert-info">
- </div>
- <div class="content alert alert-danger">
- </div>
- <div class="content alert alert-success">
- </div>
- </div>
- </body>
- </html>
Creating the Script
This code contains the script of the application. This code will automatically randomize the content when load. To do this just copy and write these block of codes as shown below inside the text editor and save it as script.js inside the js directory- function displayRandom(){
- var contents = $(".content");
- for(var i = 0; i < contents.length; i++){
- var target = Math.floor(Math.random() * contents.length -1) + 1;
- var target2 = Math.floor(Math.random() * contents.length -1) +1;
- contents.eq(target).before(contents.eq(target2));
- }
- }
Add new comment
- 211 views