简体   繁体   中英

Why I can't get this jquery code to work?

I am trying to make the page scroll to post which has specific id eg post-21 post-22 etc

But It won't work. what could be wrong with my syntax here please?

// this is number of posts visible. returns e.g. 2
var posts_visible = <?php echo $news['num_per_page']; ?>;
// this is number of more posts loaded. returns e.g. 2
var posts_more = <?php echo $news['num_per_more']; ?>;
// here i calculate the value to know which position should we be at after scroll
var newposition = posts_visible + (posts_more * $.cookie('n_more'));
// here i am trying to set #post-(thepostnumber)
var thispost = '$("#post-' + newposition + '")';
$('html,body').animate({
    scrollTop: thispost.position().top + 'px',
    scrollLeft: thispost.position().left + 'px'
},1000);

Please note that alert(thispost) returns accurately the post with the proper ID i should be at. Just can't get it to work in the animate/scroll. Please help me

Try:

var thispost = $("#post-" + newposition);

You don't want to create a string " $("#post-42") ", you want to create the string " #post-42 " and pass it to the $ function.

You need just the selector as a string, not the entire $() function call, like this:

var thispost = $("#post-" + newposition).position();
$('html,body').animate({
    scrollTop: thispost.top + 'px',
    scrollLeft: thispost.left + 'px'
},1000);

Also it can be optimized like above...no need to call .position() twice to get the same result.

var thispost = $("#post-"+ newposition);
$('html,body').animate({
    scrollTop: thispost.position().top + 'px',
    scrollLeft: thispost.position().left + 'px'
},1000);

Not sure if this is helpful, but worth sharing. I use this plugin when I want to scroll something http://demos.flesler.com/jquery/scrollTo/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM