JS Being Reset on Events - javascript

I have several animations that run when a portion of the page is in view. For some reason the animation of the percentage bar filling is reset any time another animation is ran resulting in the percentage bar refilling each time. Below is the code for the percentage bar and below that is an example of another animation that is ran when in view. I've narrowed it down to it being the JS causing the issue, hopefully someone can point out whats causing this issue. Any help is appreciated!
Percentage JS:
/* BAR PERCENTAGE */
function isElementVisible($elementToBeChecked)
{
var TopView = $(window).scrollTop();
var BotView = TopView + $(window).height();
var TopElement = $elementToBeChecked.offset().top;
var BotElement = TopElement + $elementToBeChecked.height();
return ((BotElement <= BotView) && (TopElement >= TopView));
}
$(window).scroll(function () {
$( ".bar-percentage" ).each(function() {
$this = $(this);
isOnView = isElementVisible($(this));
if(isOnView && !$(this).hasClass('Starting')){
$(this).addClass('Starting');
startAnimation($(this));
}
});
});
function startAnimation($this) {
$('.bar-percentage[data-percentage]').each(function () {
var progress = $(this);
var percentage = Math.ceil($(this).attr('data-percentage'));
$({countNum: 0}).animate({countNum: percentage}, {
duration: 2000,
easing:'swing',
step: function() {
// What todo on every count
var pct = '';
if(percentage == 0){
pct = Math.floor(this.countNum) + '%';
}else{
pct = Math.floor(this.countNum+1) + '%';
}
progress.text(pct) && progress.siblings().children().css('width',pct);
}
});
});
}
Other Animation Example:
$(window).scroll(function () {
$( "#about-image-1" ).each(function() {
$this = $(this);
isOnView = isElementVisible($(this));
if(isOnView && !$(this).hasClass('fadeIn')){
$(this).addClass('fadeIn');
startAnimation($(this));
}
});
});

Related

Hiding Arrows Based on Horizontal Scroll

I'm struggling to make a tiny change in this horizontal scroll code: http://jsfiddle.net/Lpjj3n1e/
I want to make the right button disappear when you scroll all the way to the right (just like it happens with the left button in the original code).
There should be a quick and easy solution but I haven't been able to find one. Please help me and thank you in advance!
$(function() {
var print = function(msg) {
alert(msg);
};
var setInvisible = function(elem) {
elem.css('visibility', 'hidden');
};
var setVisible = function(elem) {
elem.css('visibility', 'visible');
};
var elem = $("#elem");
var items = elem.children();
// Inserting Buttons
elem.prepend('<div id="right-button" style="visibility: hidden;"><</div>');
elem.append(' <div id="left-button">></div>');
// Inserting Inner
items.wrapAll('<div id="inner" />');
// Inserting Outer
debugger;
elem.find('#inner').wrap('<div id="outer"/>');
var outer = $('#outer');
var updateUI = function() {
var maxWidth = outer.outerWidth(true);
var actualWidth = 0;
$.each($('#inner >'), function(i, item) {
actualWidth += $(item).outerWidth(true);
});
if (actualWidth <= maxWidth) {
setVisible($('#left-button'));
}
};
updateUI();
$('#right-button').click(function() {
var leftPos = outer.scrollLeft();
outer.animate({
scrollLeft: leftPos - 200
}, 800, function() {
debugger;
if ($('#outer').scrollLeft() <= 0) {
setInvisible($('#right-button'));
}
});
});
$('#left-button').click(function() {
setVisible($('#right-button'));
var leftPos = outer.scrollLeft();
outer.animate({
scrollLeft: leftPos + 200
}, 800);
});
$(window).resize(function() {
updateUI();
});
});
The main problem seems to be that on clicking the left button there is no function to check whether the arrow should be removed or not.
To test for this we can use the actualWidth which has already been calculated (but it needs to be made more global so its declaration has moved).
There is another small thing which needs rectification - if the maxWidth is greater than the actualWidth there is no need for the arrows. In the code below therefore setVisible has become setVisibleIfNeeded
Here is the revised JS - the original was taken from the jsfiddle. There is a NOTE beside each alteration.
$(function() {
var print = function(msg) {
alert(msg);
};
var setInvisible = function(elem) {
elem.css('visibility', 'hidden');
};
var setVisibleIfNeeded = function(elem) {
if (actualWidth>maxWidth) {//NOTE we don't want to show the arrows if there is space in the div for everything without the need to scroll
elem.css('visibility', 'visible');
}
};
var elem = $("#elem");
var items = elem.children();
// Inserting Buttons
elem.prepend('<div id="right-button" style="visibility: hidden;"><</div>');
elem.append(' <div id="left-button" style="visibility: hidden;">></div>');//NOTE: visibility set to hidden
// Inserting Inner
items.wrapAll('<div id="inner" />');
// Inserting Outer
debugger;
elem.find('#inner').wrap('<div id="outer"/>');
var outer = $('#outer');
var actualWidth=0;//NOTE the declaration is moved up here from the function it was in
var maxwidth=0;//ditto
var updateUI = function() {
maxWidth = outer.outerWidth(true);
actualWidth = 0;
$.each($('#inner >'), function(i, item) {
actualWidth += $(item).outerWidth(true);
});
setVisibleIfNeeded($('#left-button'));
};
updateUI();
$('#right-button').click(function() {
setVisibleIfNeeded($('#left-button'));//NOTE added
var leftPos = outer.scrollLeft();
outer.animate({
scrollLeft: leftPos - 200
}, 800, function() {
debugger;
if ($('#outer').scrollLeft() <= 0) {
setInvisible($('#right-button'));
}
});
});
$('#left-button').click(function() {
setVisibleIfNeeded($('#right-button'));
var leftPos = outer.scrollLeft();
outer.animate({
scrollLeft: leftPos + 200
}, 800,function() {//NOTE function added here to get rid of left button
if (leftPos>=(actualWidth-400)) {setInvisible($('#left-button'));}
});
});
$(window).resize(function() {
updateUI();
});
});

