In this tutorial, you’ll learn how to add JavaScript to your Jekyll website to make it more engaging and dynamic.
Assuming that you already have a Jekyll project set up, if you don’t, you can read the tutorials on how to set up a Jekyll project and install Jekyll on your computer.
Create a JavaScript File
The first step to adding JavaScript to your Jekyll website is to create a JavaScript file. This file will contain the JavaScript code that you want to add to your web pages. You can create this file using any text editor, such as Visual Studio Code or Sublime Text.
To create a JavaScript file, follow these steps:
- Open a text editor
- Create a new file
- Save the file with a
.js
extension in my case itsnav.js
Once you’ve created your JavaScript file, you can add your JavaScript code to it.
Link JavaScript to Jekyll
The next step is to link your JavaScript file to your Jekyll website. This is done by adding a script tag to your web page. The script tag tells the browser to load the JavaScript file and execute the code inside it.
To link your JavaScript file to your Jekyll website, follow these steps:
- Open the HTML file where you want to add the JavaScript code
- Add the following code to the head section of the HTML file:
<script src="/assets/js/nav.js"></script>
Replace /assets/js/nav.js
with the path to your JavaScript file.
Once you’ve added this code to your HTML file, save the file.
Organizing JavaScript Files in Jekyll
As your Jekyll website grows, you may find that you have multiple JavaScript files that you want to include on your web pages. In this case, it’s a good idea to organize your JavaScript files into separate folders.
To organize your JavaScript files in Jekyll, follow these steps:
- Create a new folder in your Jekyll project directory (e.g.
js
) - Move all of your JavaScript files into this folder
- Update the script tag in your HTML file to reflect the new location of your JavaScript file(s)
<script src="/assets/js/nav.js"></script>
Jekyll Where to Put JavaScript
By default, Jekyll will not automatically copy JavaScript files to your output directory (_site
). To ensure that your JavaScript files are included in the output directory, you need to place them in the assets directory of your Jekyll project.
To add JavaScript to your Jekyll website, follow these steps:
- Create a new folder named “assets” in your Jekyll project directory
- Inside the assets directory, create a new directory named “js”
- Move your JavaScript files into the js directory
Once you’ve placed your JavaScript files in the /assets/js/
directory, Jekyll will automatically copy them to the appropriate location in the output directory when you build your website.
In conclusion, adding JavaScript to your Jekyll website can enhance its functionality and interactivity. By following the steps outlined in this tutorial, you can easily add JavaScript to your Jekyll website and organize your JavaScript files for future maintenance.