Opens an external site in a new window
Mental Health Awareness Month
“Community”
RODNEY LAB
  • Home
  • Plus +
  • Newsletter
  • Links
  • Profile
RODNEY LAB
  • Home
  • Plus +
  • Newsletter
  • Links

Use Vim Keyboard Shortcuts on your Blog # Use Vim Keyboard Shortcuts on your Blog #

blurry low resolution placeholder image Use Vim Keyboard Shortcuts on your Blog
  1. Home Rodney Lab Home
  2. Blog Posts Rodney Lab Blog Posts
  3. SvelteKit SvelteKit Blog Posts
<PREVIOUS POST
NEXT POST >
LATEST POST >>

Use Vim Keyboard Shortcuts on your Blog #

Updated 3 years ago
5 minute read
Gunning Fog Index: 6.7
Content by Rodney
blurry low resolution placeholder image Author Image: Rodney from Rodney Lab
SHARE:

⌨️ Adding Vim Keyboard Navigation to your Blog Posts #

Let’s look at how to use Vim keyboard shortcuts on your blog. Although the Vim text editor first appeared in the late 20th century, it still enjoys appreciable popularity. The Stack Overflow 2021 Developer Survey results show 24% of developers use Vim, and another 5%, Neovim (a younger alternative) . I personally use Vim for dev work, and end up finding myself trying to use Vim keyboard shortcuts everywhere (even where not supported) towards the end of a long day coding! Completely selfishly, why not make life easier for Vim developers to get around your blog posts?

Please enable JavaScript to watch the video 📼

Use Vim Keyboard Shortcuts on your Blog: What we're Building

In this post, we see how you can modify a Svelte blog site to respond to some Vim keyboard shortcuts. We’ll clone the SvelteKit Blog MDsveX Starter  to get things going quicker. Then we will create a new component for responding to keyboard shortcuts and add that to the existing blog post template. If you are not yet familiar with SvelteKit, you can still follow along. If you don’t like Svelte, then the code can also be adapted for use on React or plain HTML/JavaScript sites. Why don’t we press on?

🚘 Start your Engines! #

Let’s start by cloning the starter and spinning up our development server:

    
git clone https://github.com/rodneylab/sveltekit-blog-mdx.git vim-shortcut-blog
cd vim-shortcut-blog
pnpm install
cp .env.EXAMPLE .env
npm run dev

If this is your first time using the stater, have a poke around the folders and then jump to localhost:5173  to get used to it. Check out the post on getting started with SvelteKit to see how to switch ports.

🗳 Poll #

Do you use vi, Vim or Neovim
Voting reveals latest results.

🧱 Use Vim Keyboard Shortcuts on your Blog: Building our Site #

Let’s create the VimKeyboardShortcuts component. Although we will create it as a Svelte component, it will not render anything, just react to key presses. Paste this code into a new file src/lib/components/VimKeyboardShortcuts.svelte:

src/lib/components/VimKeyboardShortcuts.svelte
svelte
    
1 <script>
2 let gAlreadyPressed = false;
3
4 function viewportHeight() {
5 return window.innerHeight;
6 }
7
8 /**
9 * @param event {KeyboardEvent} - click
10 */
11 function handleKeyDown(event) {
12 }
13 </script>
14
15 <svelte:window on:keydown={handleKeyDown} />

This is just a shell, we will flesh it out soon. This shell lets us see a few Svelte features. In line 15 we add an event listener (using Svelte syntactic sugar). It adds the event listener for key presses to the browser’s window object. Here we only need to listen for the keydown event but you can listen for other events , just adding additional on:<event> attributes. Note the event listener calls our handleKeyDown function, which we are yet to fill out. <svelte:window> does not render anything in the browser, it just provides a handle which we can use to attach the event listener to.

We will use gAlreadyPressed to listen for a repeat press of the g key (as in the gg shortcut, which takes us to the top of the page). Finally, we have a utility function to calculate the viewport height. This is the inner window browser window height. We will use this to scroll up or down by half a screen.

That’s the shell. Before we flesh it out, let’s add the component to our blog post template.

Integrating VimKeyboardShortcuts #

Update the BlogPost component (src/lib/components/BlogPost.svelte) as below. This is the template used to render blog posts.

    
1 <script>
2 import readingTime from 'reading-time';
3 import BannerImage from '$lib/components/BannerImage.svelte';
4 import SEO from '$lib/components/SEO/index.svelte';
5 import VimKeyboardShortcuts from '$lib/components/VimKeyboardShortcuts.svelte';
6
7 export let imageData;
src/lib/components/BlogPost.svelte
svelte
    
1 <SEO
2 article
3 {breadcrumbs}
4 {slug}
5 {title}
6 {datePublished}
7 {lastUpdated}
8 {metadescription}
9 {timeToRead}
10 featuredImage={featuredImageObject}
11 ogImage={ogImageObject}
12 ogSquareImage={ogSquareImageObject}
13 twitterImage={twitterImageObject}
14 />
15 <VimKeyboardShortcuts />
16 <BannerImage {imageData} />
17 <h1>{title}</h1>

Now we have the component in the DOM for our blog posts, we just need to fill it out and test it.

handleKeyDown #

Let’s jump back to src/lib/components/VimKeyboardShortcuts.svelte and add the code for handling key presses:

src/lib/components/VimKeyboardShortcuts.svelte
svelte
    
