JavaScript: Building Table Sorting and Pagination

As part of my job in managing this blog, I check my stats frequently, and I've noticed that some of my more basic Vue.js articles have had consistently good traffic for quite some time. As I find myself doing more and more with "regular" JavaScript (sometimes referred to as "Vanilla JavaScript", but I'm not a fan of the term) I thought it would be a good idea to update those old posts for folks who would rather skip using a framework. With that in mind, here is my update to my post from over four years ago, Building Table Sorting and Pagination in Vue.js

You don't need to read that old post as I think the title is rather descriptive. How can we use JavaScript to take a set of data - render it in a table - and support both sorting and pagination? Here's how I solved this. Before I begin, a quick note. I'll be loading all of my data and while that works with a "sensible" amount of data, you don't want to be sending hundreds of thousands of rows of data to the client and sorting and paging in the client. That being said, I think an entirely client-side solution is absolutely safe if you understand the size of your data and know it's not going to impact performance.

Pagination in MS SQL Server

What Is Pagination?

Pagination is the process of dividing large data into smaller data sets in discrete pages. It is widely used in web applications.

How Does Pagination Work in MS SQL Server?

In MS SQL Server, we can achieve the pagination functionality by using OFFSET and FETCH clauses with ORDER BY in a SELECT statement.

Server Side Pagination Using ASP.NET Core And Angular 8 – Part Two

Introduction

In this article, we will learn how we create server-side pagination, which is very useful whenever we need to display a large number of records. This is the second part of my article on server-side pagination, you can check out the first part of this article from the link below. 

How It Will Work?

In this article, we are going to show previous and next buttons with custom logic so whenever we click on next button it shows the next page of records. For example, suppose we are on page one and after clicking on next, it would show the second page of records. However, here we will see different logic. 

Backend

Here in the previous article we have already created database and tables so there's no need to create it again. If you don't have the related database, tables, and stored procedure, then please check the previous article

Web API

Complete code of pagination controller:   

How to Change the Number of Posts Displayed On Your WordPress Blog Page

Do you want to change the number of posts displayed on your WordPress blog page? By default, all WordPress archive pages show a maximum of 10 posts per page.

However, you can change them easily from your dashboard settings and show as many articles as you like.

In this article, we will show you how to easily change the number of posts displayed on your WordPress blog page with just 2 simple steps.

Change the Number of Posts Displayed on Your WordPress Blog Page

The first thing you need to do is login to your WordPress dashboard and go to Settings » Reading page. Next, you need to change the value of ‘Blog pages show at most’ option to any number of posts you want to display.

Change Number of Posts on Your Blog Page in WordPress

Don’t forget to click on the ‘Save Changes’ button to store your settings.

Now your WordPress blog and archive pages will show the number of posts that you want to display.

How Many Posts Should I Display on My Blog Page?

Usually, bloggers display 10 posts per page as set by default. It seems an appropriate number to show from the user-experience and SEO (Search Engine Optimization) perspective.

You can display as many posts as you like, but we do not recommend choosing a number higher than 10 especially when you are not showing excerpts.

Mainly because the more posts you display on a page, the bigger the page size will be, which makes it slower to load.

On WPBeginner’s Blog and Archive pages, we show 10 posts with an excerpt and the featured image. This makes it easier for our users to browse the archives quickly, and it offers a better user experience.

We hope this article helped you change the number of posts displayed on your blog page. You may also want to see our guide on how to schedule your posts in WordPress to be published at a future time.

If you liked this article, then please subscribe to our YouTube Channel for WordPress video tutorials. You can also find us on Twitter and Facebook.

The post How to Change the Number of Posts Displayed On Your WordPress Blog Page appeared first on WPBeginner.

Creating a Reusable Pagination Component in Vue

The idea behind most of web applications is to fetch data from the database and present it to the user in the best possible way. When we deal with data there are cases when the best possible way of presentation means creating a list.