Unable to combine functions in to one file

I have two functions, one to show a gallery of images and one for a smooth scroll up icon. The problem is when I use them separately, both of them works. But when I put them in the same file only the first one works. I can t figure out the problem. I am using jquery-2.0.3
Here is my Code:
$(function() {
$('.demo li').picEyes();
// Caching the Scroll Top Element
// console.log("function move to top");
var ScrollButton = $("#scroll");
$(window).scroll(function() {
// console.log($(this).scrollTop());
if ($(this).scrollTop() >= 50) {
ScrollButton.show()
} else {
ScrollButton.hide();
}
});
// Click On Button To Scroll To Top Of The Page
ScrollButton.click(function() {
$("html,body").animate({
scrollTop: 0
}, 800);
});
});
the code of picEyes function:
(function($){
$.fn.picEyes = function(){
var $obj = this;
var num,zg = $obj.length - 1;
var win_w = $(window).width();
var win_h = $(window).height();
var eyeHtml = '<div class="picshade"></div>'
+'<a class="pictures_eyes_close" href="javascript:;"></a>'
+'<div class="pictures_eyes">'
+'<div class="pictures_eyes_in">'
+'<img src="" />'
+'<div class="next"></div>'
+'<div class="prev"></div>'
+'</div>'
+'</div>'
+'<div class="pictures_eyes_indicators"></div>';
$('body').append(eyeHtml);
$obj.click(function() {
$(".picshade").css("height", win_h);
var n = $(this).find("img").attr('src');
$(".pictures_eyes img").attr("src", n);
num = $obj.index(this);
popwin($('.pictures_eyes'));
});
$(".pictures_eyes_close,.picshade,.pictures_eyes").click(function() {
$(".picshade,.pictures_eyes,.pictures_eyes_close,.pictures_eyes_indicators").fadeOut();
$('body').css({'overflow':'auto'});
});
$('.pictures_eyes img').click(function(e){
stopPropagation(e);
});
$(".next").click(function(e){
if(num < zg){
num++;
}else{
num = 0;
}
var xx = $obj.eq(num).find('img').attr("src");
$(".pictures_eyes img").attr("src", xx);
stopPropagation(e);
popwin($('.pictures_eyes'));
});
$(".prev").click(function(e){
if(num > 0){
num--;
}else{
num = zg;
}
var xx = $obj.eq(num).find('img').attr("src");
$(".pictures_eyes img").attr("src", xx);
stopPropagation(e);
popwin($('.pictures_eyes'));
});
function popwin(obj){
$('body').css({'overflow':'hidden'});
var Pwidth = obj.width();
var Pheight = obj.height();
obj.css({left:(win_w - Pwidth)/2,top:(win_h - Pheight)/2}).show();
$('.picshade,.pictures_eyes_close').fadeIn();
indicatorsList();
}
function updatePlace(obj){
var Pwidth = obj.width();
var Pheight = obj.height();
obj.css({left:(win_w - Pwidth)/2,top:(win_h - Pheight)/2});
}
function indicatorsList(){
var indHtml = '';
$obj.each(function(){
var img = $(this).find('img').attr('src');
indHtml +='<img src="'+img+'"/>';
});
$('.pictures_eyes_indicators').html(indHtml).fadeIn();
$('.pictures_eyes_indicators a').eq(num).addClass('current').siblings().removeClass('current');
$('.pictures_eyes_indicators a').click(function(){
$(this).addClass('current').siblings().removeClass('current');
var xx = $(this).find('img').attr("src");
$(".pictures_eyes img").attr("src", xx);
updatePlace($('.pictures_eyes'));
});
}
function stopPropagation(e) {
e = e || window.event;
if(e.stopPropagation) {
e.stopPropagation();
} else {
e.cancelBubble = true;
}
}
}
})(jQuery);
You should add click event handler, when DOM will be ready, do like this:-
$(function () {
$('.demo li').picEyes();
// Caching the Scroll Top Element
// console.log("function move to top");
//var ScrollButton =ScrollButton.click
var ScrollButton = $("#scroll")
$(window).scroll(function () {
// console.log($(this).scrollTop());
if ($(this).scrollTop() >= 50) {
ScrollButton.show()
} else {
ScrollButton.hide();
}
});
// Click On Button To Scroll To Top Of The Page
ScrollButton.click(function () {
$("html,body").animate({
scrollTop: 0
}, 800);
});
});
I bet both scripts have own ScrollButton element, and while gallery is loaded it owerwrites behaviour of other ScrollButton element.
I put the call of picEyes function outside of the main function and somehow worked !

