Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Auto Save

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <h1>SPA Vanilla JS</h1>
<nav>
    <a route="home">Home</a>
    <a route="about">About</a>
    <a route="services">Services</a>
</nav>

<main>
    <template id="home">
        <div>
            <h2>Home page</h2>
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
            <img src="https://img.freepik.com/vector-gratis/escena-naturaleza-rio-colinas-bosque-montana-ilustracion-estilo-dibujos-animados-planos-paisaje_1150-37326.jpg?size=626&ext=jpg&ga=GA1.2.1950879610.1628726400" width="320"/>
            <p>Nibh cras pulvinar mattis nunc sed blandit libero volutpat sed. Lectus mauris ultrices eros in cursus turpis. Augue ut lectus arcu bibendum at. Id eu nisl nunc mi ipsum faucibus vitae aliquet. Vel elit scelerisque mauris pellentesque pulvinar pellentesque habitant morbi. Platea dictumst vestibulum rhoncus est pellentesque elit. </p>
        </div>
    </template>
    <template id="about">
        <div>
            <h2>About page</h2>
            <ul>
                <li>Example 1</li>
                <li>Example 2</li>
                <li>Example 3</li>
                <li>Example 4</li>
                <li>Example 5</li>
            </ul>
            <img src="https://cdn.pixabay.com/photo/2019/12/11/21/18/landscape-4689328_960_720.jpg" width="320"/>
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat</p>
        </div>
    </template>
    <template id="services">
        <div>
            <h2>Services page</h2>
            <img src="https://www.creativefabrica.com/wp-content/uploads/2020/04/25/illustration-of-natural-landscape-Graphics-3952025-1-1-580x412.jpg" width="320"/>
            <details>
                <summary>First</summary>
                <p>JavaScript engines were originally used only in web browsers, but they are now core components of other software systems, most notably servers and a variety of applications.</p>
            </details>
            <details>
                <summary>Second</summary>
                <p>Alongside HTML and CSS, JavaScript is one of the core technologies of the World Wide Web.[11] Over 97% of websites use it client-side for web page behavior,[12] often incorporating third-party libraries.[13] Most web browsers have a dedicated JavaScript engine to execute the code on the user's device.</p>
            </details>
            <details>
                <summary>Third</summary>
                <p>Although there are similarities between JavaScript and Java, including language name, syntax, and respective standard libraries, the two languages are distinct and differ greatly in design..</p>
            </details>
        </div>
    </template>
</main>

<footer>Made by Darud Lingilien</footer>
              
            
!

CSS

              
                body * {
    outline: 0;
    margin: 0;
}

body {
    padding: 2rem;
    background-color: #260e47;
    color: white;
    display: flex;
    flex-direction: column;
    row-gap: 1rem;
    align-items: center;
}

nav {
    display: grid;
    gap: 1rem;
    grid-template-columns: repeat(1, minmax(0, 1fr));
    justify-content: center;
    padding: .5rem;
    text-align: center;
}

a {
    user-select: none;
    cursor: pointer;
    width: 9.25rem;
    padding: .5rem .75rem;
    display: inline-block;
    background-color: #5e2f9e;
}

p {
    max-width: 30rem;
    text-align: justify;
}

a:hover {
    filter: brightness(120%);
}

div {
    display: flex;
    flex-direction: column;
    row-gap: .75rem;
    align-items: center;
} 

ul {
    list-style-type: disc;
    list-style-position: inside;
}

footer {
    background-color: #59328c;
    padding: .75rem 1rem;
    width: 100%;
    text-align: center;
}

details {
    width: 100%;
    border-bottom: .25rem solid #884ad9;
    padding: 1rem;
}

summary {
    padding: .75rem 0;
}

h1 {
    font-size: 2.75rem;
}

h2 {
    font-size: 1.75rem;
}

@media(min-width: 540px) {
    nav {
        grid-template-columns: repeat(3, minmax(0, 1fr));
    }
    
    details {
        width: 30rem;
    }
}
              
            
!

JS

              
                //Route class
class Route {
    #contentID;
    
    constructor({ template, name }) {
        Object.assign(this, arguments[0]);
        
        if(this.template.content.firstElementChild.tagName != "DIV") {
            throw new Error("The first element of a component must be a 'div' element");    
        };
        
        this.template.content.firstElementChild.id = this.contentID = this.template.id;

        this.template.id = "";
    };
    
    show(element) {
        this.parent.fragment.appendChild(document.importNode(this.template.content, true));
        element.append(this.parent.fragment);
    };
};

//Link constructor
const Link = ({ element, parent }) => ({
    element,
    parent,
    route: element.getAttribute("route"),
    registerListener() {
        this.element.addEventListener("click", () => {
            this.parent.goToRoute(this.route);
        });
    },
});

//App main class
class SPA {
    constructor({ routes, element }) {
        Object.assign(this, arguments[0]);
        
        this.fragment = document.createDocumentFragment();
        
        this.links = Object.assign({}, [...document.querySelectorAll("a[route]")].map((link) => Link({ 
                element: link,
                parent: this,
            })));
        
        Object.values(this.links).forEach((link) => link.registerListener());
        
        Object.values(this.routes).forEach((route) => { route.parent = this; });
    };
    
    start(route = undefined) {
        let goTo = (route || Object.keys(this.routes)[0]);
        
        this.routes[goTo].show(this.element);
        this.currentRoute = this.routes[goTo].name;
    };
    
    goToRoute(route) {
        if(this.currentRoute == route) return;

        if(!this.routes.hasOwnProperty(route)) {
            throw new Error(`The specific route '${route}' doesn't exists, make sure you've defined it`)
        };
        
        this.element.innerHTML = "";
        
        this.routes[route].show(this.element);
        
        this.currentRoute = this.routes[route].name;
    };
};

//Define Routes
const routes = {
    home: new Route({ 
        name: "home", 
        template: document.querySelector("#home"),
    }),
    about: new Route({ 
        name: "about", 
        template: document.querySelector("#about"), 
    }),
    services: new Route({ 
        name: "services", 
        template: document.querySelector("#services"), 
    }),
};

//Start SPA
document.addEventListener("DOMContentLoaded", () => {
    const spa = new SPA({ routes: routes, element: document.querySelector("main") });
    
    spa.start();
});
              
            
!
999px

Console