header hide on scroll - delay on scroll up - javascript

I want to add a delay to this header when the user scrolls 200px up: https://codepen.io/iabhinavr/pen/BaKxvRx
If see the codepen, right now it only delays on scrolls down.
This is what I have tried:
// menu hide on scroll
(function(){
var doc = document.documentElement;
var w = window;
var curScroll;
var prevScroll = w.scrollY || doc.scrollTop;
var curDirection = 0;
var prevDirection = 0;
var header = document.getElementById('site-header');
var toggled;
var threshold = 350;
var thresholdScrollUp = 200;
var checkScroll = function() {
curScroll = w.scrollY || doc.scrollTop;
curScrollBottom = w.scrollY || doc.scrollTop;
if(curScroll > prevScroll) {
// scrolled down
curDirection = 2;
}
else {
//scrolled up
curDirection = 1;
}
if(curDirection !== prevDirection) {
toggled = toggleHeader();
}
prevScroll = curScroll;
if(toggled) {
prevDirection = curDirection;
}
};
var toggleHeader = function() {
toggled = true;
if(curDirection === 2 && curScroll > threshold) {
header.classList.add('hide');
jQuery('#site-header-sticky-wrapper').addClass('hide');
}
else if (curDirection === 1 && curScrollBottom > thresholdScrollUp) {
jQuery('#site-header-sticky-wrapper').removeClass('hide');
header.classList.remove('hide');
}
else {
toggled = false;
}
return toggled;
};
window.addEventListener('scroll', checkScroll);
})();
I added:
var thresholdScrollUp = 200;
and changed:
else if (curDirection === 1)
to:
else if (curDirection === 1 && curScrollBottom > thresholdScrollUp)
Any help would be appreciated

Your provided code pen code work differently. Checkout this one
(function(){
var doc = document.documentElement;
var w = window;
var curScroll;
var prevScroll = w.scrollY || doc.scrollTop;
var curDirection = 0;
var prevDirection = 0;
var lastY = 0;
var header = document.getElementById('site-header');
var toggled;
var threshold = 200;
var checkScroll = function() {
curScroll = w.scrollY || doc.scrollTop;
if(curScroll > prevScroll) {
// scrolled down
curDirection = 2;
}
else {
//scrolled up
curDirection = 1;
}
if(curDirection !== prevDirection) {
toggled = toggleHeader();
} else {
lastY=curScroll
}
prevScroll = curScroll;
if(toggled) {
prevDirection = curDirection;
}
};
var toggleHeader = function() {
toggled = true;
if(curDirection === 2 && (curScroll-lastY) > threshold) {
lastY=curScroll
header.classList.add('hide');
}
else if (curDirection === 1 && (lastY-curScroll) > threshold) {
lastY=curScroll
header.classList.remove('hide');
}
else {
toggled = false;
}
return toggled;
};
window.addEventListener('scroll', checkScroll);
})();

Related

How when I scroll highest and then remove class

I have a question about when I scroll highest I want to remove the class that have position fixed because the position fixed will hide my div right, so I need remove it and dont hide my div when I scroll highest.
May I know can only edit the javascript code to solved it? ty
Here is my codepen link
https://codepen.io/WeiKang-Ng/pen/bGxGQwx
Here is js code
(function(){
var doc = document.documentElement;
var w = window;
/*
define four variables: curScroll, prevScroll, curDirection, prevDirection
*/
var curScroll;
var prevScroll = w.scrollY || doc.scrollTop;
var curDirection = 0;
var prevDirection = 0;
var header = document.getElementById('site-header');
var toggled;
var threshold = 100;
var checkScroll = function() {
curScroll = w.scrollY || doc.scrollTop;
if(curScroll > prevScroll) {
// scrolled down
curDirection = 2;
}
else {
//scrolled up
curDirection = 1;
}
if(curDirection !== prevDirection) {
toggled = toggleHeader();
}
prevScroll = curScroll;
if(toggled) {
prevDirection = curDirection;
}
};
var toggleHeader = function() {
toggled = true;
if (curDirection === 2 && curScroll > threshold) {
header.classList.add("nav-on-scroll");
header.classList.remove("show-nav-on-scroll");
} else if (curDirection === 1 && curScroll > threshold) {
header.classList.add("show-nav-on-scroll");
} else {
toggled = false;
}
return toggled
};
window.addEventListener('scroll', checkScroll);
})();
you need to add 2 lines to remove class from the header.
1st line removes the class if the user is scrolling up and has not yet reached the threshold.
2nd line removes the class if the user is not scrolling or has scrolled past the threshold.
modify the toggleHeader function as follow
var toggleHeader = function() {
toggled = true;
if (curDirection === 2 && curScroll > threshold) {
header.classList.add("nav-on-scroll");
header.classList.remove("show-nav-on-scroll");
} else if (curDirection === 1 && curScroll > threshold) {
header.classList.add("show-nav-on-scroll");
header.classList.remove("nav-on-scroll");
} else {
toggled = false;
header.classList.remove("nav-on-scroll");
}
return toggled;
};

The color will not change on a div, generated by a script

