(jQuery to Vanilla Javascript) fixed floating element - javascript

I am not a big fan of jQuery because it can cause a bigger load time on the page load(even if it's small), so I refrain from using jQuery as much as possible.
I am trying to convert this jQuery code to plain javascript, could someone lead me in the correct direction?
Non-working non-jquery javascript
window.onload = function()
{
var scrolledElement = document.querySelector('#comment');
var top = scrolledElement.offsetTop;
window.scroll(function()
{
var y = window.pageYOffset;
if (y >= top)
{
scrolledElement.classList.add('fixed');
} else {
scrolledElement.classList.remove('fixed');
}
});
});
and this is the actual code for jQuery.
$(document).ready(function () {
var top = $('#comment').offset().top - parseFloat($('#comment').css('marginTop').replace(/auto/, 0));
$(window).scroll(function (event) {
var y = $(this).scrollTop();
if (y >= top) {
$('#comment').addClass('fixed');
} else {
$('#comment').removeClass('fixed');
}
});
});
Here is what I have so far in jsfiddle. http://jsfiddle.net/knjQh/29/

Update your JS to attach a event on scroll
window.onload = function () {
var scrolledElement = document.querySelector('#comment');
var top = scrolledElement.offsetTop;
var listener = function () {
var y = window.pageYOffset;
if (y >= top) {
scrolledElement.classList.add('fixed');
} else {
scrolledElement.classList.remove('fixed');
}
};
window.addEventListener('scroll', listener, false);
}
Check
http://jsfiddle.net/raunakkathuria/knjQh/33/

Related

convert jQuery to plain javascript code

i'm trying to replicate the navbar of this website, i have successfully implement it using jQuery but i need to rewrite this in plain javascript
(function ($) {
$(document).ready(function () {
var $nav1 = $("#nav-1"),
$nav2 = $("#nav-2"),
$sticky = $nav1.before($nav2.addClass("fixed").removeClass("hide"));
$(window).on("scroll", function () {
var fromTop = $(window).scrollTop();
$("body").toggleClass("on-scroll", (fromTop > 200));
});
});
})(jQuery);
this is my attempt to rewrite it in plain JS but its not working atm
(function () {
var nav1 = document.getElementById("nav-1"),
nav2 = document.getElementById("nav-2"),
sticky = nav1.insertAdjacentHTML("beforebegin", nav2.outerHTML);
// nav2.className += " fixed";
nav2.classList.add("fixed");
nav2.classList.remove("hide");
window.onscroll = function () {
var fromTop = window.scrollTop;
body.classList.toggle("on-scroll", fromTop > 200);
};
}());
You are very close, first of, you probably want to remove the orginal #nav-2 since you are making a copy. Second of, you want to determine the scrollTop of the body, which you access by document.body, see updates below:
(function () {
var nav1 = document.getElementById("nav-1"),
nav2 = document.getElementById("nav-2"),
sticky = nav1.insertAdjacentHTML("beforebegin", nav2.outerHTML);
nav2.parentElement.removeChild(nav2);
// nav2.className += " fixed";
nav2.classList.add("fixed");
nav2.classList.remove("hide");
window.onscroll = function () {
var fromTop = document.body.scrollTop;
document.body.classList.toggle("on-scroll", fromTop > 200);
};
}());
JSFiddle

Jquery typing effect on scroll bug

Hi I have some js code that do typing effect on my web page it start typing when you scroll down end of page. For first it work normally but when you start scroll faster down to up the typing effect goes crazy how can I fix that
demo page
code
$(window).scroll(function (e) {
var elem = $(".hello-page");
var scrollTop = $(window).scrollTop();
var blockTop = elem.offset().top;
var docHeight = $(document).height();
var windowH = $(window).height();
if (scrollTop >= blockTop) {
var helloPageA = $(".hello-page").find("a");
var text = helloPageA.attr("data-text");
helloPageA.text('');
$.each(text.split(''), function (i, letter) {
setTimeout(function () {
helloPageA.html(helloPageA.html() + letter);
}, 150 * i);
});
} else {
elem.find("a").text('');
}
});
jsfiddle example
Thanks for your help
So, here is the solution - http://jsfiddle.net/u3ojjx8r/1/
I borrowed initial structure of the code from previous answer here and it was removed unfortunately, therefore I can't mention one of the co-authors. Though the code looked quite similar to topic-starter's one.
The idea of the code below is to separate the queuing of characters to render and the actual rendering. Another important improvement is always have control over timeouts, i.e. never schedule more than one timeout. That allows you to cancel them any time without unpredicted/uncontrolled behavior.
var timeoutVar;
var queue = [];
var drawQueueTimeout = -1;
var helloPageA = $(".hello-page").find("a");
function pushQueue (element) {
console.log('pushQUeue', element.char);
queue.push(element);
checkQueue();
}
function flushQueue () {
console.log('flushQueue');
queue = [];
clearTimeout(drawQueueTimeout);
drawQueueTimeout = -1;
}
function checkQueue () {
console.log('checkQueue', queue.length, drawQueueTimeout);
if (queue.length > 0 && drawQueueTimeout < 0) {
console.log('schedule drawQueue');
drawQueueTimeout = setTimeout(drawQueue, 150);
}
}
function drawQueue () {
drawQueueTimeout = -1;
console.log('draw queue');
if (queue.length > 0) {
var element = queue.shift();
console.log('drawQueue', element.char);
helloPageA.html(helloPageA.html() + element.char);
}
checkQueue();
}
$(window).scroll(function (e) {
var elem = $(".hello-page");
var scrollTop = $(window).scrollTop();
var blockTop = elem.offset().top;
var docHeight = $(document).height();
var windowH = $(window).height();
if (scrollTop + windowH == docHeight) {
// Empty anything typed so far
helloPageA.empty();
flushQueue();
var text = helloPageA.attr("data-text");
helloPageA.text('');
$.each(text.split(''), function (i, letter) {
pushQueue({
char: letter,
index: i
});
});
} else {
helloPageA.empty();
flushQueue();
}
});

