Tutorial :Jquery - Select random JSON Object



Question:

I have this jquery code to output the entries in a JSON file on page load...

$.getJSON('b.json', function(data) {        $('#dictionary').empty().hide();              $.each(data, function(entryIndex, entry) {          var html = '<div class="entry">';          html += '<h3 class="title">' + entry['title'] + '</h3>';          html += '<div class="link_url">' + entry['link_url'] + '</div>';          html += '<div class="image_src">';          html += entry['image_src'];          if (entry['quote']) {            html += '<div class="quote">';            $.each(entry['quote'], function(lineIndex, line) {              html += '<div class="quote-line">' + line + '</div>';            });            if (entry['author']) {              html += '<div class="quote-author">' + entry['author'] + '</div>';            }            html += '</div>';          }          html += '</div>';          html += '</div>';            $('#dictionary').append(html).fadeIn();        });      });  

What I need to do is load one of these entries, randomly.

Any advice appreciated.

Many thanks, C

The JSON file is...

[    {      "title": "WESITE NAME",      "link_url": "http://www.website.com",      "image_src": "http://www.website.com/images/recent.jpg",    },    {      "title": "WESITE NAME",      "link_url": "http://www.website.com",      "image_src": "http://www.website.com/images/recent.jpg",    },    {      "title": "WESITE NAME",      "link_url": "http://www.website.com",      "image_src": "http://www.website.com/images/recent.jpg",    }  ]  


Solution:1

$.getJSON('b.json', function(data) {     var entry = data[Math.floor(Math.random()*data.length)];    //do the same exact thing with entry  }  


Solution:2

Looks like you want a random entry from an array.

try:

var random_entry = entry[Math.floor(Math.random() * entry.length)]  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »