0

I'm trying to figure out how to select a random item from a json array and show that item in a DIV.

Below is my code. I hope someone can help.

var url = 'path to json';

$.getJSON(url, function(json) {                     
    var featuredRecipe = '';
    $.each(json, function(i, item) {
        featuredRecipe += '<div class="col-md-12 col-sm-12 img-margin">' + ' <div class="addthis_inline_share_toolbox" data-url="' + item.recipePageURL +'" data-title="' + item.recipeName + '"></div>' + '<a href="' + item.recipePageURL +'">' + '<img class="img-responsive" src="' + item.recipeImageCategoryURL + '">' + '</a>' + '<a href="' + item.recipePageURL +'">' + '<h3 class="recipeSubCategoryImgCaption">' + item.recipeName + '</h3>' + '</a>' + '</div>';
    });
    $('#featuredRecipe').html(featuredRecipe);                      
});

I tried using this, but I am not sure what I have to do next if I include it:

var rand = json[Math.floor(Math.random()*json.length)];
mhu
  • 17,720
  • 10
  • 62
  • 93
Tom
  • 305
  • 1
  • 3
  • 15
  • So you mean you don't want to build the html in order of the data. But you want to jumble it up.. right? – Rajshekar Reddy Dec 12 '16 at 15:51
  • 2
    You are basically looking for this: http://stackoverflow.com/questions/3718282/javascript-shuffling-objects-inside-an-object-randomize or http://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array – Chris Dec 12 '16 at 15:51
  • Well currently it shows all the items in my JSON recipe DB. But i want to take that code and randomize the contents and only show one item from the database in the div. – Tom Dec 12 '16 at 15:51
  • @RajshekarReddy your correct except i just want to show one item from the div instead of all. could you please show me what i need to do? – Tom Dec 12 '16 at 15:56
  • So you just want to build featuredRecipe from rand rather than looping over everything? `var featuredRecipe = '
    ' + '
    ' + '' etc. etc.';`
    – Steve Dec 12 '16 at 15:56
  • i tired this but it doesnt work. because i need to loop over the items but then randomize them and only show one on the page – Tom Dec 12 '16 at 16:00
  • 1
    @Tom How about you read the link I posted and just show the first element? Add [0] and you are done... you can literally just copy and paste the first shuffle function... – Chris Dec 12 '16 at 16:03
  • hi chris i was trying this but i cant seem to get it to work. does it need to go inside my loop? – Tom Dec 12 '16 at 16:07

0 Answers0