Recently I felt like my site was lacking something. I write about computers and some IRL things, and going without any images is kinda boring. But I didn't want to ruin the site aesthetic.
Update: I realized that the script I made didn't work with images that were linked via a relative path within the site, so I modified the code and added a function to convert paths so that it would work. Also here is a demo: sample.jpg
Someone nice suggested that if I were to add images to my site it should be best done as a link, instead of inserting a whole image. Of course, I can't do something without using JS so here's my idea:
- Make a small JS script that will scan any URLs to see if they are links to images and redirect them to a page on my site.
- Make a nice little page that all those links will be redirected to.
- Write a script that will grab the image link from a URL parameter.
- Render the image and a backlink on the page!
This should be a piece of cake. Here is the code part:
- jQuery is present because why not.
The HTML structure is just a blank page with a container that I styled to center an image or a piece of text in it:
The actual JS part is super simple:
Hint: I don't know what page I will be linking from, so I used document.referrer to automatically get the last visited URL.
And that is it for the viewing page! All we have to do is add some code to rewrite our image URLs on other pages to pass a parameter to this page. Here is how that would work:
Hint: I'm using the .toLowerCase() method to account for some files that may have their extensions capitalized, for example files that may end with .JPG. And just like earlier, I'm not sure where the image page may be linked to, so I used window.location.origin instead of a relative path.
Whoops, I almost forgot, to get this to work, all you need is to place a simple url to your image on your page like so:
Now I'll be trying to supply my articles with relevant image links, so hopefully they will be a bit more entertaining to read.
I hope this article was of use! If you need any help or have any suggestions, let me know!