I'm working on a website for my custom themes on a blogging site. I want to have a review section, but I only want to have one review per page refresh. I was wondering if there is any way to write a script with jQuery or javascript (I'm not sure which one) to pick a random element from an array (All of the reviews will have a seperate element, each person having a different div ID with a different review) and display that element inside a div called #reviews, and hide the other elements? It sounds very confusing, but basically I need either jQuery or javascript to pick a review and put it in the review section. If anyone could help it'd be greatly appreciated.
3 Answers
Here's one way jsFiddle
<aside id="reviews">
<article class="review"></article>
<article class="review"></article>
<article class="review"></article>
</aside>
and
var $reviews = $('#reviews .review').hide();
$reviews.eq(Math.random()*$reviews.length).show();
But unless you plan on revealing the other reviews at some point (slider, or pagination), you should really do this server side. Sending people content just to hide it is a little wasteful.
2 Comments
.reviews randomly.jQuery is JavaScript. To get a random element from an array, use Math.random():
function getRandomElement(a) {
return a[Math.floor(Math.random() * a.length)];
}
1 Comment
I would use knockout.js which is great for binding JavaScript objects to DOM. You can fill an array of your object and data-bind it to the div. Each time you will bind a random element of the array to the div. The data binding is very simple:
<p>First name: <input data-bind="value: firstName" /></p>
// This is a simple *viewmodel* - JavaScript that defines the data and behavior of your UI
function AppViewModel() {
this.firstName = "Bert";
}
// Activates knockout.js
ko.applyBindings(new AppViewModel());
For more examples see the great tutorials in: Knockout.js tutorials