Reputation: 97
I have a load more button on my page
<a class="btn btn-link border-top px-3 mt-5" role="button" id="reveal">Load more</a></p>
And an onclick function that loads content inside this div:
<div id="ajax-content" class="row m-0">
</div>
The script works and loads more content every time I click the button:
<script>
$('#reveal').on('click', function() {
$('#ajax-content').load('/wp-content/themes/template/ajax-news.php?offset=4');
$('#ajax-content').attr('id', '#ajax-contented');
})
</script>
But I need the offset-variable to increase by 4 every time I click it, so the content that loads is not the same. Hope anyone can point me to the right direction to make this work.
Upvotes: 2
Views: 247
Reputation: 337713
To achieve this you could use a data
attribute on the a
element which you increment by 4
on each successive click event:
$('#reveal').on('click', function(e) {
e.preventDefault();
let offset = ($(this).data('offset') || 0) + 4;
//$('#ajax-content').load('/wp-content/themes/heidner/ajax-aktuelt.php?offset=' + offset);
$('#ajax-content').html(offset);
$(this).data('offset', offset);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p><a href="#" class="btn btn-link border-top px-3 mt-5" role="button" id="reveal">Last flere saker</a></p>
<div id="ajax-content" class="row m-0"></div>
This would also be possible with a global variable, but they are bad practice and should be avoided where possible.
In addition, note that changing id
attributes at runtime is also not good practice. In this case it would stop the repeated clicks from updating the content. As such I removed that line.
Upvotes: 1