Changing background image referred to each menu item only by scrolling - javascript

I'm developing a wordpress theme that has a function of changing background image by hovering menu item(each menu item is attached different image). On mobile, I'd like to change background image just by scrolling so that viewers don't need to click each menu to change the background image.
This is the method I implemented to change background by hovering.
http://codepen.io/nummelin/pen/kzaso
// When any of the a's inside of sidebarContainer are hovered
$( ".sidebarContainer a" ).hover(function() {
// Removes all previous classes but keeps sidebar1
$('.sidebar1').removeClass().addClass('sidebar1');
// Splits up the URL on the current href
var URI = $(this).attr('href').split('/');
console.log(URI[2]);
// Applies the last part of the URL to sidebar1
$('.sidebar1').addClass(URI[2]);
});
Achieving with scrolling, I think I need a function that hovering menu item by its position like the image below.
Does anyone have any ideas how to achieve this? I've been exploring a plugin or sample code similar to this, but haven't found any...
Any advices would be appreciated.

Okay, so this is the code I wrote. Hope it helps. I've worked on cross-fading effect but it wasn't that easy. If someone tried please teach me how to do it.
Demo on Codepen:
http://codepen.io/bavavava/pen/rrNpaY
jQuery(function($){
'use strict';
$(document).ready(function(){
var elem = $('li.list-item'),
$listPosition = $.map(elem, function(el, i) { return $(el).offset().top; }),
$listURL = $.map(elem, function(el,i) { return $(el).find('a').attr('href'); }),
$bg = $('.container');
console.log($listPosition);
console.log($listURL);
//PRELOAD IMAGES
$.fn.preload = function() {
this.each(function(){
$('<img/>')[0].src = this;
});
}
$($listURL).preload();
//SCROLL CHANGE
$(window).on('scroll', function () {
var windowScroll = $(this).scrollTop();
$.each($listPosition, function (i, pos) {
if (windowScroll >= pos) {
$bg.css('background', 'url(' + $listURL[i] + '), black no-repeat center center fixed');
}
});
});
});
});

Related

Smooth scroll elements inside child div which is below header

So here is the fiddle link https://jsfiddle.net/malakar369/y5Lppeg0/8/
jQuery(document).ready(function ($) {
$('.custom-click').on('click', function (e) {
e.preventDefault();
var href = $(this).attr('href');
var current_div = $(href);
var animateTo = $(href).position().top ;
console.log(animateTo);
$('#main-height-container').animate({scrollTop: animateTo},"slow");
});
});
It works if my div is at the top of the page. However, since it is not at the top i am having and extensive amount of issue. Could any of you guys could have a look at it and help me out.
Thanks
$(href).position().top is in window coordinates
Try this
var animateTo = $("#main-height-container").scrollTop() - $("#main-height-container").position().top + $(href).position().top;
https://jsfiddle.net/y5Lppeg0/9/

Wow.js repeat animation every time you scroll up or down

