Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this code in my callback execute on page load?

Javascript:

$('#pagination-demo').twbsPagination({
    totalPages: 35,
    visiblePages: 7,
    onPageClick: function (event, page) {
        console.log('Why does this run on load?');
    }
});

Markup:

<!DOCTYPE html>
<html>

<head>
    <script src="http://code.jquery.com/jquery.min.js"></script>
    <link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
    <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>

    <script src="http://esimakin.github.io/twbs-pagination/js/jquery.twbsPagination.js"></script>
    <meta charset="utf-8">
    <title>JS Bin</title>
</head>

<body>
    <ul id="pagination-demo" class="pagination-sm"></ul>
</body>

</html>

JS Bin here: http://jsbin.com/potekina/1/edit

In the onPageClick callback I log to the console "Why does this run on load?" I dont understand why that code is running on load if its only supposed to happen when links are clicked. Why does it run on load?

like image 230
Rigil Avatar asked Jun 12 '26 10:06

Rigil


2 Answers

There is an option to add in init :

$('.pagination').twbsPagination({
    initiateStartPageClick: false
});
like image 164
dryobs Avatar answered Jun 14 '26 23:06

dryobs


From the source:

init: function (options) {
   ...
   this.$element.bind('page', this.options.onPageClick);
   ...
   this.$element.trigger('page', this.options.startPage);
}

The twpsPagination plugin is apparently triggering onPageClick in init. It's a peculiarity of the plugin, not an anomaly in your code. We can't give an answer to what the authors' reasoning behing that design choice was.

Presumably, the event was intended for post page-render setup, and they've guessed that it's just as relevant for setting up the initial page as for subsequent page loads, but I'll give you that "page click" is a bit of a misnomer then.

If you really want to have your scripts run only on actual page clicks, you'd have to perform some workaround, such as a variable:

var firstPageClick = true;

onPageClick: function() {
   if(firstPageClick) {
       firstPageClick = false;
       return;
   }

   // actual event listener
}
like image 33
David Hedlund Avatar answered Jun 14 '26 23:06

David Hedlund



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!