PDA

View Full Version : Help with Quotes, random and number



Amotne1
10-11-2016, 03:28 AM
Hello All. I need to use jquery to post quotes between each box on a page. The quotes are coming from a data source. The amount of quotes posted between the boxes will vary depending on the amount of boxes. Example. If there are only 3 boxes on a page then I only need to post two quotes, on in the space between each box. The number of boxes will vary, so the number of posts displayed will change as well.

I have a plunker at
https://plnkr.co/edit/5FUiNa0G5XoXEWsj2HxK?p=preview

jscheuer1
10-11-2016, 03:27 PM
First of all you have several typos on the word quote:


$.getJSON('qoutes.json', function(data){
alert('got it!')

})

Also within that file:


{
"quotes":[
{
"qoute": "To be or not to be, that is the question"

},

{
"qoute": "It is better to have lived and loved, than to not have lived at all"

},

{
"qoute": "Loose lips, sink ships"

}


]

}

Those kinds of things can really mess up code. Once I straightened that out, this seemed workable:


<!DOCTYPE html>
<html>
<head>
<title>Quotes Demo</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<style>
.qbox{color:red}
.quote{color:blue;}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script>
jQuery(function($){ /* same as document ready */
var $div = $('<div>', {class: 'quote'}).append('<p>'), qs, ql, idx;
function sf(){return 0.5 - Math.random();}
$.getJSON('quotes.json', function(data){
qs = data.quotes; ql = qs.length;
$('.qbox').each(function(i, qb){
!(idx = i % ql) && qs.sort(sf);
$div.clone().find('p').text(qs[idx].quote).end().insertAfter(qb);
});
});
});
</script>
</head>
<body>
<div class="qbox">
This is box 1
</div>

<div class="qbox">
This is box 2
</div>

<div class="qbox">
This is box 3
</div>

<div class="qbox">
This is box 4
</div>

<div class="qbox">
This is box 5
</div>
</body>
</html>