javascript - Keeping the page vertically fixed on an element, when lots of content is revealed above (so causing scroll) -


i have long page lots of data tables of hidden content.

they hidden quite repetitive not users want have scroll past them time.

frequently down page there option click open of hidden data tables.

the problem is, if go half way down page , click open tables, of content being revealed above current view causes page scroll down, meaning user becomes disorientated on page.

i've mocked problem here. if scroll down 1 of "show more" links nearer bottom of page you'll see mean. http://jsfiddle.net/lnubwdzl/

i want clicked link remain static under cursor user knows are.

this kind of solution:

$("a").on('click', function() {     $('html, body').animate({         scrolltop: $(this).offset().top     }, 2000); }); 

... other questions on so, doesn't seem cut it. if ends in right place page still moves lot before coming rest.

if understand correctly , mentioned in comments, think can set same duration value both slidedown(); , animate() functions, , have them both inside same click handler.

your code may become:

$('a').on('click', function(e){     e.preventdefault();     if($('.hide').length>0){$('html, body').animate({scrolltop:$(this).offset().top},400);}     $('.hide').hide().removeclass('hide').slidedown(400); }); 

hope helps.

update #1: added check on top of animate() not animate when there no $('.hide') element present anymore.

update #2: take @ resulting fiddle of experiment. let me know if looking for.

the way works is:

  • upon click of anchor, offset().top of clicked element first stored in variable named prevoffset.
  • current $(window).scrolltop() value stored in variable named scrolltop.
  • then .hide elements temporarily made visible via $('.hide').show();.
  • another offset().top of same clicked element stored in variable named curroffset.
  • all .hide elements made invisible again via $('.hide').hide();.
  • scrolltop animated value calculated as: scrolltop+(curroffset-prevoffset).
  • all $('.hide') elements animated via slidedown().

javascript:

var duration=400,hideelements=null,scrolltop=0,prevoffset=0,curroffset=0; $('a').on('click',function(e){     e.preventdefault();     hideelements=$('.hide');     if(hideelements.length>0){         scrolltop=$(window).scrolltop();         prevoffset=$(this).offset().top;         hideelements.show();         curroffset=$(this).offset().top;         hideelements.hide();         $('html, body').animate({scrolltop:scrolltop+(curroffset-prevoffset)},duration);         hideelements.removeclass('hide').slidedown(duration);     } }); 

hope looking for.


Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -