Reputation: 21
I know there's a lot of questions like this, but still can't figure it out.
<div class="message"></div>
<button id="getMessage">Get Quote</button>
$.getJSON("http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1", function(data) {
var content = data[0].content + data[0].title;
$("#getMessage").on("click", function() {
$(".message").html(content);
});
});
the problems is that on("click")
only works once, but I want it to work every time the button is clicked. What am I doing wrong?
Upvotes: 1
Views: 2198
Reputation: 2709
Try this:
$("#getMessage").on("click", function() {
$.getJSON("http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1", function(data) {
var content = data[0].content + data[0].title;
$(".message").html(content);
});
});
Upvotes: 0
Reputation: 324620
You seem to be assuming that just because "quotesondesign" gives you a random quote, that var content
is somehow magical in its ability to generate further random quotes. This is not the case.
All your on('click')
does is take the single random quote that was fetched and display it. If it's already been displayed, it will just display it again, replacing the first and seeming to do nothing.
You need to put that $.getJSON
call inside the on('click')
so that the "quotesondesign" call is made a second time to retrieve another quote.
Alternatively, increase posts_per_page
to a higher number to get a selection of quotes, and move the var content
inside the on('click')
, replacing 0
with some suitable random number (eg. var selected = Math.floor(Math.random()*data.length), content = data[selected].content + data[selected].title;
)
Upvotes: 2