JavaScript extra

Automatically reload page if js file changes #

  1. Install nodejs.
  2. Install live-server using nodejs: npm install -g live-server.
  3. cd to the project folder.
  4. run live-server (accept all networks notification)
  5. Browse: http://127.0.0.1:8080
  6. Enjoy!

It may not reload the browser (it only detects the changes)!

Add MathJax to website #

👉 Check the codes.

If you use table of content for posts in which links starting with # link to headings. After jumping, headings are usually hidden by the fixed navigation. Adding below script before </body> tag can solve the problem (change value 100 to change where the page jump).[ref]

👉 Check the codes.

👉 Check the codes.[ref]

Back to top button #

Click and go back to the top of the page using javascript with smooth effect.

👉 Check the codes.

Hide / Show box #

Auto hide / show the next div of the currently clicked div.

👉 Check the codes.

Advantage: We don't need the id of content div, this method requires that div.hs__content comes right after div.hs__title, otherwise it won't work!

Click to enlarge photo #

If some photos on your page are too small and you wanna add a function in that users can click on the photo to enlarge it. This technique requires Bootstrap 4.

👉 Check the codes.

Prevent default event #

Stop arrow key acts as usual,

window.addEventListener("keydown", function(e) {
// space and arrow keys
if([32, 37, 38, 39, 40].indexOf(e.keyCode) > -1) {
e.preventDefault();
}
}, false);

If div_1 inside div_2, prevent actions in div_2 when performs on div_1 (check this example), use e.stopPropagation().

Search + result + navigation #

  • Auto close the result if losing focus.
  • Cycling the result items with arrow up/down keys.
  • Auto focus to the a tag of the title.

👉 Check the codes.

Scrolling headings in TOC #

Follow the position of viewport, auto highlight heading in toc w.r.t the current heading on page

👉 Check the codes.

Fetch starred repository (JSON to ol) #

Automatically fetch a list of Github starred repositories using Github API and display it under <ol> html tag.[ref]

👉 Check the codes.