javascript - Show / Hide elements - move to top of screen? -
i'm using jquery toggle hiding , showing of divs.
this works fine until 1 of divs expands off screen. i'd scrollup div @ top of screen.
this code i'm using :
$('.slider').hide(800); $('a#show').on('click', function (e) { e.preventdefault(); var elem = $(this).next('.slider') $('.slider').not(elem).hide(); elem.toggle(); });
i've created fiddle showing issue. clicking on section 2 expands past bottom of screen.
ideally want scrollup section2 @ top of screen.
i've added after elem.toggle();
, sort of work.
$('html, body').animate({ scrolltop: elem.offset().top }, 1000);
updated fiddle
the issue have scrollup scrolls partway div , not top.
can advise how scroll top of current div , not partway it.
** update ** updated fiddle showing partial scrolling issue.
click on section 1, open, scroll downwards section 2 , click on it.
it open part way div.
how sort ?
** followup **
this seems issue if have timings in code :
$('.slider').not(elem).hide(600); elem.toggle(600);
the above has issue. yet next works:
$('.slider').not(elem).hide(); elem.toggle();
but lacks nice transition. way both working ?
thanks
from described updated code seems work, page scroll top of div have chosen. if wanted bottom of div @ bottom of page, scrolls way, can find height of div , window, , work out scrolltop value using code:
scrolltop: elem.offset().top + $(elem).height() - $(window).height()
fiddle
edit: happening because work out offset of sec div, close first div changes position of sec one. can workaround waiting first div close before working out next offset scroll to.
settimeout(function(){$('html, body').animate({ scrolltop: elem.offset().top }, 1000);}, 600);
new fiddle
javascript jquery scroll
No comments:
Post a Comment