var BGLinks = (function() {
var that = {};
// can be set like BGLinks.parameter
that.version = 'NIV';
that.clickTooltip = false;
that.apocrypha = false;
that.showTooltips = true;
that.host = 'www.biblegateway.com';
var showTimer = 0;
var hideTimer = 0;
var container;
var addedCSS = false;
var setupRun = false;
var delay = 1000;
var bgHost;
var toolsHost;
var cdHost;
var browser = navigator.appVersion;
var book_string = 'Genesis|Gen?|Gn|Exodus|Exod?|Ex|Leviticus|Le?v|Numbers|Nu?m|Nu|Deuteronomy|Deut?|Dt|Josh?ua|Josh?|Jsh|Judges|Ju?dg|Jg|Ru(?:th)?|Ru?t|(?:1|i|2|ii) ?Samuel|(?:1|i|2|ii) ?S(?:a|m)|(?:1|i|2|ii) ?Sam|(?:1|i|2|ii) ?Kin(?:gs?)?|(?:1|i|2|ii) ?Kgs|(?:1|i|2|ii) ?Chronicles|(?:1|i|2|ii) ?Chr(?:o?n)?|(?:1|i|2|ii) ?Cr|Ezra?|Nehemiah|Neh?|Esther|Esth?|Jo?b|Psalms?|Psa?|Proverbs|Pro?v?|Ecclesiastes|Ec(?:cl?)?|Song (?:O|o)f Solomon|Song (?:O|o)f Songs?|Son(?:gs?)?|SS|Isaiah?|Isa?|Jeremiah|Je?r|Lamentations|La(?:me?)?|Ezekiel|Eze?k?|Daniel|Da?n|Da|Hosea|Hos?|Hs|Jo(?:el?)?|Am(?:os?)?|Obadiah|Ob(?:ad?)?|Jon(?:ah?)?|Jnh|Mic(?:ah?)?|Mi|Nah?um|Nah?|Habakkuk|Hab|Zephaniah|Ze?ph?|Haggai|Hagg?|Hg|Zechariah|Ze?ch?|Malachi|Ma?l|Matthew|Matt?|Mt|Mark|Ma(?:r|k)|M(?:r|k)|Luke?|Lk|Lu?c|John|Jn|Ac(?:ts?)?|Romans|Ro?m|(?:1|i|2|ii) ?Corinthians|(?:1|i|2|ii) ?C(?:or?)?|Galatians|Gal?|Gl|Ephesians|Eph?|Philippians|Phil|Colossians|Co?l|(?:1|i|2|ii) ?Thessalonians|(?:1|i|2|ii) ?Th(?:e(?:ss?)?)?|(?:1|i|2|ii) ?Timothy|(?:1|i|2|ii) ?Tim|(?:1|i|2|ii) ?T(?:i|m)|Ti(?:tus)?|Ti?t|Philemon|Phl?m|Hebrews|Heb?|Jam(?:es)?|Jms|Jas|(?:1|i|2|ii) ?Peter|(?:1|i|2|ii) ?Pe?t?|(?:1|i|2|ii|3|iii) ?J(?:oh)?n?|Jude?|Revelations?|Rev|R(?:e|v)';
var apoc_books = '|Tobit?|To?b|Judi(?:th?)?|Jdt|(?:1|2) ?Mac(?:cabees)?|(?:1|2) ?Ma?|Wi(?:sdom)?|Wi?s|Sir(?:ach)?|Ba(?:ruc?h)?|Ba?r';
that.linkVerses = function() {
updateURLs();
insertBiblerefs(document.body);
if (that.showTooltips === true) {
addBiblerefListeners();
}
setup();
}
var updateURLs = function() {
bgHost = window.location.protocol + '//' + that.host;
toolsHost = bgHost + '/share/tooltips/data';
cdHost = bgHost + '/public/link-to-us/tooltips';
}
var insertBiblerefs = function(node) {
if (node.nodeType === 3) {
var new_nodes = searchNode(node,0);
return new_nodes;
}
else if (node.tagName != undefined && node.tagName.match(/^(?:a|h\d|img|pre|input|option)$/i)) {
return null;
}
else {
var children = node.childNodes;
var i = 0;
while(i<children.length) {
var new_nodes = insertBiblerefs(children[i]);
i += new_nodes +1;
}
}
return null;
}
var searchNode = function(node, inserted_nodes) {
var apoc_string = that.apocrypha === true ? apoc_books : '';
//finds book and chapter for each verse that been separated by &,and,etc...
var book_chap = '((?:('+book_string+apoc_string+')(?:\.)? ?)?(?:(\\d*):)?(\\d+(?:(?:ff|f|\\w)|(?:\\s?(?:-|–|—)\\s?\\d+)?)))([^a-z0-9]*)';
var regex_string = '(?:'+book_string+apoc_string+')(?:\.)? ?\\d+:\\d+(?:ff|f|\\w)?(?:\\s?(?:(?:(?:-|–|—)\\s?(?:(?:'+book_string+apoc_string+')(?:\.)?\\s)?)|(?:(?:,|;|&|&|and|cf\\.|cf)))\\s?(?:(?:(?:vv.|vs.|vss.|v.) ?)?\\d+\\w?)(?::\\d+\\w?)?)*';
var regex = new RegExp(regex_string,'i');
var verse_match = node.nodeValue.match(regex);
if (verse_match == null) {
return inserted_nodes;
} else {
var text = node.nodeValue;
var before_text = text.substr(0,text.indexOf(verse_match[0]));
var after_text = text.substr(text.indexOf(verse_match[0])+verse_match[0].length);
if (before_text.length > 0) {
var newTxtNode = document.createTextNode(before_text);
node.parentNode.insertBefore(newTxtNode, node);
inserted_nodes++;
}
var book_chap_regex = new RegExp(book_chap, 'gi');
var book;
var chapter;
var verse;
while (matched = book_chap_regex.exec(verse_match[0])) {
// break up what may be multiple references into links.
if (matched[2] != '' && matched[2] != null) {
book = matched[2];
}
if (matched[3] != '' && matched[3] != null) {
chapter = matched[3];
}
verse = matched[4];
var newLinkNode = document.createElement("a");
newLinkNode.className = 'bibleref';
newLinkNode.target = '_BLANK';
var passage = book+' '+chapter+':'+verse;
newLinkNode.href = bgHost+'/passage/?search='+passage+'&version='+that.version+'&src=tools';
newLinkNode.innerHTML = matched[1];
if (that.clickTooltip === true) {
newLinkNode.onclick=function() {return false};
}
node.parentNode.insertBefore(newLinkNode, node);
inserted_nodes++;
if (matched[6] != '') {
var newTxtNode = document.createTextNode(matched[5]);
node.parentNode.insertBefore(newTxtNode, node);
// do we need to update inserted_nodes with this?
}
}
if (after_text.length > 0) {
var newTxtNode = document.createTextNode(after_text);
node.parentNode.insertBefore(newTxtNode, node);
node.parentNode.removeChild(node);
inserted_nodes = searchNode(newTxtNode,inserted_nodes+1);
}
else {
node.parentNode.removeChild(node);
}
}
return inserted_nodes;
}
var addCSS = function() {
if (!addedCSS) {
var css = document.createElement('link');
css.type = "text/css";
css.rel = "stylesheet";
if (browser.search('MSIE 6.0') != -1) {
browser = 'ie6';
css.href = cdHost+'/theme/bglinks-ie.css';
} else {
css.href = cdHost+'/theme/popover.css';
}
css.media = "screen";
var n1 = document.getElementsByTagName("head")[0].childNodes[0]
n1.parentNode.insertBefore(css,n1);
addedCSS = true;
}
}
var addBiblerefListeners = function() {
var links = document.getElementsByTagName('a');
for ( var i = 0;i< links.length;i++) {
var link = links[i]
if (link.className && link.className == 'bibleref') {
if (that.clickTooltip !== true) {
addListener(link,'mouseover', linkMouseover);
addListener(link,'mouseout', linkMouseout);
} else {
addListener(link,'click', toggleTooltip);
}
}
}
}
var addListener = function (listen_object, action, callback) {
if (listen_object.addEventListener) {
if (action == 'mouseover') {
listen_object.addEventListener("mouseover",callback,false);
} else if (action == 'mouseout') {
listen_object.addEventListener("mouseout",callback,false);
} else if (action == 'click') {
listen_object.addEventListener("click",callback,false);
}
} else if (listen_object.attachEvent) {
if (action == 'mouseover') {
listen_object.attachEvent("onmouseover",callback);
} else if (action == 'mouseout') {
listen_object.attachEvent("onmouseout",callback);
} else if (action == 'click') {
listen_object.attachEvent("onclick",callback);
}
} else {
if (action == 'mouseover') {
listen_object.onmouseover = callback;
} else if (action == 'mouseout'){
listen_object.onmouseout = callback;
} else if (action == 'click') {
listen_object.onclick = callback;
}
}
}
var toggleTooltip = function(e) {
if (!e) {
e = window.event;
}
link = e.target || e.srcElement;
var reference;
var bibleref;
if (bibleref = link.getAttribute('data-bibleref')) {
reference = bibleref;
} else {
reference = link.href.match(/search=(.*?)(?:&.*)?$/)[1];
}
var id = reference.replace(/%20| /g, '');
var id = reference.replace(/:/g, '_');
var tooltip = document.getElementById('bg_popup-'+id);
if (tooltip === null || tooltip.style.display == 'none') {
showTooltip(e);
} else {
hideTooltip(e);
}
}
var showTooltip = function(e) {
if (!e) {
e = window.event;
}
link = e.target || e.srcElement;
var reference;
var bibleref;
if (bibleref = link.getAttribute('data-bibleref')) {
reference = bibleref;
} else {
reference = link.href.match(/search=(.*?)(?:&.*)?$/)[1];
}
var id = reference.replace(/%20| /g, '');
id = id.replace(/:/g, '_');
id = id.replace(/ /g, '');
var tooltip = document.getElementById('bg_popup-'+id);
hideAllTooltips(e);
if (tooltip === null) {
tooltip = getTooltip(reference, link);
} else {
tooltip_loc = tooltipLocation(link);
tooltip.style.left = tooltip_loc.offsetX+'px';
tooltip.style.top = tooltip_loc.offsetY+'px';
tooltip.style.display = 'block';
}
}
var hideTooltip = function(e) {
if (!e) {
e = window.event;
}
target = e.target || e.srcElement;
var reference;
var bibleref;
if (bibleref = link.getAttribute('data-bibleref')) {
reference = bibleref;
} else {
reference = link.href.match(/search=(.*?)(?:&.*)?$/)[1];
}
reference = reference.replace(/%20| /g, '');
reference = reference.replace(/:/g, '_');
var tooltip = document.getElementById('bg_popup-'+reference);
if (tooltip) {
tooltip.style.display = 'none';
}
}
var hideAllTooltips = function(e) {
var divs = container.children;
for (var i = 0;i < divs.length;i++) {
divs[i].style.display = 'none';
}
}
var linkMouseover = function(e) {
if (!e) {
e = window.event;
}
if (e.target.nodeName.toLowerCase() == 'a') {
window.clearTimeout(showTimer);
showTimer = window.setTimeout(function() {showTooltip(e)}, delay);
}
}
var linkMouseout = function(e) {
if (!e) {
e = window.event;
}
if (e.target.nodeName.toLowerCase() == 'a' && showTimer) {
window.clearTimeout(showTimer);
window.clearTimeout(hideTimer);
hideTimer = window.setTimeout(function() {hideTooltip(e)}, delay);
}
}
var tooltipMouseover = function(e) {
if (!e) {
e = window.event;
}
var relNode = e.relatedTarget || e.fromElement;
while (relNode && relNode != null && (!relNode.className || relNode.className.indexOf('bg_popup-outer') == -1) && relNode.nodeName.toLowerCase() != 'body') {
relNode = relNode.parentNode;
}
if (relNode && relNode.className && relNode.className.indexOf('bg_popup-outer') != -1) return;
window.clearTimeout(showTimer);
window.clearTimeout(hideTimer);
}
var tooltipMouseout = function(e) {
if (!e) {
e = window.event;
}
var relNode = e.relatedTarget || e.toElement;
while (relNode && relNode != null && (!relNode.className || relNode.className.indexOf('bg_popup-outer') == -1) && relNode.nodeName.toLowerCase() != 'body') {
relNode = relNode.parentNode;
}
if (relNode && relNode.className && relNode.className.indexOf('bg_popup-outer') != -1) return;
window.clearTimeout(hideTimer);
hideTimer = window.setTimeout(function() {hideAllTooltips(e)}, delay);
}
var createContainer = function() {
container = document.createElement('div');
container.id = 'bg_popup-container';
document.body.appendChild(container);
}
var getTooltip = function(reference, link) {
var tooltip = document.createElement('div');
tooltip.style.display='none';
tooltip.className = 'bg_popup bg_popup-outer';
var tooltip_loc = tooltipLocation(link);
tooltip.style.top = tooltip_loc.offsetY+'px';
tooltip.style.left = tooltip_loc.offsetX+'px';
var id = 'bg_popup-'+reference.replace(/%20/g, '');
id = id.replace(/:/g, '_');
id = id.replace(/ /g, '');
tooltip.id=id;
tooltip.innerHTML = '<div class="bg_popup-header"><div class="bg_popup-header_title"><strong>'+reference.replace(/%20/g, ' ')+'</strong></div></div><div class="bg_popup-content"><div class="bg_popup-spinner"><img alt="loading" src="'+cdHost+'/theme/images/tools/spinner.gif"/></div></div><div class="bg_popup-footer"><a class="bg_popup-bglogo" href="'+bgHost+'/" target="_blank"></a></div>';
tooltip.style.display = 'block';
addCloseButton(tooltip);
tooltip = container.appendChild(tooltip);
if (that.clickTooltip !== true) {
addListener(tooltip,'mouseover', tooltipMouseover);
addListener(tooltip,'mouseout', tooltipMouseout);
}
var remote_passage = document.createElement('script');
remote_passage.type = 'text/javascript';
remote_passage.src = toolsHost+'/?search='+reference+'&version='+that.version+'&callback=BGLinks.updateTooltip';
remote_passage.id = 'bg_remote_passage_script-'+reference.replace(/%20/g, '');
remote_passage.id = remote_passage.id.replace(/:/g, '_');
remote_passage.id = remote_passage.id.replace(/ /g, '');
var hook = document.getElementsByTagName('script')[0];
hook.parentNode.insertBefore(remote_passage, hook);
return tooltip;
}
that.updateTooltip = function(tooltip_content) {
var id = 'bg_popup-'+tooltip_content.reference.replace(/%20/g, '');
id = 'bg_popup-'+tooltip_content.reference.replace(/:/g, '_');
id = id.replace(/ /g, '');
var tooltip = document.getElementById(id);
var reference_display = tooltip_content.reference_display.replace(/%20/g,' ');
if (tooltip_content.text == undefined) {
if (tooltip.text == undefined) {
tooltip_content.text = 'Retrieving Passage...'
}
else {
tooltip_content.text = tooltip.text;
reference_display = tooltip.reference_display;
}
}
tooltip.innerHTML = '<div class="bg_popup-header"><div class="bg_popup-header_title"><strong>'+reference_display+' '+tooltip_content.version+'</strong></div></div><div class="bg_popup-content"><div class="bg_popup-content-bible"><p>'+tooltip_content.text+' <a class="bg_popup-copyright" href="'+bgHost+tooltip_content.version_url+'" target="_blank">('+tooltip_content.version+')</a> <a class="bg_popup-more" href="'+bgHost+'/passage/?search='+tooltip_content.reference+'&version='+tooltip_content.version+'&src=tools" target="_blank">More</a></p></div></div><div class="bg_popup-footer"><a class="bg_popup-bglogo" href="'+bgHost+'/" target="_blank"></a></div>';
addCloseButton(tooltip);
}
var addCloseButton = function(tooltip) {
var divs = tooltip.getElementsByTagName('div');
for (var i = 0; i < divs.length;i++) {
if (divs[i].className == 'bg_popup-header_right') {
addListener(divs[i], 'click', hideAllTooltips);
}
}
}
var tooltipLocation = function(link) {
var tooltip_height = 234;
var tooltip_width = 362;
if (typeof(window.innerWidth) == 'number') {
width = window.innerWidth;
height = window.innerHeight;
} else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
width = document.documentElement.clientWidth;
height = document.documentElement.clientHeight;
} else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
width = document.body.clientWidth;
height = document.body.clientHeight;
}
var display_loc = {};
var offsetPos = getOffsetPos(link);
var leftPos = offsetPos.leftPos;
var topPos = offsetPos.topPos;
if (link.offsetWidth/link.parentNode.offsetWidth >.5) {
leftPos = getOffsetPos(link.parentNode);
leftPos = leftPos.leftPos;
}
if ((leftPos + tooltip_width+5) > width) {
leftPos -= tooltip_width;
if ((leftPos + tooltip_width + link.offsetWidth) <= width) leftPos += link.offsetWidth;
if (leftPos + tooltip_width + 25 <= width) leftPos += 25;
if (leftPos - (link.offsetWidth/2) >= 0) leftPos -= (link.offsetWidth/2);
} else {
if (leftPos + (link.offsetWidth/2) <= width && link.offsetWidth/link.parentNode.offsetWidth <=.5) leftPos += (link.offsetWidth/2);
if (leftPos - 35 >= 0) {
leftPos -= 35;
}
}
var scrollY = window.pageYOffset || document.documentElement.scrollTop || 0;;
if ((topPos+link.offsetHeight+tooltip_height+15) <= height +scrollY || topPos-tooltip_height+5 <0) {
topPos += link.offsetHeight + 10;
} else {
topPos -= tooltip_height + 10;
}
display_loc.offsetY = topPos;
display_loc.offsetX = leftPos;
return (display_loc);
}
var getOffsetPos = function(linkObj) {
var topPos = leftPos = 0;
do {
topPos += linkObj.offsetTop;
leftPos += linkObj.offsetLeft;
if(document.all) {
topPos+=linkObj.clientTop;
leftPos+=linkObj.clientLeft;
}
} while ((linkObj = linkObj.offsetParent) != null);
return {'topPos' : topPos, 'leftPos' : leftPos};
}
var setup = function() {
if (!setupRun) {
if (that.showTooltips === true) {
addCSS();
addListener(document, 'click', hideAllTooltips);
}
createContainer();
setupRun = true;
}
}
return that;
})();
$(document).ready(function() {
BGLinks.linkVerses();
});
This is the script, located at http://churchofcwa.wikia.com/wiki/MediaWiki:Common.js/bglinks.js, that I am encountering an error with css, this script was copied from https://www.biblegateway.com/public/link-to-us/tooltips/bglinks.js and is not made by me. The issue I am encountering is via the css page (MediaWiki:Common.css) when changing the color of the script by
.bg_popup-content-bible {color:#000000}
The font color of the p tag within that div does not change. Originally I had it set to the p tag specifically of that div, but a css checker said that styling would be overqualified, and it was not functional nevertheless. What the script does is take all Bible verses listed on a page, and automatically links them to Biblegateway and creates a preview popup when hovering. However, the font is very unreadable and so I have tried to change it to black.
The popup currently has a near-white font (that blends with the popup)
and needs to have a black font, with the rest of the page content needs the near white font. When the script runs through it generates a div surrounding each bible verse, and the js applies to it (the div in which the Bible verse text appears is in the bg_popup-content-bible with a <p> tag), making it popup like so.
I have noted that in the script there is a section that calls for a "addedCSS"
var addCSS = function() {
if (!addedCSS) {
var css = document.createElement('link');
css.type = "text/css";
css.rel = "stylesheet";
if (browser.search('MSIE 6.0') != -1) {
browser = 'ie6';
css.href = cdHost + '/theme/bglinks-ie.css';
} else {
css.href = cdHost + '/theme/popover.css';
}
css.media = "screen";
var n1 = document.getElementsByTagName("head")[0].childNodes[0]
n1.parentNode.insertBefore(css, n1);
addedCSS = true;
}
}
I do not believe it is possible to change the url that the addedCss pull from, from the MediaWiki:Common.css, as this script was not made for the specific system being used (when removing or altering the variable the script does not work). I don't know if this is not happening because of a javascript issue (which is beyond me, and it's difficult to alter the script without breaking it) or if it's just a matter of incorrect css, but I have been working on this for several months here and there, and would like to get this final detail to work.
Try changing it to
.bg_popup-content-bible {color:#000000 !important;}
Ignore the CSS specificity checker. I have tested the below css on your site and it works. Make sure to put it in your site.css.
.bg_popup-content-bible p {
color: #000000;
}
It needs to be written as above because it has to override the <p> styling you've already set earlier in site.css:
p {
color: #f5f5f5
}
EDIT
It is not a problem with the script. Based on what you have said in the comments it seems like you are unable to actually edit / output css. So the other option is just to modify the script you've posted above:
Change this:
tooltip.innerHTML = '<div class="bg_popup-header"><div class="bg_popup-header_title"><strong>'+reference_display+' '+tooltip_content.version+'</strong></div></div><div class="bg_popup-content"><div class="bg_popup-content-bible"><p>'+tooltip_content.text+' <a class="bg_popup-copyright" href="'+bgHost+tooltip_content.version_url+'" target="_blank">('+tooltip_content.version+')</a> <a class="bg_popup-more" href="'+bgHost+'/passage/?search='+tooltip_content.reference+'&version='+tooltip_content.version+'&src=tools" target="_blank">More</a></p></div></div><div class="bg_popup-footer"><a class="bg_popup-bglogo" href="'+bgHost+'/" target="_blank"></a></div>';
to this:
tooltip.innerHTML = '<div class="bg_popup-header"><div class="bg_popup-header_title"><strong>'+reference_display+' '+tooltip_content.version+'</strong></div></div><div class="bg_popup-content"><div class="bg_popup-content-bible"><p style="color:#000000">'+tooltip_content.text+' <a class="bg_popup-copyright" href="'+bgHost+tooltip_content.version_url+'" target="_blank">('+tooltip_content.version+')</a> <a class="bg_popup-more" href="'+bgHost+'/passage/?search='+tooltip_content.reference+'&version='+tooltip_content.version+'&src=tools" target="_blank">More</a></p></div></div><div class="bg_popup-footer"><a class="bg_popup-bglogo" href="'+bgHost+'/" target="_blank"></a></div>';
Given the way Stack formats the code above, to make it very clear you are editing the part of the line above that says:
<p>'+tooltip_content.text+'
and making it:
<p style="color:#000000">'+tooltip_content.text+'

Easy Smooth Scroll Plugin: How do I offset scroll?

I am using the Easy Smooth Scroll Plugin for Wordpress.
Below is the .js file that the plugin uses:
var ss = {
fixAllLinks: function() {
var allLinks = document.getElementsByTagName('a');
for (var i = 0; i < allLinks.length; i++) {
var lnk = allLinks[i];
if ((lnk.href && lnk.href.indexOf('#') != -1) && ((lnk.pathname == location.pathname) || ('/' + lnk.pathname == location.pathname)) && (lnk.search == location.search)) {
ss.addEvent(lnk, 'click', ss.smoothScroll);
}
}
},
smoothScroll: function(e) {
if (window.event) {
target = window.event.srcElement;
} else if (e) {
target = e.target;
} else return;
if (target.nodeName.toLowerCase() != 'a') {
target = target.parentNode;
}
if (target.nodeName.toLowerCase() != 'a') return;
anchor = target.hash.substr(1);
var allLinks = document.getElementsByTagName('a');
var destinationLink = null;
for (var i = 0; i < allLinks.length; i++) {
var lnk = allLinks[i];
if (lnk.name && (lnk.name == anchor)) {
destinationLink = lnk;
break;
}
}
if (!destinationLink) destinationLink = document.getElementById(anchor);
if (!destinationLink) return true;
var destx = destinationLink.offsetLeft;
var desty = destinationLink.offsetTop;
var thisNode = destinationLink;
while (thisNode.offsetParent && (thisNode.offsetParent != document.body)) {
thisNode = thisNode.offsetParent;
destx += thisNode.offsetLeft;
desty += thisNode.offsetTop;
}
clearInterval(ss.INTERVAL);
cypos = ss.getCurrentYPos();
ss_stepsize = parseInt((desty - cypos) / ss.STEPS);
ss.INTERVAL = setInterval('ss.scrollWindow(' + ss_stepsize + ',' + desty + ',"' + anchor + '")', 10);
if (window.event) {
window.event.cancelBubble = true;
window.event.returnValue = false;
}
if (e && e.preventDefault && e.stopPropagation) {
e.preventDefault();
e.stopPropagation();
}
},
scrollWindow: function(scramount, dest, anchor) {
wascypos = ss.getCurrentYPos();
isAbove = (wascypos < dest);
window.scrollTo(0, wascypos + scramount);
iscypos = ss.getCurrentYPos();
isAboveNow = (iscypos < dest);
if ((isAbove != isAboveNow) || (wascypos == iscypos)) {
window.scrollTo(0, dest);
clearInterval(ss.INTERVAL);
location.hash = anchor;
}
},
getCurrentYPos: function() {
if (document.body && document.body.scrollTop) return document.body.scrollTop;
if (document.documentElement && document.documentElement.scrollTop) return document.documentElement.scrollTop;
if (window.pageYOffset) return window.pageYOffset;
return 0;
},
addEvent: function(elm, evType, fn, useCapture) {
if (elm.addEventListener) {
elm.addEventListener(evType, fn, useCapture);
return true;
} else if (elm.attachEvent) {
var r = elm.attachEvent("on" + evType, fn);
return r;
} else {
alert("Handler could not be removed");
}
}
}
ss.STEPS = 25;
ss.addEvent(window, "load", ss.fixAllLinks);
The live page is here: http://iamjoepro.com/album/promaha/
I have the smooth scroll scrolling to an anchor, but I would like to offset it by the height of my fixed header (120px)
I am no javascript expert, I'm hoping this is easy for someone, but I can't decipher where to add the offset in my .js file?
I had a similar issue and found that the following solution worked for me.
Change the line:
var desty = destinationLink.offsetTop;
to read:
var desty = destinationLink.offsetTop - 120;
(where '120' is the height in pixels of your fixed header)
Then, remove the line:
location.hash = anchor;
(otherwise, the page will scroll to your 120px offset but then return back to the location of the anchor)
Hope this helps!

How to make this floating menu work only when specific #divs become visible?

I needed to make a floating menu, I searched online and found a script here http://www.jtricks.com/javascript/navigation/floating.html
/* Script by: www.jtricks.com
* Version: 1.12 (20120823)
* Latest version: www.jtricks.com/javascript/navigation/floating.html
*
* License:
* GNU/GPL v2 or later http://www.gnu.org/licenses/gpl-2.0.html
*/
var floatingMenu =
{
hasInner: typeof(window.innerWidth) == 'number',
hasElement: typeof(document.documentElement) == 'object'
&& typeof(document.documentElement.clientWidth) == 'number'};
var floatingArray =
[
];
floatingMenu.add = function(obj, options)
{
var name;
var menu;
if (typeof(obj) === "string")
name = obj;
else
menu = obj;
if (options == undefined)
{
floatingArray.push(
{
id: name,
menu: menu,
targetLeft: 0,
targetTop: 0,
distance: .07,
snap: true,
updateParentHeight: false
});
}
else
{
floatingArray.push(
{
id: name,
menu: menu,
targetLeft: options.targetLeft,
targetRight: options.targetRight,
targetTop: options.targetTop,
targetBottom: options.targetBottom,
centerX: options.centerX,
centerY: options.centerY,
prohibitXMovement: options.prohibitXMovement,
prohibitYMovement: options.prohibitYMovement,
distance: options.distance != undefined ? options.distance : .07,
snap: options.snap,
ignoreParentDimensions: options.ignoreParentDimensions,
updateParentHeight:
options.updateParentHeight == undefined
? false
: options.updateParentHeight,
scrollContainer: options.scrollContainer,
scrollContainerId: options.scrollContainerId,
confinementArea: options.confinementArea,
confinementAreaId:
options.confinementArea != undefined
&& options.confinementArea.substring(0, 1) == '#'
? options.confinementArea.substring(1)
: undefined,
confinementAreaClassRegexp:
options.confinementArea != undefined
&& options.confinementArea.substring(0, 1) == '.'
? new RegExp("(^|\\s)" + options.confinementArea.substring(1) + "(\\s|$)")
: undefined
});
}
};
floatingMenu.findSingle = function(item)
{
if (item.id)
item.menu = document.getElementById(item.id);
if (item.scrollContainerId)
item.scrollContainer = document.getElementById(item.scrollContainerId);
};
floatingMenu.move = function (item)
{
if (!item.prohibitXMovement)
{
item.menu.style.left = item.nextX + 'px';
item.menu.style.right = '';
}
if (!item.prohibitYMovement)
{
item.menu.style.top = item.nextY + 'px';
item.menu.style.bottom = '';
}
};
floatingMenu.scrollLeft = function(item)
{
// If floating within scrollable container use it's scrollLeft
if (item.scrollContainer)
return item.scrollContainer.scrollLeft;
var w = window.top;
return this.hasInner
? w.pageXOffset
: this.hasElement
? w.document.documentElement.scrollLeft
: w.document.body.scrollLeft;
};
floatingMenu.scrollTop = function(item)
{
// If floating within scrollable container use it's scrollTop
if (item.scrollContainer)
return item.scrollContainer.scrollTop;
var w = window.top;
return this.hasInner
? w.pageYOffset
: this.hasElement
? w.document.documentElement.scrollTop
: w.document.body.scrollTop;
};
floatingMenu.windowWidth = function()
{
return this.hasElement
? document.documentElement.clientWidth
: document.body.clientWidth;
};
floatingMenu.windowHeight = function()
{
if (floatingMenu.hasElement && floatingMenu.hasInner)
{
// Handle Opera 8 problems
return document.documentElement.clientHeight > window.innerHeight
? window.innerHeight
: document.documentElement.clientHeight
}
else
{
return floatingMenu.hasElement
? document.documentElement.clientHeight
: document.body.clientHeight;
}
};
floatingMenu.documentHeight = function()
{
var innerHeight = this.hasInner
? window.innerHeight
: 0;
var body = document.body,
html = document.documentElement;
return Math.max(
body.scrollHeight,
body.offsetHeight,
html.clientHeight,
html.scrollHeight,
html.offsetHeight,
innerHeight);
};
floatingMenu.documentWidth = function()
{
var innerWidth = this.hasInner
? window.innerWidth
: 0;
var body = document.body,
html = document.documentElement;
return Math.max(
body.scrollWidth,
body.offsetWidth,
html.clientWidth,
html.scrollWidth,
html.offsetWidth,
innerWidth);
};
floatingMenu.calculateCornerX = function(item)
{
var offsetWidth = item.menu.offsetWidth;
var result = this.scrollLeft(item) - item.parentLeft;
if (item.centerX)
{
result += (this.windowWidth() - offsetWidth)/2;
}
else if (item.targetLeft == undefined)
{
result += this.windowWidth() - item.targetRight - offsetWidth;
}
else
{
result += item.targetLeft;
}
if (document.body != item.menu.parentNode
&& result + offsetWidth >= item.confinedWidthReserve)
{
result = item.confinedWidthReserve - offsetWidth;
}
if (result < 0)
result = 0;
return result;
};
floatingMenu.calculateCornerY = function(item)
{
var offsetHeight = item.menu.offsetHeight;
var result = this.scrollTop(item) - item.parentTop;
if (item.centerY)
{
result += (this.windowHeight() - offsetHeight)/2;
}
else if (item.targetTop === undefined)
{
result += this.windowHeight() - item.targetBottom - offsetHeight;
}
else
{
result += item.targetTop;
}
if (document.body != item.menu.parentNode
&& result + offsetHeight >= item.confinedHeightReserve)
{
result = item.confinedHeightReserve - offsetHeight;
}
if (result < 0)
result = 0;
return result;
};
floatingMenu.isConfinementArea = function(item, area)
{
return item.confinementAreaId != undefined
&& area.id == item.confinementAreaId
|| item.confinementAreaClassRegexp != undefined
&& area.className
&& item.confinementAreaClassRegexp.test(area.className);
};
floatingMenu.computeParent = function(item)
{
if (item.ignoreParentDimensions)
{
item.confinedHeightReserve = this.documentHeight();
item.confinedWidthReserver = this.documentWidth();
item.parentLeft = 0;
item.parentTop = 0;
return;
}
var parentNode = item.menu.parentNode;
var parentOffsets = this.offsets(parentNode, item);
item.parentLeft = parentOffsets.left;
item.parentTop = parentOffsets.top;
item.confinedWidthReserve = parentNode.clientWidth;
// We could have absolutely-positioned DIV wrapped
// inside relatively-positioned. Then parent might not
// have any height. Try to find parent that has
// and try to find whats left of its height for us.
var obj = parentNode;
var objOffsets = this.offsets(obj, item);
if (item.confinementArea == undefined)
{
while (obj.clientHeight + objOffsets.top
< item.menu.scrollHeight + parentOffsets.top
|| item.menu.parentNode == obj
&& item.updateParentHeight
&& obj.clientHeight + objOffsets.top
== item.menu.scrollHeight + parentOffsets.top)
{
obj = obj.parentNode;
objOffsets = this.offsets(obj, item);
}
}
else
{
while (obj.parentNode != undefined
&& !this.isConfinementArea(item, obj))
{
obj = obj.parentNode;
objOffsets = this.offsets(obj, item);
}
}
item.confinedHeightReserve = obj.clientHeight
- (parentOffsets.top - objOffsets.top);
};
floatingMenu.offsets = function(obj, item)
{
var result =
{
left: 0,
top: 0
};
if (obj === item.scrollContainer)
return;
while (obj.offsetParent && obj.offsetParent != item.scrollContainer)
{
result.left += obj.offsetLeft;
result.top += obj.offsetTop;
obj = obj.offsetParent;
}
if (window == window.top)
return result;
// we're IFRAMEd
var iframes = window.top.document.body.getElementsByTagName("IFRAME");
for (var i = 0; i < iframes.length; i++)
{
if (iframes[i].contentWindow != window)
continue;
obj = iframes[i];
while (obj.offsetParent)
{
result.left += obj.offsetLeft;
result.top += obj.offsetTop;
obj = obj.offsetParent;
}
}
return result;
};
floatingMenu.doFloatSingle = function(item)
{
this.findSingle(item);
if (item.updateParentHeight)
{
item.menu.parentNode.style.minHeight =
item.menu.scrollHeight + 'px';
}
var stepX, stepY;
this.computeParent(item);
var cornerX = this.calculateCornerX(item);
var stepX = (cornerX - item.nextX) * item.distance;
if (Math.abs(stepX) < .5 && item.snap
|| Math.abs(cornerX - item.nextX) <= 1)
{
stepX = cornerX - item.nextX;
}
var cornerY = this.calculateCornerY(item);
var stepY = (cornerY - item.nextY) * item.distance;
if (Math.abs(stepY) < .5 && item.snap
|| Math.abs(cornerY - item.nextY) <= 1)
{
stepY = cornerY - item.nextY;
}
if (Math.abs(stepX) > 0 ||
Math.abs(stepY) > 0)
{
item.nextX += stepX;
item.nextY += stepY;
this.move(item);
}
};
floatingMenu.fixTargets = function()
{
};
floatingMenu.fixTarget = function(item)
{
};
floatingMenu.doFloat = function()
{
this.fixTargets();
for (var i=0; i < floatingArray.length; i++)
{
this.fixTarget(floatingArray[i]);
this.doFloatSingle(floatingArray[i]);
}
setTimeout('floatingMenu.doFloat()', 20);
};
floatingMenu.insertEvent = function(element, event, handler)
{
// W3C
if (element.addEventListener != undefined)
{
element.addEventListener(event, handler, false);
return;
}
var listener = 'on' + event;
// MS
if (element.attachEvent != undefined)
{
element.attachEvent(listener, handler);
return;
}
// Fallback
var oldHandler = element[listener];
element[listener] = function (e)
{
e = (e) ? e : window.event;
var result = handler(e);
return (oldHandler != undefined)
&& (oldHandler(e) == true)
&& (result == true);
};
};
floatingMenu.init = function()
{
floatingMenu.fixTargets();
for (var i=0; i < floatingArray.length; i++)
{
floatingMenu.initSingleMenu(floatingArray[i]);
}
setTimeout('floatingMenu.doFloat()', 100);
};
// Some browsers init scrollbars only after
// full document load.
floatingMenu.initSingleMenu = function(item)
{
this.findSingle(item);
this.computeParent(item);
this.fixTarget(item);
item.nextX = this.calculateCornerX(item);
item.nextY = this.calculateCornerY(item);
this.move(item);
};
floatingMenu.insertEvent(window, 'load', floatingMenu.init);
// Register ourselves as jQuery plugin if jQuery is present
if (typeof(jQuery) !== 'undefined')
{
(function ($)
{
$.fn.addFloating = function(options)
{
return this.each(function()
{
floatingMenu.add(this, options);
});
};
}) (jQuery);
}
The script requires the menu to have #floatdiv id. I made my div, #floatdiv, and added the following line of javascript to the head to make the action start working:
<script type="text/javascript">
floatingMenu.add('floatdiv',
{
targetLeft: 250,
targetTop: 290,
snap: true
});
</script>
the #floatdiv css is here,
#floatdiv{
height:45px;
width:830px;
z-index:2;
}
The script is working fine. When I scroll down, the menu float as specified. But I dun wanna the menu to float all the way with scrolling. I need the float of the menu to fire only when I enter specific divs not all the way with scrolling.. Any clues?
is this what look like?
html
<div id="header">HEADER</div>
<div id="content">
<div id="left">LEFT</div>
<div id="right">RIGHT</div>
</div>
<div id="footer">FOOTER</div>
js
$(function() {
var $sidebar = $("#right"),
$window = $(window),
rightOffset = $sidebar.offset(),
rightDelta = $("#footer").offset().top - $("#header").offset().top - $("#header").outerHeight() - $("#right").outerHeight(),
topPadding = 15;
$window.scroll(function() {
$sidebar.stop().animate({
marginTop: Math.max(Math.min($window.scrollTop() - rightOffset.top + topPadding, rightDelta), 0)
});
});
});
working demo
hope this help you
I wrote the script listed in the question.
The script is very versatile and can make div float within a specific area (e.g. another container div). Here are the instructions:
http://www.jtricks.com/javascript/navigation/floating/confined_demo.html

