Using EJS to display relative off-canvas

23 views Asked by At

I have three off-canvases with multiple functionalities in a single page. Specifically, in all routes. I was trying to hide them all until the relative components being toggling.

Even though the JavaScript code can achieve that but it is odd that if the user presses F12, the code will still be there. It is not much secure as some of the functionalities are better not be public. For instance, it is not a good idea to display the login off-canvas while the user logged in.

I was trying to fetch the href to backend route then return the value to EJS to determine which off-canvas should be displayed, and eliminate all irrelative off-canvases. Please view the following code.

// Offcanvas part is a partial which intend to apply on all routes .

<div class="offcanvas book background-white" data-tab="/book/:id">
    // books offcanvas
</div> 

<% if (href === /user/login) { %>
<div class="offcanvas login background-white narrow" data-tab="/user/login">
    // login offcanvas
</div>
<% } %>

<div class="offcanvas signup background-white narrow" data-tab="/user/signup">
    // signup offcanvas
// offcanvas JavaScrpt code
const offcanvasItems = document.querySelectorAll('.offcanvas-item');

document.addEventListener('DOMContentLoaded', () => {
    offcanvasItems.forEach(toggler => {
        toggler.addEventListener('click', e => {
            e.preventDefault();
            e.stopPropagation();

            const href = toggler.getAttribute('href');
            toggleOffcanvas(href);
        });
    });
});

    // toggle offcanvas
const offcanvas = document.querySelectorAll('.offcanvas');
    
const toggleOffcanvas = (href) => {
    offcanvas.forEach(async item => {
        const dataTab = item.getAttribute('data-tab');
        
        if (dataTab === href) {
            item.classList.toggle('active');
            
            const res = await fetch(window.location.pathname, {
                method: 'POST',
                body: JSON.stringify({ href }),
                headers: { 'Content-Type': 'application/json'}
            });

            await res.json();

        } else {
            item.classList.remove('active');
        };
    });
};
// login offcanvas toggler
<li class="navbar-item">
     <a class="navbar-link offcanvas-item login" href="/user/login">Login</a>
</li>
app.post('*', (req, res, next) => {
    const href = req.body.href;
    res.locals.href = href;
    next();
});
0

There are 0 answers