jQuery click mobile problems (slider)

I have coded a small script for scrolling in a vertical gallery on mobile devices – in browser everything works fine, but I can't make it work on my smartphone. What am I doing wrong?
Thats my query:
jQuery( '.single-cinema-cat .next' ).on('click touchstart', function () {
alert("The btn was clicked.");
if( jQuery( this ).hasClass( 'disabled' ) )
return;
jQuery( this ).addClass( 'disabled' );
var $el = jQuery( this );
if( jQuery( window ).innerWidth() >= 970 )
scrollVertical_next( $el );
else
scrollHorizontal_next( $el );
});
the click element is a span-element in my html markup – could this be a problem? screenshot of my markup: https://picload.org/image/ralwaarg/jquerymobile.png
please save me for further headaches :-)
scrollVertical_next
function scrollVertical_next($el) {
var $wrapper = $el.closest('.single-cinema-cat').find('.inner');
var margin = parseInt($wrapper.find('article').css('margin-bottom')) + parseInt($wrapper.find('article').css('margin-top'));
var current_height = parseInt($wrapper.find('ul').css('top'));
var single_height = $wrapper.find('article').outerHeight() + margin;
var target_height = current_height - single_height;
var total_height = $wrapper.find('ul').innerHeight();
var stopper_height = -1 * total_height + 4 * single_height;
if (target_height < stopper_height)
return;
$wrapper.find('ul').animate({
'top': target_height + 'px'
}, 250, 'swing', function() {
if (target_height > stopper_height)
$el.removeClass('disabled');
$el.closest('.single-cinema-cat').find('.prev').removeClass('disabled');
});
}
scrollHorizontal_next
function scrollHorizontal_next($el) {
var $wrapper = $el.closest('.single-cinema-cat').find('.inner');
var margin = parseInt($wrapper.find('article').css('margin-bottom')) + parseInt($wrapper.find('article').css('margin-top'));
var current_height = parseInt($wrapper.find('ul').css('top'));
var single_height = $wrapper.find('article').outerHeight() + margin;
var target_height = current_height - single_height;
var total_height = $wrapper.find('ul').innerHeight();
var stopper_height = -1 * total_height + 1 * single_height;
if (target_height < stopper_height)
return;
$wrapper.find('ul').animate({
'top': target_height + 'px'
}, 250, 'swing', function() {
if (target_height > stopper_height)
$el.removeClass('disabled');
$el.closest('.single-cinema-cat').find('.prev').removeClass('disabled');
});
}
Touch event must be handled this way
jQuery('.single-cinema-cat .next').on('click touchstart', function (event) {
event.stopPropagation();
event.preventDefault();
if (event.handled !== true) {
////////// your stuff //////////////////////////
alert("The btn was clicked.");
if (jQuery(this).hasClass('disabled'))
return;
jQuery(this).addClass('disabled');
var $el = jQuery(this);
if (jQuery(window).innerWidth() >= 970)
scrollVertical_next($el);
else
scrollHorizontal_next($el);
////////////////////////////////////////////////////
event.handled = true;
} else {
return false;
}
});

