Georg
Georg

Reputation: 498

How can I apply 'offset' to an element inside an iframe?

I want to navigate to a div inside an iframe using jQuery.animate from a link outside the iframe. This is the Code I use:

function scrollToAnchorIframe(aid){
  var aTag = window.frames['myFrame'].document.getElementById(aid);
  $('html,body').animate({scrollTop: aTag.offset().top - 62},'slow');
}

However, it doesn't work, logging the error "Object [object HTMLElement] has no method 'offset'". Is there a way to get the offset of the id to make it work?

Update (Solved): That's the code I'm using now:

function scrollToAnchorIframe(aid){
  var aTag = window.frames['myFrame'].document.getElementById(aid);
  jQuery('html,body').animate({scrollTop: $(aTag).offset().top + $("#myFrame").offset().top - 62},'slow');
}

Upvotes: 5

Views: 2645

Answers (2)

Luca Bordoni
Luca Bordoni

Reputation: 1

If the iframe is put inside a container box, here's an update in order to navigate up/down to the iframe's bookmark-anchor from the parent-page container (note: "window.frames" has a known compatibility bug with FF browser, so i'll use "contentWindow" instead):

function iframeBookmark(anchor) {
mytag = document.getElementById("iframeID").contentWindow.document.getElementById(anchor);
pos1 = $(mytag).offset().top;
pos2 = $("#iframeID").offset().top;
if (pos2 > pos1) {
    $("#iframeContainerID").animate({scrollTop: pos2 - (pos2 - pos1) },'slow');
    }
else {
    $("#iframeContainerID").animate({scrollTop: pos2 + (pos1 - pos2)  },'slow');
    }
}

So, when we call the function from the parent HTML, the up/down scroll depends to the iframe current position:

 <a onclick="iframeBookmark('iframeBookmarkID')">...</a>

...where 'iframeBookmarkID' is the ID of the bookmark-anchor in the iframe page.

Upvotes: 0

Adil Shaikh
Adil Shaikh

Reputation: 44740

aTag is DOM element , make it jQuery object

$('html,body').animate({scrollTop: $(aTag).offset().top - 62},'slow');

Upvotes: 4

Related Questions