23 function handleKeyDown(event) {
24 const { ctrlKey, key } = event;
25 switch (key) {
26 case 'd':
27 if (ctrlKey) {
28 window.scrollBy(0, 0.5 * viewportHeight());
29 }
30 break;
31 case 'G':
32 const lastElement = document.getElementsByTagName('main')[0].lastElementChild;
33 lastElement.scrollIntoView(true);
34 break;
35 case 'g':
36 if (gAlreadyPressed) {
37 const firstElement = document.getElementsByTagName('main')[0].firstElementChild;
38 firstElement.scrollIntoView(true);
39 } else {
40 gAlreadyPressed = true;
41 setTimeout(() => {
42 gAlreadyPressed = false;
43 }, 1000);
44 }
45 break;
46 case 'u':
47 if (ctrlKey) {
48 window.scrollBy(0, -0.5 * viewportHeight());
49 }
50 default:
51 }
52 }
53 </script>

We use a switch statement here in the logic for responding to different key presses. This is a little cleaner than a series of if statements. switch is one of those features you might look at when initially learning JavaScript, but then, somehow, not often use in your domain. So here’s the MDN docs on switch in case you need to brush up . Switch cases use strict comparison (===).

Handling a Key Double Press #

Let’s look at the g block in detail (lines 35 – 45). This block handles the shortcut which scrolls to the top of the post. It is triggered when the user presses g twice. The first thing we do in the block is check if g has already been pressed. If it has, we look for the main HTML element (we rely on the post using semantic HTML here). Next, we find the first child element of the main element. Then finally in line 38, we scroll that element into view.

We get smooth scrolling behaviour because the starter’s global CSS includes scroll-behavior: smooth; on the html element. You can see this in src/lib/styles/styles.scss.

If the user is pressing the g key for the first time. We need to register it, but not do anything else. We can do that by setting gAlreadyPressed to true. However, we really should expect the user to press g, for the second time, quite soon after the first time (that’s if they intended to execute the shortcut we are listening for). This means we need to reset gAlreadyPressed back to false after, let’s say one second. This is what we do in lines 41 – 43, using setTimeout . Our setTimeout call waits for 1000 milliseconds before it does anything. It then executes the anonymous function () => { gAlreadyPressed = false; } which we passed in as the first argument.

That’s all the logic in now! The other switch blocks are simpler variations of the one we just went through. Next we can test it all out.

💯 Use Vim Keyboard Shortcuts on your Blog: Testing Everything #

Here’s a list of the keyboard shortcuts we programmed:

Ctrl + d
scroll down half a window height,
G
scroll to bottom of the post,
g g
scroll to top of the post,
Ctrl + u
scroll up half a window height.

Try them out to check all is well.

Please enable JavaScript to watch the video 📼

Use Vim Keyboard Shortcuts on your Blog: Test

🙌🏽 Use Vim Keyboard Shortcuts on your Blog: What we Learned #

In this post, we learned:

  • how to listen for keyboard events in Svelte;
  • listening for key combination presses in JavaScript; and
  • how to listen for a double key press in JavaScript.

I do hope there is at least one thing in this article which you can use in your work or a side project. For extensions, you could add shortcuts to jump to the next post if the user presses l or, previous post for h. On top, you can jump up a level (based on the page breadcrumbs) if the user types :q. The sky is the limit, you can really go to town on this! For more Vim keyboard shortcuts Richard Torruellas has a fantastic cheat sheet . For more on Keyboard events, Tapas Adhikary wrote a tremendous freeCodeCamp post .

As always, get in touch with feedback if I have missed a trick somewhere! Also, I’m especially keen to hear feedback from users with accessibility needs; on whether adding these shortcuts has a negative impact on your experience.

You can see the full code for this Vim keyboard shortcut blog site on the Rodney Lab Git Hub repo .

🙌🏽 Use Vim Keyboard Shortcuts on your Blog: Feedback #

Have you found the post useful? Do you have your own methods for solving this problem? Let me know your solution. Would you like to see posts on another topic instead? Get in touch with ideas for new posts. Also, if you like my writing style, get in touch if I can write some posts for your company site on a consultancy basis. Read on to find ways to get in touch, further below. If you want to support posts similar to this one and can spare a few dollars, euros or pounds, please consider supporting me through Buy me a Coffee.

Finally, feel free to share the post on your social media accounts for all your followers who will find it useful. As well as leaving a comment below, you can get in touch via @askRodney on Twitter and also askRodney on Telegram . Also, see further ways to get in touch with Rodney Lab. I post regularly on SvelteKit as well as other topics. Also, subscribe to the newsletter to keep up-to-date with our latest projects.

Thanks for reading this post. I hope you found it valuable. Please get in touch with your feedback and suggestions for posts you would like to see. Read more about me …

blurry low resolution placeholder image Rodney from Rodney Lab
TAGS:
SVELTEKIT

Likes:

Likes

  • James profile avatar
  • Vinny profile avatar
  • Ryan Arpe profile avatar
  • Mirco Veltri profile avatar
Likes provided by Mastodon & X via Webmentions.

Related Posts

blurry low resolution placeholder image Get Started with SvelteKit Headless WordPress

Get Started with SvelteKit Headless WordPress

plus
sveltekit
<PREVIOUS POST
NEXT POST >
LATEST POST >>

Leave a comment …

Your information will be handled in line with our Privacy Policy .

Ask for more

1 Nov 2022 — Astro Server-Side Rendering: Edge Search Site
3 Oct 2022 — Svelte eCommerce Site: SvelteKit Snipcart Storefront
1 Sept 2022 — Get Started with SvelteKit Headless WordPress

Copyright © 2020 – 2025 Rodney Johnson. All Rights Reserved. Please read important copyright and intellectual property information.

  • Home
  • Profile
  • Plus +
  • Newsletter
  • Contact
  • Links
  • Terms of Use
  • Privacy Policy
We use cookies  to enhance visitors’ experience. Please click the “Options” button to make your choice.  Learn more here.