Using Javascript to Make Multiple Views for a SPA

Tommy Werner
2 min readDec 21, 2020

I was recently tasked with creating a Single Page Application (SPA) for Flatiron School. The requirements were simple enough, use a Rails API backend and a Javascript/HTML/CSS frontend to make a CRUD application that has several fetch requests from the frontend. I decided to stick with my usual plan: make something that I would actually use.

I began work on my movie watchlist application, WatchNext, and quickly realized that I wouldn’t be able to keep all the information on one view as I had originally intended. Instead, I would need to split up the Watchlist, Search, and Watched views using HTML and Javascript.

The solution I arrived at was to create a div for each view in the index file for my application.

In that snippet, you can see that the views for Search and Watched are both hidden by default. This is because I wanted my Watchlist view to be the default upon page load. I further reinforced this by including the following Javascript at the end of my index file to trigger the initial page function.

The real magic happens with the navigation bar buttons at the top of the page. I created links for each of the three views and attached the following listeners to each.

As you can see, I simply adjust the div class for each to be hidden or not in order to display the desired view. Each of the views still exist within the document, but are hidden from view when not required. This is a simple way to allow for multiple views while keeping everything within a single page.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Tommy Werner
Tommy Werner

Written by Tommy Werner

Flatiron School Software Engineering student, Chicagoan, and boardgame fan.

No responses yet

Write a response