Skip to content

Instantly share code, notes, and snippets.

@tlxue
Created August 9, 2011 04:29
Show Gist options
  • Save tlxue/1133416 to your computer and use it in GitHub Desktop.
Save tlxue/1133416 to your computer and use it in GitHub Desktop.
Fix the postion of vote buttons when scrolling
// run this in a question page
// just a demo, compatibility hasn't been tested
(function(){
// utility
function s(syntax){
// a simple selector, support ID, Class and tag.
if(syntax&&typeof(syntax)==="string"){
if(/^#/.test(syntax)){
return document.getElementById(syntax.slice(1));
}else if(/^\./.test(syntax)){
return document.getElementsByClassName(syntax.slice(1));
}else{
if(document.getElementsByTagName(syntax).length<1){
if(document.getElementById(syntax)===null){
return document.getElementsByClassName(syntax);
}else{
return document.getElementById(syntax);
}
}else{
return document.getElementsByTagName(syntax);
}
}
}else{
return undefined;
}
}
function findTop(obj) {
// find the top offset of an element
var curtop = obj.offsetTop;
while (obj.offsetParent !== null) {
curtop += obj.offsetParent.offsetTop;
obj = obj.offsetParent;
}
return curtop;
}
// detect vote postion and change it
function detect(element){
// detect and alter the position of vote buttons
var screenToTop = document.body.scrollTop || document.documentElement.scrollTop, // distance from window top to page top
eTop = findTop(element), // element top to window
vote = element.childNodes[1], //vote element
voteHeight = 44; //button height
abLeft = element.offsetLeft-30+"px"; // button left to window left
if(screenToTop - eTop>=-4 && screenToTop-eTop-element.offsetHeight < -206){
// just fixed vote
if(!(/\bfixedVote\b/.test(vote.className))){
vote.className += " fixedVote";
}
vote.setAttribute('style','position:fixed;top: 4px;left: '+ abLeft);
}else if(screenToTop - eTop>=-4 && screenToTop-eTop-element.offsetHeight < -161){
// when vote button is about to vanish, gradually alter its position
if(!(/\bfixedVote\b/.test(vote.className))){
vote.className += " fixedVote";
}
var t_t = (-206-(screenToTop-eTop-element.offsetHeight))+ "px;";
vote.setAttribute('style','position:fixed;top: '+t_t+ 'left: '+ abLeft);
}else{
// return to original state
if(/\bfixedVote\b/.test(vote.className)){
vote.className = vote.className.slice(0,-10);
vote.setAttribute('style','position:absolute;left: -30px');
}
}
}
function onPageScroll(e){
// page scroll event
var ans = s('xyr');
for(var i=0;i<ans.length;i++){
if(s('xyr')[i].offsetHeight > 300){
detect(s('xyr')[i]);
}
}
}
window.addEventListener('scroll', onPageScroll, false);
//console.log(s('xnq')); //vote
//console.log(s('xyr')); //doc
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment