Problem
I have created a piece of code for a live pagination, but I don’t like the code. It works it does the job, but I guess I could done it better.
$('.show-content').livequery(function() {
$(this).find('.page-me:not(:first)').hide();
var totalPage = $(this).find('.page-me').length;
for (var i = 0; i <= totalPage - 1; i++) {
$('.modal-pagination').append('<a href="#" id="' + i + '">Page ' + (i + 1) + '</a>')
}
$('.modal-pagination a').live('click', function() {
var thePag = $(this).attr('id');
$('.show-content').find('.page-me').hide();
$('.show-content').find('.page-me:nth(' + thePag + ')').show();
return false;
});
});
Solution
The code looks fine to me. The only things I would personally change is the use of the live()
method (which has been deprecated, and was slow anyway) todelegate()
and the use of the :nth()
selector, which again I believe is not very fast – although I’ve not specifically tested it. In place of that I’d use eq()
.
$('.modal-pagination').delegate('a', 'click', function(e) {
e.preventDefault();
var thePag = $(this).attr('id');
$('.show-content').find('.page-me').hide().eq(thePag -1).show();
});
var toArray = [].slice.call.apply([].slice]);
var contentShow = toArray(document.getElementsByClassName('contentShow'));
contentShow.forEach(function doStuff(element) {
var pageMe = toArray(element.getElementsByClassName('page-me')),
modalPagination = toArray(document.getElementsByClassName));
pageMe.unshift();
pageMe.forEach(function hideElement(element, index) {
element.classList.add('hidden');
modalPagination.forEach(function addLink(modal) {
var link = document.createElement("a");
link.id = index;
link.textContent = 'Page ' + (index + 1);
modal.appenChild(link);
});
});
modalPagination.forEach(function delegateClick(element) {
element.addEventListener('click', function handleClick() {
if (this.tagName !== 'a') return;
var thePage = this.id;
var showContent = toArray(document.getElementsByClassName('show-content'));
showContent.forEach(function doStuffWithPageMe(element) {
var pageMe = toArray(element.getElementsByClassName('page-me'));
for (var i = 0, len = pageMe.length; i < len; i++) {
var page = pageMe[i];
if (i % thePage === 0) {
pageMe.classList.remove('hidden');
} else {
pageMe.classList.add('hidden');
}
}
});
}
});
});
The code is ugly because your logic is ugly. You need to fix your logic and also probably fix your HTML.