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
Related
I've been designing a web infographic with some animations within the page. So I added some JavaScript code in order to trigger the animations as the user reaches them on screen.
My question is how to add many div names in a JavaScript sentence?
The name of the div is "box_info_a", I just need to add some more, but have no idea how.
This is the code:
$(function()
var $window = $(window),
win_height_padded = $window.height() * 1.1,
isTouch = Modernizr.touch;
if (isTouch) {
$('.revealOnScroll').addClass('box_info_a');
}
$window.on('scroll', revealOnScroll);
function revealOnScroll() {
var scrolled = $window.scrollTop(),
win_height_padded = $window.height() * 1.1;
// Showed...
$(".revealOnScroll:not(.box_info_a)").each(function () {
var $this = $(this),
offsetTop = $this.offset().top;
if (scrolled + win_height_padded > offsetTop) {
if ($this.data('timeout')) {
window.setTimeout(function() {
$this.addClass('box_info_a ' + $this.data('animation'));
}, parseInt($this.data('timeout'), 10));
} else {
$this.addClass('box_info_a ' + $this.data('animation'));
}
}
}); // Close Showed...
// Hidden...
$(".revealOnScroll.box_info_a").each(function (index) {
var $this = $(this),
offsetTop = $this.offset().top;
if (scrolled + win_height_padded < offsetTop) {
$(this).removeClass('box_info_a lightSpeedIn')
}
});
}
revealOnScroll();
});
Just do this:
$(document).ready(function () {
$('#trigger').click(function () {
$('#target').addClass("oneClassToAdd anotherClassToAdd");
});
});
All you have to do is put two classes in the parentheses.
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();
}
});
hi guys so i have this code ive done which when scrolling the sidebar moves up from bottom to top but im stuck with how to stop the scrolling once the sidebar hits the top of the main conatiner - can someone maybe help me with this?
code is:
$(window).bind('scroll', function () {
var scrolledY = $(window).scrollTop();
$('.parallax-sidebar').css('bottom', '+' + ((scrolledY * 1.3)) + 'px');
});
I have a fiddle example here: http://jsfiddle.net/06qwtgt6/1/
Many thanks!
$(document).ready(function () {
/********************************************************************************/
/* Parallax Scrolling */
// Cache the Window object
var $window = $(window);
$('[data-type]').each(function () {
$(this).data('offsetY', parseInt($(this).attr('data-offsetY')));
$(this).data('Xposition', $(this).attr('data-Xposition'));
$(this).data('speed', $(this).attr('data-speed'));
});
// For each element that has a data-type attribute
$('div[data-type="background"]').each(function () {
var $self = $(this),
offsetCoords = $self.offset(),
topOffset = offsetCoords.top;
$(window).bind('scroll', function () {
if (($window.scrollTop() + $window.height()) > (topOffset) &&
((topOffset + $self.height()) > $window.scrollTop())) {
var yPos = -($window.scrollTop() / $self.data('speed'));
if ($self.data('offsetY')) {
yPos += $self.data('offsetY');
}
var coords = '50% ' + yPos + 'px';
$self.css({ backgroundPosition: coords });
};
});
});
// For each element that has a data-type attribute
$('div[data-type="content"]').each(function () {
$(window).bind('scroll', function () {
var scrolledY = $(window).scrollTop();
$('.parallax-content').css('bottom', '+' + ((scrolledY * 1.3)) + 'px');
});
});
$(window).scroll(function(){
if ($(this).scrollTop() > 150) {
$('.sidebar').addClass('fixed');
} else {
$('.sidebar').removeClass('fixed');
}
});
});
CSS
.fixed {position:fixed; top:0;}
DEMO
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/
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')) {
...