jQuery slider doesn't rotate

I have a slider rotator on my site but it doesn't rotate items automatically in the boxes - navigation works and rotate but I want it to rotate automatically, right after I enter the site.
This is my js:
$(document).ready(function() {
var nbr = 0;
$('.slider').each(function() {
var slider = $(this);
//get width and height of the wrapper and give it to the UL
var wrapperwidth = $(slider).width() * $(slider).find('ul > li').size();
$(slider).find('ul').css('width', wrapperwidth);
var wrapperheight = $(slider).height();
$(slider).find('ul').css('height', wrapperheight);
//set my li width
var width = $(slider).width();
$(slider).find('ul li').css('width', width);
//set my counter vars
var counter = $(slider).find('ul > li').size();
var decount = 1;
var autocount = 1;
if (counter > 1) {
//create my number navigation
var createNum = 1;
$(slider).after('<ul class="numbers"><li></li></ul>');
var numbers = $(slider).parent().find('.numbers');
$(numbers).find('li:first-child').html(createNum+'_'+nbr).addClass('activenum').attr('id', 'id1_'+nbr);
while ( createNum != counter) {
createNum++;
$(numbers).append("<li id='id"+createNum+"_"+nbr+"'>"+createNum+"_"+nbr+"</li>");
}
//get my number-width (number navigation should always be centered)
var numwidth = $(slider).find('.numbers li:first-child').width() * $(slider).find('.numbers li').size();
$(slider).find('.numbers').css('width', numwidth);
}
nbr++;
});
//make the number clickable
$(".numbers li").click(function() {
var slider = $(this).closest('.sliderWrapper');
var slider0 = $(slider).find('.slider');
var clickednum = $(this).html().split('_')[0] * - $(slider0).width() + $(slider0).width();
$(slider0).find('ul').animate({ left: clickednum }, 400, 'swing', function() { });
$(slider).find('.activenum').removeClass('activenum');
$(this).addClass('activenum');
decount = $(this).html();
});
rotateSwitch = function(sliderW, speed) {
var sliderWrap = sliderW;
play = setInterval(function() {
var nextNum = parseInt($($(sliderWrap).find(".numbers li.activenum")).html().split('_')[0])+1;
if (nextNum > $(sliderWrap).find(".numbers li").length) {
nextNum = 1;
}
//console.log("nextnum: "+nextNum+", numbers length: "+$(sliderWrap).find(".numbers li").length);
$(sliderWrap).find(".numbers li").each(function() {
if( parseInt($(this).html().split('_')[0]) == nextNum )
$(this).click();
});
}, speed);
};
makeAutoSlide = function(sliderWrap, speed) {
if ($(sliderWrap).length > 0 && $(sliderWrap).find(".numbers li").length > 1) {
rotateSwitch(sliderWrap, speed);
$(sliderWrap).find(".slider li").hover(function() {
if ($(sliderWrap).find(".numbers li").length > 1) {
clearInterval(play); //Stop the rotation
}
}, function() {
if ($(sliderWrap).find(".numbers li").length > 1) {
rotateSwitch(sliderWrap, speed); //Resume rotation timer
}
});
}
};
});
I'm not really sure if this is a problem with setInterval and clearInterval or I wrote something wrong.
I put code in jsFiddle, so you know how the structure looks like.
http://jsfiddle.net/gecbjerd/1/
I appreciate for help.
Cheers

.next() not working as intended

