Search code examples
javascriptjquerynode.jsurlurl-routing

Javascript: Going to root url (to avoid relative url)


I'm having an issue with urls.

I have a navbar.ejs file that I include in every page of my website via

<% include ./navbar %>

In the file, I have something like this:

<li><a id="loginButton" href="../login">Login</a></li>
<li><a id="signupButton" href="../users/new">Sign up</a></li>

The issue I'm having is that depending on where I am on the website, the login button might or might not work. This is because of

"../login"

So at times when you click the login button, you're directed to https://baseurl/login

At other times, it goes to https://baseurl/campgrounds/login This URL is wrong and doesn't exist.

I know the source of the problem obviously. But how do I get replace "../login" with an absolute URL path... As in, how do I go back to the root?

Something like $("#loginButton).attr("href", document.location.hostname + "/login") doesn't work because it just directs to baseurl/baseurl/login which is also invalid


Solution

  • If the URL of the login page will always be https://yelpcamp-asool.c9users.io/login then the below code will work fine.

    <a id="loginButton" href="/login">