user3685285
user3685285

Reputation: 6596

How do you scroll to a specific div in an iframe?

I have a div with an iframe in it like so:

<div>
    <iframe ng-src="{{somesourceurl}}"></iframe>
</div>

The the source that gets loaded by the iframe has html with uniquely identified div tags like this:

<div id="n_1">
    <div id="n_2" />
    <div id="n_3" />
    <div id="n_4">
        <div id="n_5" />
    </div>
</div>

I also have a bunch of buttons that corresponds to each of these uniquely tagged divs like so:

<button onclick="goToN1()">Go To n1</button>
<button onclick="goToN2()">Go To n2</button>
<button onclick="goToN3()">Go To n3</button>
<button onclick="goToN4()">Go To n4</button>
<button onclick="goToN5()">Go To n5</button>

What do I put in my onclick functions for each of these buttons such that they will scroll to the appropriate place in the iframe?

Upvotes: 1

Views: 1247

Answers (1)

Arg0n
Arg0n

Reputation: 8423

I think you can change the src of the iframe to make the browser scroll to the element with id:

HTML 1

<div>
    <iframe id="my-iframe" ng-src="{{somesourceurl}}"></iframe>
</div>

HTML 2

<button onclick="goToId('n_1')">Go To n1</button>
<button onclick="goToId('n_2')">Go To n2</button>
<button onclick="goToId('n_3')">Go To n3</button>
<button onclick="goToId('n_4')">Go To n4</button>
<button onclick="goToId('n_5')">Go To n5</button>

JavaScript

function goToId(id) {
    var iframe = document.getElementById("my-iframe");
    var src = iframe.src;
    if(src.indexOf('#') >= 0) src = src.substr(0, src.indexOf("#"));
    iframe.src = src + "#" + id;
}

Upvotes: 2

Related Questions