Michael
Michael

Reputation: 327

JavaScript - Jump to anchor

I'm trying to open a div with a jump to the anchor. The opening part is working but it's not jumping to the named anchor

This is my script:

<script type="text/javascript">
    function spoil(id){
        if (document.getElementById) {
            var divid = document.getElementById(id);
            divid.style.display = (divid.style.display = 'block');
            window.location = '#' + id;
        }
    }
</script>

<a href="http://example.com" onclick="spoil('thanks');" title="hello">
    <img src="images/gfx.png" alt="world" width="300" height="300"/>
</a>

Any ideas what's wrong with it? Cheers.

Upvotes: 15

Views: 50092

Answers (2)

Alex K.
Alex K.

Reputation: 175748

Looks like you're unhiding a spoiler div. If so, you can scroll the element into view as follows:

function spoil(id) {
    var divid = document.getElementById(id);
    divid.style.display = 'block';
    divid.scrollIntoView(true);
    return false;
}
...
<a href="#" onclick="return spoil('thanks');" title="hello"><img src="images/gfx.png" alt="world" width="300" height="300"/></a>

Upvotes: 12

jammon
jammon

Reputation: 3464

Did you try window.location.hash = '#'+id;?

Upvotes: 54

Related Questions