Exercise Notes
Add Javascript
As part of the HTML & CSS module, you’ve built a website with a beautiful CSS layout, but no interactivity! Using JavaScript, add some buttons on your page which invoke some JavaScript. For example:
- Show and hide some of your content
- A small calculator for performing simple arithmetic
- Display a message based on the current time – like http://isitpancakeday.com/
- Anything else!
GIFs
The other thing your site is missing is GIFs. Let’s add some:
- Sign up for a Giphy Developer account and then click Create an App. Once you fill in some basic info you should be given an API key, which you can use to make requests to their API.
- Create some new files called
trending.html
,giphy.js
andrequests.js
. Add some HTML to yourtrending.html
file to get some basic content like a title and header. Now add styling in your CSS stylesheet and make sure to include a reference to both your stylesheet and yourgiphy.js
andrequests.js
scripts on your trending page. - Now let’s write some JavaScript in your
giphy.js
file that will populate the page with a list of the top 10 trending gifs. To get an idea of how to start, look at the GIPHY API Docs and Explorer, then check out this demo page that uses the Random endpoint to generate random gifs. Remember, make sure to use your own API key in your project! - The function calling the API should live in
requests.js
. For now, you can define it insiderequests.js
and call it insidegiphy.js
. As long as both scripts are added to the html, it will work. - The demo page uses the old XMLHttpRequest API to make requests to the Giphy site. Try changing this (or your own implementation) to the Fetch API.
- (As a stretch goal) Try combining this with async/await syntax.
Bundlers
We added gifs to our website. However, we had to add separate JavaScript scripts, to keep the code clean. This is not great for performance, as the browser has to make 2 separate calls for each JavaScript file. Let’s fix that:
- Initialise an npm project by using
npm init
command – for our little project, the default values should be enough - Install a bundler library – we recommend esbuild for this exercise:
npm install esbuild
- Create a new rule called
build
inside thescripts
section of thepackage.json
file:"build": "esbuild giphy.js --bundle --outfile=bundle.js"
- For the bundler to know where the request function is coming from, we need to:
- Run the rule you just created:
npm run build
- Have a look into
bundle.js
to see what the bundler did - Back into your
trending.html
, remove the lines that includerequests.js
andgiphy.js
. Includebundle.js
instead. - Open your trending page and check if everything works as before!