I'm pretty new with Jquery. I would like that my animations with Wow.js could run more than once time. For instance: i scroll to the bottom of my page and see all the animations, and if i scroll back to the top i see again the animations like when you scroll down. I hope that I explained myself. I have already seen many websites that repeats the animations on theirs pages but unfortunately I don't remember them and I can't provide a link.
I have already tried this:
$(window).scroll(function(){
new WOW().init();
}
But it repeat the animations also if you scroll a little and it's pretty ugly to see. I try to explain me better: I have a with my animation and if it is focused the animation is triggered, then i scroll down to another div and the previous div is no more visible(not in the window viewport), then again i scroll back to my div with animation and the animation is triggered again.
I'm sorry for this messy question but I really don't know how to explain it.
Thanks in advance!
This example by Benoît Boucart shows how the animation can be "reset" when the user scrolls out of view and back in. The key here is the second function that removes the animation css class when the element scrolls out of view. I wish WOW.js would implement this, but they've indicated that they don't plan to.
http://codepen.io/benske/pen/yJoqz
Snippet:
// Showed...
$(".revealOnScroll:not(.animated)").each(function () {
var $this = $(this),
offsetTop = $this.offset().top;
if (scrolled + win_height_padded > offsetTop) {
if ($this.data('timeout')) {
window.setTimeout(function(){
$this.addClass('animated ' + $this.data('animation'));
}, parseInt($this.data('timeout'),10));
} else {
$this.addClass('animated ' + $this.data('animation'));
}
}
});
// Hidden...
$(".revealOnScroll.animated").each(function (index) {
var $this = $(this),
offsetTop = $this.offset().top;
if (scrolled + win_height_padded < offsetTop) {
$(this).removeClass('animated fadeInUp flipInX lightSpeedIn')
}
});
If a user wants to repeat the animation on both the events i.e.
onScrollUp
onScrollDown
then this will be a good solution for it:
First create an addBox function, it will help to push new elements into the WOW boxes array.
WOW.prototype.addBox = function(element){
this.boxes.push(element);
};
Then use jQuery and scrollspy plugin that helps to detect which element is out of the view and then push WOW as:
$('.wow').on('scrollSpy:exit',function(){
var element = $(this);
element.css({
'visibility' : 'hidden',
'animation-name' : 'none'
}).removeClass('animated');
wow.addBox(this);
});
Solution Courtesy: ugurerkan
Answer by #vivekk is correct I m just adding a working example so that people can easily get this
see the Demo fiddle
<script>
// Repeat demo content
var $body = $('body');
var $box = $('.box');
for (var i = 0; i < 20; i++) {
$box.clone().appendTo($body);
}
// Helper function for add element box list in WOW
WOW.prototype.addBox = function(element) {
this.boxes.push(element);
};
// Init WOW.js and get instance
var wow = new WOW();
wow.init();
// Attach scrollSpy to .wow elements for detect view exit events,
// then reset elements and add again for animation
$('.wow').on('scrollSpy:exit', function() {
$(this).css({
'visibility': 'hidden',
'animation-name': 'none'
}).removeClass('animated');
wow.addBox(this);
}).scrollSpy();
</script>

remove one class when animating

I try to animate menu-panel. It should slide to the left. But it doesn't work right. And I can't understand why.
There are a few issues with the current code (e.g. you were missing a . on one panel selector and not referencing panel1 after changing the panel class. I also switched to absolute positioning with the arrow inside the panel.
I did a little cleanup to make the changes obvious (you should not repeat jQuery selectors - use temp vars instead):
JSFiddle: http://jsfiddle.net/TrueBlueAussie/2x3uT/8/
$(function () {
$('.slider-arrow').click(function () {
var $this = $(this);
var $panel = $(".panel, .panel1");
var left = -53;
var text = '»';
if ($this.hasClass('hide')) {
text = '«';
left = 0;
}
$panel.animate({
left: left
}, 700, function () {
// Animation complete.
$this.html(text).toggleClass('hide').toggleClass('show');
$panel.toggleClass('panel').toggleClass('panel1');
});
});
});
You can tweak the position numbers to make it match what you wanted.

Making nav bar effects using scroll AND click in jQuery

I want a nav to highlight (or something similar) once a user clicks on it AND when a user scrolls to the corresponding section.
However, on my computer when one clicks on any of the nav events after3, only nav event 3 changes. I'm guessing this is because after one clicks on 4 or 5, the scroll bar is already at the bottom of the page, so 4 and 5 never reach the top. The only div at the top is post 3, so my code highlights nav event 3 and ignores the click.
Is there any way I can fix this? Ive tried if statements (only highlight nav event if it's at the top AND the scrollbar isn't at the bottom or the top isn't the last item).
Here is a more accurate fiddle, using a fix below showing what I am talking about. The fix now highlights on scroll, but if you click option 5, it will not highlight.
$('.option').children('a').click(function() {
$('.option').css('background-color', '#CCCCCC;');
$(this).css('background-color', 'red');
var postId = $($(this).attr('href'));
var postLocation = postId.offset().top;
$(window).scrollTop(postLocation);
});
$(window).scroll(function() {
var scrollBar = $(this).scrollTop();
var allPosts = [];
var post = $('.content').offset();
var lastPost = allPosts.legnth-1
var windowHeight = $(window).height();
var bottomScroll = windowHeight-scrollBar;
$(".content").each(function(){
allPosts.push($(this).attr('id'));
});
i = 0;
for(i in allPosts){
var currentPost = "#"+allPosts[i];
var postPosition = $(currentPost).offset().top;
if (scrollBar >= postPosition){
$('.option').css('background-color', '#CCCCCC');
$('#nav'+allPosts[i]).css('background-color', 'red');
};
};
});
I think you've overdone your scroll() handler, to keep it simple you just needs to check if the scrollbar/scrollTop reaches the '.contents' offset top value but should not be greater than its offset().top plus its height().
$(window).scroll(function () {
var scrollBar = $(this).scrollTop();
$(".content").each(function (index) {
var elTop = $(this).offset().top;
var elHeight = $(this).height();
if (scrollBar >= elTop - 5 && scrollBar < elTop + elHeight) {
/* $(this) '.content' is the active on the vewport,
get its index to target the corresponding navigation '.option',
like this - $('.Nav li').eq(index)
*/
}
});
});
And you actually don't need to set $(window).scrollTop(postLocation); because of the default <a> tag anchoring on click, you can omit that one and it will work fine. However if you are looking to animate you need first to prevent this default behavior:
$('.option').children('a').click(function (e) {
e.preventDefault();
var postId = $($(this).attr('href'));
var postLocation = postId.offset().top;
$('html, body').animate({scrollTop:postLocation},'slow');
});
See the demo.
What you are trying to implement from scratch, although commendable, has already been done by the nice folks at Bootstrap. It is called a Scrollspy and all you need to do to implement it is include Bootstrap js and css (you also need jquery but you already have that) and make some minor changes to your html.
Scrollspy implementation steps.
And here is a demonstration. Notice only one line of js. :D
$('body').scrollspy({ target: '.navbar-example' });

How to make an image slider in javascript

I am implementing an image slider in javascript/jquery.
The demo should work like this.
http://londatiga.net/tutorials/scrollable/
Anyway I don't won't to rely on jquery.tools.min.js because this lib is out of date (the last update is about 8 months ago ).
I decide to make the js code by me.
When clicking on next or prev button I would like to shift the images on the list of one item/image.
The script shifts the items but the display is quite crappy, because the next items is not displayed.
The list is made of 4 images. At the beginning only the first two images are displayed, then when clicking on the next button I would like to display the second and the third image.
Actually the script shows just the first and the second image even if I click on the next button.
Here is the demo: http://jsfiddle.net/xRQBS/5/
Here is the code (1)
Any hints how should I fix it?
thanks
(1)
/*global jQuery */
(function ($) {
var imgs = [
'https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcSsarNmO4Vdo5QwHfznbyxPmOyiYQ-KmBKUFsgEirvjW6Kbm7tj8w',
'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRfIAfLXj3oK1lso1_0iQploSKsogfJFey3NnR0nSD9AfpWjU7egA',
'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcR1dO4FVDDitdS85aLOCsOpQyHHTysDhD4kHQ749bMtNxaj5GMKnA',
'https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcRAPO77sVu-Xk80S_txagySoTq8gKHgeiS63a9TYtKbPpGYVI5X'
];
var $list = $('.list-images');
var $slider = $('.slider');
var slideImage = function (direction) {
var unit = 150;
var left = parseInt($slider.attr('left'), 10) || 0;
left = (direction === 'prev') ? left - 150 : left + 150;
$slider.css('left', left + 'px');
};
$(function () {
$.each(imgs, function (i, img) {
$list.append($('<li>').append($('<img>').attr('src', img)));
});
$('body').on('click', '.direction', function () {
slideImage($(this).attr('data-tid'));
});
});
}(jQuery));
​
With the animate function:
$slider.animate({'left': left + 'px'}, 1000);
http://jsfiddle.net/xRQBS/6/
I'm assuming that you want the shift to be more of an animation. If so, take a look at jQuery's animate. Something like this:
$slider.animate({left: left + 'px'});
That will give it a sliding effect, which what I'm assuming you want :)

Categories

Resources