Depending on the amount of data and its content, we may decide to show all content at once (very rarely), or show only a specific part of a bigger data set (more likely). The main reason behind showing only part of the existing data is that we want to keep our applications as performant as possible and avoid loading or showing unnecessary data.

If we decide to show our data in "chunks" then we need a way to navigate through that collection. The two most common ways of navigating through set of data are:

The first is pagination, a technique that splits the set of data into a specific number of pages, saving users from being overwhelmed by the amount of data on one page and allowing them to view one set of results at a time. Take this very blog you're reading, for example. The homepage lists the latest 10 posts. Viewing the next set of latest posts requires clicking a button.

The second common technique is infinite scrolling, something you're likely familiar with if you've ever scrolled through a timeline on either Facebook or Twitter.

The Apple News app also uses infinite scroll to browse a list of articles.

We're going to take a deeper look at the first type in this post. Pagination is something we encounter on a near-daily basis, yet making it is not exactly trivial. It's a great use case for a component, so that's exactly what we're going to do. We will go through the process of creating a component that is in charge of displaying that list, and triggering the action that fetches additional articles when we click on a specific page to be displayed. In other words, we’re making a pagination component in Vue.js like this:

Let's go through the steps together.

Step 1: Create the ArticlesList component in Vue

Let’s start by creating a component that will show a list of articles (but without pagination just yet). We’ll call it ArticlesList. In the component template, we’ll iterate through the set of articles and pass a single article item to each ArticleItem component.

// ArticlesList.vue
<template>
  <div>
    <ArticleItem
      v-for="article in articles"
      :key="article.publishedAt"
      :article="article"
    />
  </div>
</template>

In the script section of the component, we set initial data:

  • articles: This is an empty array filled with data fetched from the API on mounted hook.
  • currentPage: This is used to manipulate the pagination.
  • pageCount : This is the total number of pages, calculated on mounted hook based on the API response.
  • visibleItemsPerPageCount: This is how many articles we want to see on a single page.

At this stage, we fetch only first page of the article list. This will give us a list two articles:

// ArticlesList.vue
import ArticleItem from "./ArticleItem"
import axios from "axios"
export default {
  name: "ArticlesList",
  static: {
    visibleItemsPerPageCount: 2
  },
  data() {
    return {
      articles: [],
      currentPage: 1,
      pageCount: 0
    }
  },
  components: { 
    ArticleItem, 
  },
  async mounted() {
    try {
      const { data } = await axios.get(
        `?country=us&page=1&pageSize=${
          this.$options.static.visibleItemsPerPageCount
        }&category=business&apiKey=065703927c66462286554ada16a686a1`
      )
      this.articles = data.articles
      this.pageCount = Math.ceil(
        data.totalResults / this.$options.static.visibleItemsPerPageCount
      )
    } catch (error) {
      throw error
    }
  }
}

Step 2: Create pageChangeHandle method

Now we need to create a method that will load the next page, the previous page or a selected page.

In the pageChangeHandle method, before loading new articles, we change the currentPage value depending on a property passed to the method and fetch the data respective to a specific page from the API. Upon receiving new data, we replace the existing articles array with the fresh data containing a new page of articles.

// ArticlesList.vue
...
export default {
...
  methods: {
    async pageChangeHandle(value) {
      switch (value) {
        case 'next':
          this.currentPage += 1
          break
        case 'previous':
          this.currentPage -= 1
          break
        default:
          this.currentPage = value
      }
      const { data } = await axios.get(
        `?country=us&page=${this.currentPage}&pageSize=${
          this.$options.static.visibleItemsPerPageCount
        }&category=business&apiKey=065703927c66462286554ada16a686a1`
      )
      this.articles = data.articles
    }
  }
}

Step 3: Create a component to fire page changes

We have the pageChangeHandle method, but we do not fire it anywhere. We need to create a component that will be responsible for that.

