Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 239
Michael Avatar asked Apr 17 '11 16:04

Michael


People also ask

Can we use anchor tag in JavaScript?

Using JavaScript In vanilla JavaScript, you can use the document. createElement() method, which programmatically creates the specified HTML element. The following example creates a new anchor tag with desired attributes and appends it to a div element using the Node. appendChild() method.

How do I scroll an HTML page to an anchor?

The easiest way to to make the browser to scroll the page to a given anchor is to add *{scroll-behavior: smooth;} in your style. css file and in your HTML navigation use #NameOfTheSection .

What is anchor in JavaScript?

JavaScript String anchor() It may cease to work in your browser at any time. The anchor method returns a string embedded in an <a> tag: <a name="anchorname">string</a>


2 Answers

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

like image 167
jammon Avatar answered Sep 29 '22 15:09

jammon


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>
like image 44
Alex K. Avatar answered Oct 02 '22 15:10

Alex K.