09/30/2016   Comments Off on Do something if the hashtag includes this word

View all snippets

This is short snippet that checks whether or not the URL has an appended hashtag and then does something. In this example #comment-123 and 123 being a variable is what I’m checking for.

Why I needed this?

On a blog of mind, I hide the comment section behind a short guidelines message. Users can’t see comments until they click a button to view and/or make a comment. Hidden comment section also shortens page space if someone is just skimming over the page.

This worked find if a person landed on the page normally, but what if they landed on the page via a direct comment link like this ? They’d be taken to that part of the comment, but find the comment section hidden. Then they’d have to click to read the comments, but clicking would only display the comments starting from the top. This isn’t helpful.

This script will automatically open the comment section only for people visiting the page with a direct comment link and take them directly to the comment.

Feel free to change the highlighted to whatever name is your hashtag starts with. The script will handle the rest.

if (window.location.hash) {
   if (window.location.hash.indexOf('comment-') == 1) { // your code here }
   else if (window.location.hash.indexOf('comment-') != -1) { // your code here }
   else { }