This component should do the following things:

  1. Allow the user to go to the next/previous page.
  2. Allow the user to go to a specific page within a range from currently selected page.
  3. Change the range of page numbers based on the current page.

If we were to sketch that out, it would look something like this:

Let’s proceed!

Requirement 1: Allow the user to go to the next or previous page

Our BasePagination will contain two buttons responsible for going to the next and previous page.

// BasePagination.vue
<template>
  <div class="base-pagination">
    <BaseButton
      :disabled="isPreviousButtonDisabled"
      @click.native="previousPage"
    >
      ←
    </BaseButton>
    <BaseButton
      :disabled="isNextButtonDisabled"
      @click.native="nextPage"
    >
      →
    </BaseButton>
  </div>
</template>

The component will accept currentPage and pageCount properties from the parent component and emit proper actions back to the parent when the next or previous button is clicked. It will also be responsible for disabling buttons when we are on the first or last page to prevent moving out of the existing collection.

// BasePagination.vue
import BaseButton from "./BaseButton.vue";
export default {
  components: {
    BaseButton
  },
  props: {
    currentPage: {
      type: Number,
      required: true
    },
    pageCount: {
      type: Number,
      required: true
    }
  },
  computed: {
    isPreviousButtonDisabled() {
      return this.currentPage === 1
    },
    isNextButtonDisabled() {
      return this.currentPage === this.pageCount
    }
  },
  methods: {
    nextPage() {
      this.$emit('nextPage')
    },
    previousPage() {
      this.$emit('previousPage')
    }
  }

We will render that component just below our ArticleItems in ArticlesList component.

// ArticlesList.vue
<template>
  <div>
    <ArticleItem
      v-for="article in articles"
      :key="article.publishedAt"
      :article="article"
    />
    <BasePagination
      :current-page="currentPage"
      :page-count="pageCount"
      class="articles-list__pagination"
      @nextPage="pageChangeHandle('next')"
      @previousPage="pageChangeHandle('previous')"
    />
  </div>
</template>

That was the easy part. Now we need to create a list of page numbers, each allowing us to select a specific page. The number of pages should be customizable and we also need to make sure not to show any pages that may lead us beyond the collection range.

Requirement 2: Allow the user to go to a specific page within a range

Let's start by creating a component that will be used as a single page number. I called it BasePaginationTrigger. It will do two things: show the page number passed from the BasePagination component and emit an event when the user clicks on a specific number.

// BasePaginationTrigger.vue
<template>
  <span class="base-pagination-trigger" @click="onClick">
    {{ pageNumber }}
  </span>
</template>
<script>
export default {
  props: {
    pageNumber: {
      type: Number,
      required: true
    }
  },
  methods: {
    onClick() {
      this.$emit("loadPage", this.pageNumber)
    }
  }
}
</script>

This component will then be rendered in the BasePagination component between the next and previous buttons.

// BasePagination.vue
<template>
  <div class="base-pagination">
    <BaseButton />
    ...
    <BasePaginationTrigger
      class="base-pagination__description"
      :pageNumber="currentPage"
      @loadPage="onLoadPage"
    />
    ...
    <BaseButton />
  </div>
</template>

In the script section, we need to add one more method (onLoadPage) that will be fired when the loadPage event is emitted from the trigger component. This method will receive a page number that was clicked and emit the event up to the ArticlesList component.

// BasePagination.vue
export default {
  ...
    methods: {
    ...
    onLoadPage(value) {
      this.$emit("loadPage", value)
    }
  }
}

Then, in the ArticlesList, we will listen for that event and trigger the pageChangeHandle method that will fetch the data for our new page.

// ArticlesList
<template>
  ...
    <BasePagination
      :current-page="currentPage"
      :page-count="pageCount"
      class="articles-list__pagination"
      @nextPage="pageChangeHandle('next')"
      @previousPage="pageChangeHandle('previous')"
      @loadPage="pageChangeHandle"
    />
  ...
</template>

Requirement 3: Change the range of page numbers based on the current page

OK, now we have a single trigger that shows us the current page and allows us to fetch the same page again. Pretty useless, don't you think? Let's make some use of that newly created trigger component. We need a list of pages that will allow us to jump from one page to another without needing to go through the pages in between.

We also need to make sure to display the pages in a nice manner. We always want to display the first page (on the far left) and the last page (on the far right) on the pagination list and then the remaining pages between them.

We have three possible scenarios:

  1. The selected page number is smaller than half of the list width (e.g. 1 - 2 - 3 - 4 - 18)
  2. The selected page number is bigger than half of the list width counting from the end of the list (e.g. 1 - 15 - 16 - 17 - 18)
  3. All other cases (e.g. 1 - 4 - 5 - 6 - 18)

To handle these cases, we will create a computed property that will return an array of numbers that should be shown between the next and previous buttons. To make the component more reusable we will accept a property visiblePagesCount that will specify how many pages should be visible in the pagination component.

Before going to the cases one by one we create few variables:

  • visiblePagesThreshold:- Tells us how many pages from the centre (selected page should be shown)
  • paginationTriggersArray: Array that will be filled with page numbers
  • visiblePagesCount: Creates an array with the required length
// BasePagination.vue
export default {
  props: {
    visiblePagesCount: {
      type: Number,
      default: 5
    }
  }
  ...
  computed: {
    ...
      paginationTriggers() {
        const currentPage = this.currentPage
        const pageCount = this.pageCount
        const visiblePagesCount = this.visiblePagesCount
        const visiblePagesThreshold = (visiblePagesCount - 1) / 2
        const pagintationTriggersArray = Array(this.visiblePagesCount - 1).fill(0)
      }
    ...
    }
  ...
}

Now let's go through each scenario.

Scenario 1: The selected page number is smaller than half of the list width

We set the first element to always be equal to 1. Then we iterate through the list, adding an index to each element. At the end, we add the last value and set it to be equal to the last page number — we want to be able to go straight to the last page if we need to.

if (currentPage <= visiblePagesThreshold + 1) {
  pagintationTriggersArray[0] = 1
  const pagintationTriggers = pagintationTriggersArray.map(
    (paginationTrigger, index) => {
      return pagintationTriggersArray[0] + index
    }
  )
  pagintationTriggers.push(pageCount)
  return pagintationTriggers
}
Scenario 2: The selected page number is bigger than half of the list width counting from the end of the list

Similar to the previous scenario, we start with the last page and iterate through the list, this time subtracting the index from each element. Then we reverse the array to get the proper order and push 1 into the first place in our array.

if (currentPage >= pageCount - visiblePagesThreshold + 1) {
  const pagintationTriggers = pagintationTriggersArray.map(
    (paginationTrigger, index) => {
      return pageCount - index
    }
  )
  pagintationTriggers.reverse().unshift(1)
  return pagintationTriggers
}
Scenario 3: All other cases

We know what number should be in the center of our list: the current page. We also know how long the list should be. This allows us to get the first number in our array. Then we populate the list by adding an index to each element. At the end, we push 1 into the first place in our array and replace the last number with our last page number.

pagintationTriggersArray[0] = currentPage - visiblePagesThreshold + 1
const pagintationTriggers = pagintationTriggersArray.map(
  (paginationTrigger, index) => {
    return pagintationTriggersArray[0] + index
  }
)
pagintationTriggers.unshift(1);
pagintationTriggers[pagintationTriggers.length - 1] = pageCount
return pagintationTriggers

That covers all of our scenarios! We only have one more step to go.

Step 5: Render the list of numbers in BasePagination component

Now that we know exactly what number we want to show in our pagination, we need to render a trigger component for each one of them.

We do that using a v-for directive. Let's also add a conditional class that will handle selecting our current page.

// BasePagination.vue
<template>
  ...
  <BasePaginationTrigger
    v-for="paginationTrigger in paginationTriggers"
    :class="{
      'base-pagination__description--current':
        paginationTrigger === currentPage
    }"
    :key="paginationTrigger"
    :pageNumber="paginationTrigger"
    class="base-pagination__description"
    @loadPage="onLoadPage"
  />
  ...
