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.
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.
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 .
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>
Did you try window.location.hash = '#'+id;
?
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With