Reputation: 92
I'm currently loading photos and text to a div using jquery appendTo. I'm trying to make it so that on every click, it simply reloads what's being appended, but it instead just continues to append new elements rather than clear the old one and load the new. My function currently looks like this:
function load_new() {
$.getJSON('images.json', function(data) {
var $item = data.images[Math.floor(Math.random()*data.images.length)];
var $image = $('<script id="scripty"> $.backstretch("' + $item.image + '", {speed: 1200}); </script>');
var $caption = $('<h1>' + $item.caption + '</h1>');
$image.appendTo('body');
$caption.appendTo('.text');
});
};
Any help is greatly appreciated!!!
Upvotes: 0
Views: 160
Reputation: 51
I'm not sure to get you but append add new elements inside container after existing elements inside container. If you want to replace content you should use $(element).html(newContent)
Upvotes: 1
Reputation: 457
I would make your structure different. You could have structure like this:
<body>
<div id="image"></div>
<div class="text">
<div class="append-text"></div>
</div>
</body>
And then your function can look more like this:
function load_new() {
$.getJSON('images.json', function(data) {
var $item = data.images[Math.floor(Math.random()*data.images.length)];
var $image = $('<script id="scripty"> $.backstretch("' + $item.image + '", {speed: 1200}); </script>');
var $caption = $('<h1>' + $item.caption + '</h1>');
$('#image').html($image);
$('.append-text').html($caption);
}
And then just rearrange the divs to where you would like the content to appear when you update them.
Upvotes: 1