how to fix loop "go to bottom" when i scroll top

After you click Go To Bottom then roll the mouse over it just automatically roll down it? way still uses the setInterval without fail no summer?
link source code
http://jsfiddle.net/trananh/v7gdr4n0/
var process;
var delay = 50;
var scrollPixel = 20;
//Fix Undefine pageofset when using IE 8 below;
function getPapeYOfSet() {
var yOfSet = (typeof (window.pageYOffset) === "number") ? window.pageYOffset : document.documentElement.scrollTop;
return yOfSet;
}
function goToBottom() {
process = setInterval(function () {
var yOfSet = getPapeYOfSet();
if (yOfSet >= document.body.scrollHeight) {
clearInterval(process);
} else {
window.scrollBy(0, scrollPixel);
}
}, delay);
}
JAvascript function goToBottom

javascript code not working if placed at top of file

I have the following code. It set a filter bar in a search results page in a fixed position in the window after scrolling down to a certain point:
var docked;
var filters = document.getElementById('filters');
var init = filters.offsetTop;
function scrollTop() {
return document.body.scrollTop || document.documentElement.scrollTop;
}
window.onscroll = function () {
if (!docked && (init - scrollTop() < 0)) {
filters.style.top = 0;
filters.style.position = 'fixed';
filters.className = 'docked';
docked = true;
} else if (docked && scrollTop() <= init) {
filters.style.position = 'absolute';
filters.style.top = init + 'px';
filters.className = filters.className.replace('docked', '');
docked = false;
}
}
My issue is (and it's more curiosity) - if I place this code at the top of my file (in the <head>), it doesn't work at all. The filter section doesn't scroll with the window as it should. However, when I place this code at the bottom of the file (right above the closing </body> tag), it works just fine.
Why is this? Does this have something to do with the way the code works? Or could it be just a quirk or bug in the rest of my file causing this?
Wrap your assignments in window.onload = function(){ /* your code here */ }; and it will run. The reason being that your assignment of var filters = document.getElementById('filters'); comes back as undefined since that element does not exist during page load at the time you reference it.
Example:
var docked;
var filters;
var init;
window.onload = function(){
filters = document.getElementById('filters');
init = filters.offsetTop;
};
if you do this, it should work:
$(document).ready(window.onscroll = function () {
if (!docked && (init - scrollTop() < 0)) {
filters.style.top = 0;
filters.style.position = 'fixed';
filters.className = 'docked';
docked = true;
} else if (docked && scrollTop() <= init) {
filters.style.position = 'absolute';
filters.style.top = init + 'px';
filters.className = filters.className.replace('docked', '');
docked = false;
}
}
);

Floating widget/banner using the prototype JS

I created a script using the originals from jQuery: http://terkel.jp/demo/jquery-floating-widget-plugin.html
But when typing to prototype JS it is not working properly.
It strictly doesn't count correctly the upper and lower height.
Any thoughts? I attached my code and link to view the active script.
Online problem: http://1.delnik20.cz/
Prototype:
document.observe('dom:loaded', function() {
Element.addMethods({
floatingWidget: function(el, classes) {
var $this = $(el),
$parent = $this.getOffsetParent(),
$window = $(window),
top = $this.positionedOffset().top - parseFloat($this.getStyle('marginTop').replace(/auto/, 0)),
bottom = $parent.positionedOffset().top + $parent.getHeight() - $this.getHeight();
if ($parent.getHeight() > $this.getHeight()) {
Event.observe($window, 'scroll', function (e) {
var y = document.viewport.getScrollOffsets().top;
if (y > top) {
$this.addClassName(classes.floatingClass);
if (y > bottom) {
$this.removeClassName(classes.floatingClass).addClassName(classes.pinnedBottomClass);
} else {
$this.removeClassName(classes.pinnedBottomClass);
}
} else {
$this.removeClassName(classes.floatingClass);
}
});
}
return el;
}
});
$('floating-widget').floatingWidget({
floatingClass: 'floating',
pinnedBottomClass: 'pinned-bottom'
});
});
Prototypejs equivalent to jQuery's offset() is cumulativeOffset(), the equivalent to outerHeight() is measure('margin-box-height') (which may be optimized using the Element.Layout object). Thus your code should look like:
floatingWidget: function(el, classes) {
var $this = $(el),
$parent = $this.getOffsetParent(),
$window = $(window),
top = $this.cumulativeOffset().top - $this.measure('margin-top'),
bottom = $parent.cumulativeOffset().top + $parent.getHeight() - $this.measure('margin-box-height');
if ($parent.getHeight() > $this.measure('margin-box-height')) {
...

Categories

Resources