JensLuyten February 2016

Scrolling to an element without ID in a window opened by window.open

At the top of my page, I have a menu with a couple of items, and when I click them, I scroll to a point of in page where the div is placed, using this line of code:

$('html, body').animate({scrollTop:$(divid).position().top - 160 }, 'slow');

where $(divid) contains the classname of the div. (I am using Drupal so the possibility of adding an ID is not there).

This works fluently, but now I have the same menu in another page. When I click a link, I navigate to the page where the div is placed in, but I can't get it to scroll to the div.

After a lot of research I came to this piece of code

$('#block-views-footer-menu-block-2 .views-row-6 a').click(function(e){
    e.preventDefault();
    var newwindow = window.open('/aanbod', '_self');

    $(newwindow.document).ready(function(){
        to_position('.field-paragraphs:nth-of-type(6)');
    });
});

where to_position() contains the first line of code in this post.

However, the to_position() function fires before the new window is loaded. This way, the moment the to_position() function is fired, '.field-paragraphs:nth-of-type(6)' is not known yet, so the function cannot access the position of it.

I really don't see what I am doing wrong, any help is appreciated.

Thanks in advance!

Answers


gurvinder372 February 2016

Pass the information to the pop-up itself and let it do the scrolling for you.

var newwindow = window.open('/aanbod?scrolltoposition=' + ".field-paragraphs:nth-of-type(6)", '_self');

now in this new window, add the code to scroll the position you want to scroll to

$(document).ready( function(){

   var elementSelector = location.search.split( "=" )[1];
   var $element = $( elementSelector );
   $('html, body').animate({scrollTop:$element.position().top - 160 }, 'slow');

} );

ensure that you have included the jquery in the pop-up


hepifish February 2016

If you are using jQuery, you may use the following

    $(document).ready(function(){
    // your code
    });

A page can't be manipulated safely until the document is "ready." jQuery detects this state of readiness for you. Code included inside $( document ).ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute. Code included inside $( window ).load(function() { ... }) will run once the entire page (images or iframes), not just the DOM, is ready.

Post Status

Asked in February 2016
Viewed 3,197 times
Voted 10
Answered 2 times

Search




Leave an answer