Read More Buttons and Blog Post Tags
26/10/2022

The most complicated part of making this website was undoubtably using JavaScript for the functionality of the read-more/read-less buttons on these posts and the tags to filter posts by. Although I did find lots of examples of code online which I could have copied, pasted, and slightly altered to get this functionality, I wanted to learn and write the JS myself. What I came up with might not be the most efficient way of getting these buttons to work, but it does work!
In explaining this I am going to use a simplified version of the code just to avoid taking up loads of space, but if you want to read the full version you can find the source code to this site on my GitHub, which is linked in the navigation bar.

(There is an error in the code above: on the second more/less button the line should read "onclick=btnSelection('more1')", not 'more5'.)

Blog Post Tags
Above you can see simplified versions of the html and css for a blog page. Ultimately how you style the buttons and content doesn't matter, so the only focus of this is the classes I have assigned to each html tag, and the classes .show and .hide in the css. For the blog post tags, on clicking on the tag the user initiates the function tagSelection(c) where c is the tag which this clicked. The purpose of this function is very simple. It just needs to add the class .show to all blog posts with the class "c", and add the class .hide to all blog posts without the class "c". For example when you click 'Tag 1', you initiate tagSelection('tag1'), which hides all blog posts without "tag1" as a class, and shows the ones with "tag1" as a class.

The important objects to take away from this are:
- document.querySelectorAll(".all") : which gets all the classes of the element with the class "all";
- .split() : which splits our NodeList into individual strings;
- .indexOf() : which checks if the string "c" == one of our node strings, if it does it returns the position of c in that node, else it returns -1.
Read More/Read Less
The read-more/-less buttons work on much the same principle as the blog post tags.
There is only one important take away from this:
- .innerText : allows us to check and change the inner text of an element.