URL Query Parameters
I once considered changing up how I structured my blog page. My blog page has gone through two iterations:
- Collapsible button, similar to how I do my webgraphics page. Where clicking the title button would expand the content
- The newest version, clicking the date on the side would display the corresponding content (making use of the
data-*
property in HTML).
I see a lot of people here also use version #2 to do their blogs. Meaning they have all the blog contents in one giant HTML file(?) That's what I assumed anyway since that's how I do it.
Here comes the problem. Every blogs end up having the same URL. So if I link to the blog page, I'd see the default content. There's no way for me to link to a specific blog If I want to reference it from another page.
I considered making a new page for every blogs just for this, like would it be nicer for each blog to have their own page I can link to? But I'd hate to have a thousand page for each blog + I found it too slow and annoying to load a new page every time.
TLDR; I want each blog to have its own link, without splitting the content into separate files. All content still lives in the same HTML page.
The solution: window.location.search
+ URLSearchParam
Technically I could use window.location.search
only and do the same thing, but using it with URLSearchParam
is easier for me + easy to change up things if I want to.
If I want to link to a specific blog now, instead of just linking with href="blogs.html"
like usual, I'd do href="blogs.html?date=023132"
. This specific URL would display the blog written with said date.
How this works (in my own words):
window.location.search
gives you the part of the URL after the page name. So in this case, it's?date=023132
.URLSearchParams
is a built-in JS object that makes it easy to read and manipulate query parameters in URLs. Like a tool to pull out stuff after the?
in a URL. It have multiple methods attached to it, in this case I only use.get()
.
Here's the code
const params = new URLSearchParams(window.location.search)
const date = params.get('date')
if (date) {
// display the content matching with "date" !
}
What happens here:
- Make a params object with the location I grabbed from
window.location.search
. - Extract the
date
value from the URL (just the number part like023132
). - If the
date
exists (meaning it's not just a regular link), I run code to display the blog post that matches that date.
This solve it. You can learn more about URLSearchParams
here on MDN. I don't exactly get what I'm doing either but it works!! So I'm just sharing ideas here.
If you want to see how I use it. Here, I link you to my first blog. See the URL for yourself, still the same blogs.html
page, just displaying the first blog content!!