Trying to find javascript element's position on screen....Not working properly on webkit browsers

This is the code i'm using right now. On webkit browsers (Chrome and Safari Specifically) if the page is scrolled, it doesn't take into account the amount that page has been scrolled. I need help redesigning the function to work for Webkit browsers. And I don't want to be loading up jQuery as this will be used on a web widget and I need to keep the file size down. Thanks guys!
function __getIEVersion() {
var rv = -1; // Return value assumes failure.
if (navigator.appName == 'Microsoft Internet Explorer') {
var ua = navigator.userAgent;
var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
if (re.exec(ua) != null)
rv = parseFloat(RegExp.$1);
}
return rv;
}
function __getOperaVersion() {
var rv = 0; // Default value
if (window.opera) {
var sver = window.opera.version();
rv = parseFloat(sver);
}
return rv;
}
var __userAgent = navigator.userAgent;
var __isIE = navigator.appVersion.match(/MSIE/) != null;
var __IEVersion = __getIEVersion();
var __isIENew = __isIE && __IEVersion >= 8;
var __isIEOld = __isIE && !__isIENew;
var __isFireFox = __userAgent.match(/firefox/i) != null;
var __isFireFoxOld = __isFireFox && ((__userAgent.match(/firefox\/2./i) != null) ||
(__userAgent.match(/firefox\/1./i) != null));
var __isFireFoxNew = __isFireFox && !__isFireFoxOld;
var __isWebKit = navigator.appVersion.match(/WebKit/) != null;
var __isChrome = navigator.appVersion.match(/Chrome/) != null;
var __isOpera = window.opera != null;
var __operaVersion = __getOperaVersion();
var __isOperaOld = __isOpera && (__operaVersion < 10);
function __parseBorderWidth(width) {
var res = 0;
if (typeof(width) == "string" && width != null && width != "" ) {
var p = width.indexOf("px");
if (p >= 0) {
res = parseInt(width.substring(0, p));
}
else {
//do not know how to calculate other values
//(such as 0.5em or 0.1cm) correctly now
//so just set the width to 1 pixel
res = 1;
}
}
return res;
}
//returns border width for some element
function __getBorderWidth(element) {
var res = new Object();
res.left = 0; res.top = 0; res.right = 0; res.bottom = 0;
if (window.getComputedStyle) {
//for Firefox
var elStyle = window.getComputedStyle(element, null);
res.left = parseInt(elStyle.borderLeftWidth.slice(0, -2));
res.top = parseInt(elStyle.borderTopWidth.slice(0, -2));
res.right = parseInt(elStyle.borderRightWidth.slice(0, -2));
res.bottom = parseInt(elStyle.borderBottomWidth.slice(0, -2));
}
else {
//for other browsers
res.left = __parseBorderWidth(element.style.borderLeftWidth);
res.top = __parseBorderWidth(element.style.borderTopWidth);
res.right = __parseBorderWidth(element.style.borderRightWidth);
res.bottom = __parseBorderWidth(element.style.borderBottomWidth);
}
return res;
}
//returns the absolute position of some element within document
function getElementAbsolutePos(element) {
var res = new Object();
res.x = 0; res.y = 0;
if (element !== null) {
if (element.getBoundingClientRect) {
var viewportElement = document.documentElement;
var box = element.getBoundingClientRect();
var scrollLeft = viewportElement.scrollLeft;
var scrollTop = viewportElement.scrollTop;
res.x = box.left + scrollLeft;
res.y = box.top + scrollTop;
}
else { //for old browsers
res.x = element.offsetLeft;
res.y = element.offsetTop;
var parentNode = element.parentNode;
var borderWidth = null;
while (offsetParent != null) {
res.x += offsetParent.offsetLeft;
res.y += offsetParent.offsetTop;
var parentTagName =
offsetParent.tagName.toLowerCase();
if ((__isIEOld && parentTagName != "table") ||
((__isFireFoxNew || __isChrome) &&
parentTagName == "td")) {
borderWidth = kGetBorderWidth
(offsetParent);
res.x += borderWidth.left;
res.y += borderWidth.top;
}
if (offsetParent != document.body &&
offsetParent != document.documentElement) {
res.x -= offsetParent.scrollLeft;
res.y -= offsetParent.scrollTop;
}
//next lines are necessary to fix the problem
//with offsetParent
if (!__isIE && !__isOperaOld || __isIENew) {
while (offsetParent != parentNode &&
parentNode !== null) {
res.x -= parentNode.scrollLeft;
res.y -= parentNode.scrollTop;
if (__isFireFoxOld || __isWebKit)
{
borderWidth =
kGetBorderWidth(parentNode);
res.x += borderWidth.left;
res.y += borderWidth.top;
}
parentNode = parentNode.parentNode;
}
}
parentNode = offsetParent.parentNode;
offsetParent = offsetParent.offsetParent;
}
}
}
var scrOfX = 0, scrOfY = 0;
if( typeof( window.pageYOffset ) == 'number' ) {
//Netscape compliant
scrOfY = window.pageYOffset;
scrOfX = window.pageXOffset;
} else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
//DOM compliant
scrOfY = document.body.scrollTop;
scrOfX = document.body.scrollLeft;
} else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
//IE6 standards compliant mode
scrOfY = document.documentElement.scrollTop;
scrOfX = document.documentElement.scrollLeft;
}
return res;
}
if (element.getBoundingClientRect) {
var viewportElement = document.documentElement;
var box = element.getBoundingClientRect();
var scrollLeft = viewportElement.scrollLeft;
var scrollTop = viewportElement.scrollTop;
res.x = box.left + scrollLeft;
res.y = box.top + scrollTop;
}
I'm concerned that this code block only uses one way of attempting to detect the scroll position. I would move the bottom block of code to the top of the function and use scrOfX/Y instead of scrollLeft and scrollTop.

Categories

Resources