</template>

And we are done! We just built a nice and reusable pagination component in Vue.

When to avoid this pattern

Although this component is pretty sweet, it’s not a silver bullet for all use cases involving pagination.

For example, it’s probably a good idea to avoid this pattern for content that streams constantly and has a relatively flat structure, like each item is at the same level of hierarchy and has a similar chance of being interesting to the user. In other words, something less like an article with multiple pages and something more like main navigation.

Another example would be browsing news rather than looking for a specific news article. We do not need to know where exactly the news is and how much we scrolled to get to a specific article.

That’s a wrap!

Hopefully this is a pattern you will be able to find useful in a project, whether it’s for a simple blog, a complex e-commerce site, or something in between. Pagination can be a pain, but having a modular pattern that not only can be re-used, but considers a slew of scenarios, can make it much easier to handle.

The post Creating a Reusable Pagination Component in Vue appeared first on CSS-Tricks.

How to Paginate Comments in WordPress (Step by Step)

Have you noticed that your blog posts with a lot of comments load slower than other posts? That’s because loading so many comments increase server load which increases your average page load time.

Having a lot of comments is a good thing because it means that your users are engaged with your content. Your most commented posts are usually the most popular posts on your blog.

However if a lot of comments are slowing down your website, then it can hurt your SEO rankings. That’s when pagination for WordPress comments comes handy.

