Chatrine Karima
Chatrine Karima

Reputation: 25

How to make a link that changes the source of an iframe and scrolles to an anchor on that page

I use this code, and it works, but it only works one time. How come?

<script type="text/javascript">
function goToAnchor(name){
window.location.hash = name;}
</script>


<li onclick="goToAnchor('topp');"><a href="test.html" target="iframetest">Tst</a></li>

Upvotes: 0

Views: 100

Answers (2)

georgebrock
georgebrock

Reputation: 30043

The first time your call it, it changes window.location.hash and causes the browser to scroll to the ID or anchor you specified. The second time, window.location.hash is already set to topp (or whatever you passed to goToAnchor the first time) and since the hash hasn't changed the browser doesn't change the scroll position.

There are various ways to fix this:

  1. Don't use JavaScript. Just use links like this: <a href='#topp'>Topp</a>
  2. Use the scrollIntoView function to scroll to the element you're targetting:

    document.getElementById('topp').scrollIntoView();
    

Upvotes: 0

Oli B
Oli B

Reputation: 514

Do you need javascript?

<li><a href="test.html#topp" target="iframetest">Tst</a><li>

Upvotes: 1

Related Questions