0

I want to change the url according to the menu pages, so to easily share a link to someone else, since each page has its own url name.

So, I have a function that loads the file content. But how to implement it with the url change also into the function?

<script>
    function getfile(data) {
        var file= data+'.html';
        $('#content').load(file);
    }
</script>

Here is the navigation using onclick function.

<ul>
    <li><a href="#" onclick="getfile('profile')">Profile</a> </li>
    <li><a href="#" onclick="getfile('about')">About</a> </li>
    <li><a href="#" onclick="getfile('contact')">Contact</a> </li>    
</ul>


<div id="content"></div>

1 Answer 1

1

You could use the History API. The pushState method will allow you to change the current page's URL, without reloading the content.

Example:

<script>
    function getfile(data) {
        var file= data+'.html';
        $('#content').load(file);
        history.pushState(null, null, file);
    }
</script>

You may also be interested in the popstate event, to detect when the browser travels back to the previous pages.

Update:

In order to load files for a sub directory, you will need to know the path to the root directory for the site. Something like the following will work if the site is at the root directory.

<script>
    var rootPath = '/';
    function getfile(data) {
        var file= rootPath+data+'.html';
        $('#content').load(file);
        history.pushState(null, null, file);
    }
</script>
Sign up to request clarification or add additional context in comments.

5 Comments

Thank it's working if files in same directory,but problem if i call the file in another directory like : var file = 'files/'+data+'.html';
@qmnew In that case, you will need to know the root folder to prepend it to the file variable. If the page is at the root directory, you could use /. See updated answer.
yup, I have created the variable like this : var file = 'files/'+data+'.html'; but,the problem url become continuous repeated if click multiple time.
localhost/main/files/files/files/files/about.html
Oh,ok,that is working fine,I have just included '/' at front as you said,thank Alexander O'Mara

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.