In this article, we will show you how to paginate comments in WordPress to speed up your post load time. The best part is that it comes as a default feature in WordPress, and it is very easy.

Paginate comments in WordPress

Why You Should Paginate Comments in WordPress

Comment pagination helps you improve your website speed which is an important factor in your website SEO rankings.

Many of our users have reported that sometimes posts with a lot of comments can cause their readers to see white screen of death because it exhausts their server’s memory.

Even when it doesn’t cause ‘white screen of death’, posts with a lot of comments tend to be really really slow.

Comment pagination reduces server load for your most commented posts by splitting comments into multiple pages.

Another reason to paginate your WordPress comments is to maintain the keyword density of your articles. Comments add a lot of content to your post’s page, and they may not always include your target keywords in a sufficient amount.

When keyword ratio to content decreases, search engines fail to index your post for the right keywords.

Comment pagination can also have a negative SEO impact if it is not used correctly. Basically, WordPress generates URLs for each new page of comments. Search engines may consider this as ‘duplicate content’.

This issue can be easily fixed by using the Yoast SEO plugin, which points search engines to the canonical URL of your article.

Now that we have discussed the pros and cons of comment pagination, let’s take a look at how to easily paginate comments in WordPress.

Paginating WordPress Comments in Two Steps

The first thing you need to do is login to your WordPress admin area and go to Settings » Discussions page.

Next, look for the ‘Break comments into pages’ option. From here you need to enter the number of comments you want on each page, and how you want to display them.

Break Comments into Pages in WordPress Posts

Don’t forget to click on the ‘Save Changes’ button to store your settings.

You can now visit any popular post on your website that has a lot of comments. You will notice the pagination links below the comments.

Depending on your theme’s styling, you will either see numeric pagination or ‘Previous / Next’ comment links.

Here is how comment pagination looks on our article 24 “Must Have” WordPress Plugins.

WordPress Comments Pagination in WPBeginner

Note: Just like comments, you can also paginate WordPress posts by splitting a long post into multiple pages.

We hope that this tutorial helped you paginate comments in WordPress. You might also want to see our guide on how to combat comment spam in WordPress.

If you liked this article, then please subscribe to our YouTube Channel for WordPress video tutorials. You can also find us on Twitter and Facebook.

The post How to Paginate Comments in WordPress (Step by Step) appeared first on WPBeginner.