So,
if($(this).hasClass('active')){
$(this).removeClass('active');
$(this).prev().addClass('active');
}
works fine, it adds the class "active" to this previous div of the same kind.
if($(this).hasClass('active')){
$(this).removeClass('active');
$(this).next().addClass('active');
}
However, adds the class to the next div (as i intend for it to do) for about 0.5 of a second BUT then removes it.
Here's ALL of the jQuery (as per your comments below) - Please do not comment on my horrible code organization
$(window).load(function () {
// Initial variables
var numberSlides = 0;
var currentSlide = 1;
var ready = true;
var pageWidthR = $(document).width() - 352;
var pageWidthL = $(document).width() - 352;
// Update number of slides by number of .slide elements
$('#features-slider .slide').each(function () {
numberSlides++;
});
// Go through each slide and move it to the left of the screen
var i = 0;
$($('#features-slider .slide').get().reverse()).each(function () {
if (i == 0) {
} else {
var newWidth = i * 115;
$(this).css('left', '-' + newWidth + '%');
}
i++;
});
// Animate the first slide in
$('#features-slider .slide:last-child').addClass('active').animate({
left: 0
}, 1500);
// Remove the loading message
$('#loading').fadeOut(1000, function () {
$('#loading').remove();
// Now that we're done - we can show it
$('#features-slider').show();
});
/***** Left and Right buttons *****/
/* Right */
$('#rightbutton').click(function () {
var numberSlides = 0;
$('#features-slider .slide').each(function () {
numberSlides++;
});
var index = $('.slide.active').index() + 1;
if (!$('.slide').is(':animated') && index != 1) {
$('#features-slider .slide').each(function () {
if ($(this).hasClass('active')) {
var currentLeft = $(this).css('left');
var newLeft = parseInt(currentLeft) + 115;
} else {
var currentLeft = $(this).css('left');
var newLeft = parseInt(currentLeft) + 115;
}
$(this).animate({
left: newLeft + '%'
}, 1500);
if ($(this).hasClass('active')) {
$(this).removeClass('active');
$(this).prev().addClass('active');
}
});
}
});
/* Left */
$('#leftbutton').click(function () {
var numberSlides = 0;
$('#features-slider .slide').each(function () {
numberSlides++;
});
var index = $('.slide.active').index() + 1;
if (!$('.slide').is(':animated') && index != numberSlides) {
$('#features-slider .slide').each(function () {
if ($(this).hasClass('active')) {
var currentLeft = $(this).css('left');
var newLeft = parseInt(currentLeft) - 115;
} else {
var currentLeft = $(this).css('left');
var newLeft = parseInt(currentLeft) - 115;
}
$(this).animate({
left: newLeft + '%'
}, 1500);
if ($(this).hasClass('active')) {
$(this).next().addClass('active');
$(this).removeClass('active').not($(this).next());
}
});
}
});
});
$(document).ready(function () {
// Hide the slider and show a loading message while we do stuff and the images / DOM loads - Also disable overflow on the body so no horizontal scrollbar is shown
$('body').css('overflow-x', 'hidden');
$('#features-slider').hide();
$('#loading').html('<center> <img id="loader" src="/wp-content/themes/responsive/library/images/ajax-loader.gif" /> Loading</center>');
});
RESOLVED
New left button function :
$('#leftbutton').click(function(){
var numberSlides = 0;
$('#features-slider .slide').each(function(){
numberSlides++;
});
var index = $('.slide.active').index()+1;
if( !$('.slide').is(':animated') && index != numberSlides ){
var done = false;
$('#features-slider .slide').each(function(){
if($(this).hasClass('active')){
var currentLeft = $(this).css('left');
var newLeft = parseInt(currentLeft)-115;
} else {
var currentLeft = $(this).css('left');
var newLeft = parseInt(currentLeft)-115;
}
$(this).animate({left: newLeft+'%'}, 1500);
if($(this).hasClass('active') && done == false){
$(this).next().addClass('active');
$(this).removeClass('active');
done = true;
}
});
});
If you're iterating forward through the elements, then it should be clear what's going on - you add the "active" class to the next element, and then the next iteration takes it away.
This is just a guess however as you did not post enough code for me (or anybody else) to be sure.
edit — ok now that you've updated the question, it's clear that the guess was correct. The .each() function will iterate forward through the elements. When an element has the "active" class, and the code removes it and adds it to the next element, then on the next iteration the work is undone.
Since you are referencing this and by the behavior you're describing, you are likely iterating a loop for a list of elements. As a result, you are completing the action you want but the next iteration is removing the previous changes due to your usage of removing a class and then adding the class back.
As it stands now, your code does not illustrate how this occurence can be happening.
Update:
As suspected, you seem to be looping as signified by: each(function(){. While iterating through your objects the class is being pushed forward and is not acting as desired. You are stating add the class to the next element, but remove it from the current element, and this behavior continues through your iteration.
On a side note, update your code to call removeClass() on the current object first, before adding it to the next object:
if ($(this).hasClass('active')) {
$(this).removeClass('active').next().addClass('active');
}

Categories