Reputation: 763
I have a page with sorting(ransack gem) and pagination, at the top of the page there is general information, at the bottom table with 10 items per page. If the user clicks on pagination or sorting buttons I would like to automatically scroll to the table skipping the top area.
Using URLSearchParams
i could track clicks on pagination buttons, but when the user clicks on one of the sorting buttons ransack added something like %5Bs%5D=description+asc
and I can't track it using URLSearchParams
.
const url = `http://localhost:3000/articles`;
const urlWithSorting = `http://localhost:3000/articles?q%5Bs%5D=started_at+desc`;
const urlWithPageAndSorting = `http://localhost:3000/articles?page=1&q%5Bs%5D=started_at+desc`;
const searchParams = new URLSearchParams(urlWithPageAndSorting);
// url
const hasPageParams = searchParams.has('page'); // false
const hasSortingParams = searchParams.has('s'); // false
// urlWithSorting
const hasPageParams = searchParams.has('page'); // false
const hasSortingParams = searchParams.has('s'); // false
// urlWithPageAndSorting
const hasPageParams = searchParams.has('page'); // true
const hasSortingParams = searchParams.has('s'); // false
if (hasPageParams || hasSortingParams) {
scroll(0, $(".js-article-table").position().top);
}
Any ideas on how to do this? Thanks!
Upvotes: 0
Views: 157
Reputation: 16435
These URLs are just the encoded version of a standard bracketized query:
http://localhost:3000/articles?q%5Bs%5D=started_at+desc
http://localhost:3000/articles?q[s]=started_at+desc
If you try to print out the URLSearchParams instance, you will get:
console.log([...searchParams].toString())
// q[s],started_at desc
so you can use
searchParams.has('q[s]')
Also, be aware that you cannot pass a full URL to the constructor, you have to build a URL before, and use only the search part:
searchParams = new URLSearchParams(new URL(urlWithPageAndSorting).search)
Upvotes: 1