Search code examples
javascripthtmlcssanchor

Why can't an HTML anchor change the URL?


I'm making a sliding effect which is similar to carousel. I set up four boxes, the contents of each box is different, and I use a nav to navigate.

I found every time I refresh, the page will return to the first box. But I hope the page returns to the box before refresh. Moreover, when I click on the 'a' tags, "#box*" will not be added to the URL. How can this be resolved?

<ul id="menu" class="nav nav-list span2">
    <li class="nav-header">nav</li>
    <li class="active">
        <a href="#box1" class="link">box1</a>
    </li>

    <li>
        <a href="#box2" class="link">box2</a>
    </li>

    <li>
        <a href="#box3" class="link">box3</a>
    </li>

    <li>
        <a href="#box4" class="link">box4</a>
    </li>
</ul>


<li id="box1" class="box">

    <div>XXXXX</div>
</li>

<li id="box2" class="box">

    <div>XXXXX</div>
</li>

JavaScript code

$('a.link').click(function(){
    $(this).parents("ul").children("li").removeClass("active");
    $(this).parents("li").addClass("active");
    $('#wrapper').scrollTo($(this).attr('href'), 800);
    return false;
});

Solution

  • You have to add id="box1", id="box2", ... to the elements you want the browser to jump to.

    For example:

    <ul id="menu" class="nav nav-list span2">
        <li class="nav-header">nav</li>
        <li class="active">
            <a href="#box1" class="link">box1</a>
        </li>
    
        <a href="#box2" class="link">box2</a>
    
        <li>
            <a href="#box3" class="link">box3</a>
        </li>
    
        <li>
            <a href="#box4" class="link">box4</a>
        </li>
    </ul>
    
    <div id="box1">
        <h2>yo box1</h2>
    
        Put a lot of content here
    </div>
    
    <div id="box2">
        <h2>yo box2</h2>
    
        Put a lot of content here
    </div>
    

    That will add the hash to your URL with the id of the box, so when you refresh it will also work.