Start stop function on scroll event within if/else statement - javascript

I have a script which animates a headline.
I am trying to make this script fire on page load, but if a user scrolls more than 200px, I'd like this function to stop.
Below is my animated headline script, and also my scroll/if else statement. This should fire the wordAnimate() function on page load, but stop if user scrolls more than 200px. There is also some classes being added and removed conditionally in the scroll for a sticky navbar that appears after the 200px scroll.
JS:
$(document).scroll(function() {
var scroll = $(this).scrollTop();
return (scroll < 200) && $(window).wordAnimate();
if (scroll >= 200) {
$('.logo').removeClass('transparent').addClass('opaque');
}
else {
$('.logo').removeClass('opaque').addClass('transparent');
}
});
animate-headline.js:
function wordAnimate() {
//set animation timing
var animationDelay = 2500,
//loading bar effect
barAnimationDelay = 3800,
barWaiting = barAnimationDelay - 1000, //3000 is the duration of the transition on the loading bar - set in the scss/css file
//letters effect
lettersDelay = 50,
//type effect
typeLettersDelay = 150,
selectionDuration = 500,
typeAnimationDelay = selectionDuration + 800,
//clip effect
revealDuration = 600,
revealAnimationDelay = 1500;
initHeadline();
function initHeadline() {
//insert <i> element for each letter of a changing word
singleLetters($('.cd-headline.letters').find('b'));
//initialise headline animation
animateHeadline($('.cd-headline'));
}
function singleLetters($words) {
$words.each(function(){
var word = $(this),
letters = word.text().split(''),
selected = word.hasClass('is-visible');
for (i in letters) {
if(word.parents('.rotate-2').length > 0) letters[i] = '<em>' + letters[i] + '</em>';
letters[i] = (selected) ? '<i class="in">' + letters[i] + '</i>': '<i>' + letters[i] + '</i>';
}
var newLetters = letters.join('');
word.html(newLetters).css('opacity', 1);
});
}
function animateHeadline($headlines) {
var duration = animationDelay;
$headlines.each(function(){
var headline = $(this);
if(headline.hasClass('loading-bar')) {
duration = barAnimationDelay;
setTimeout(function(){ headline.find('.cd-words-wrapper').addClass('is-loading') }, barWaiting);
} else if (headline.hasClass('clip')){
var spanWrapper = headline.find('.cd-words-wrapper'),
newWidth = spanWrapper.width() + 10
spanWrapper.css('width', newWidth);
} else if (!headline.hasClass('type') ) {
//assign to .cd-words-wrapper the width of its longest word
var words = headline.find('.cd-words-wrapper b'),
width = 0;
words.each(function(){
var wordWidth = $(this).width();
if (wordWidth > width) width = wordWidth;
});
headline.find('.cd-words-wrapper').css('width', width);
};
//trigger animation
setTimeout(function(){ hideWord( headline.find('.is-visible').eq(0) ) }, duration);
});
}
function hideWord($word) {
var nextWord = takeNext($word);
if($word.parents('.cd-headline').hasClass('type')) {
var parentSpan = $word.parent('.cd-words-wrapper');
parentSpan.addClass('selected').removeClass('waiting');
setTimeout(function(){
parentSpan.removeClass('selected');
$word.removeClass('is-visible').addClass('is-hidden').children('i').removeClass('in').addClass('out');
}, selectionDuration);
setTimeout(function(){ showWord(nextWord, typeLettersDelay) }, typeAnimationDelay);
} else if($word.parents('.cd-headline').hasClass('letters')) {
var bool = ($word.children('i').length >= nextWord.children('i').length) ? true : false;
hideLetter($word.find('i').eq(0), $word, bool, lettersDelay);
showLetter(nextWord.find('i').eq(0), nextWord, bool, lettersDelay);
} else if($word.parents('.cd-headline').hasClass('clip')) {
$word.parents('.cd-words-wrapper').animate({ width : '2px' }, revealDuration, function(){
switchWord($word, nextWord);
showWord(nextWord);
});
} else if ($word.parents('.cd-headline').hasClass('loading-bar')){
$word.parents('.cd-words-wrapper').removeClass('is-loading');
switchWord($word, nextWord);
setTimeout(function(){ hideWord(nextWord) }, barAnimationDelay);
setTimeout(function(){ $word.parents('.cd-words-wrapper').addClass('is-loading') }, barWaiting);
} else {
switchWord($word, nextWord);
setTimeout(function(){ hideWord(nextWord) }, animationDelay);
}
}
function showWord($word, $duration) {
if($word.parents('.cd-headline').hasClass('type')) {
showLetter($word.find('i').eq(0), $word, false, $duration);
$word.addClass('is-visible').removeClass('is-hidden');
} else if($word.parents('.cd-headline').hasClass('clip')) {
$word.parents('.cd-words-wrapper').animate({ 'width' : $word.width() + 10 }, revealDuration, function(){
setTimeout(function(){ hideWord($word) }, revealAnimationDelay);
});
}
}
function hideLetter($letter, $word, $bool, $duration) {
$letter.removeClass('in').addClass('out');
if(!$letter.is(':last-child')) {
setTimeout(function(){ hideLetter($letter.next(), $word, $bool, $duration); }, $duration);
} else if($bool) {
setTimeout(function(){ hideWord(takeNext($word)) }, animationDelay);
}
if($letter.is(':last-child') && $('html').hasClass('no-csstransitions')) {
var nextWord = takeNext($word);
switchWord($word, nextWord);
}
}
function showLetter($letter, $word, $bool, $duration) {
$letter.addClass('in').removeClass('out');
if(!$letter.is(':last-child')) {
setTimeout(function(){ showLetter($letter.next(), $word, $bool, $duration); }, $duration);
} else {
if($word.parents('.cd-headline').hasClass('type')) { setTimeout(function(){ $word.parents('.cd-words-wrapper').addClass('waiting'); }, 200);}
if(!$bool) { setTimeout(function(){ hideWord($word) }, animationDelay) }
}
}
function takeNext($word) {
return (!$word.is(':last-child')) ? $word.next() : $word.parent().children().eq(0);
}
function takePrev($word) {
return (!$word.is(':first-child')) ? $word.prev() : $word.parent().children().last();
}
function switchWord($oldWord, $newWord) {
$oldWord.removeClass('is-visible').addClass('is-hidden');
$newWord.removeClass('is-hidden').addClass('is-visible');
}
}
What is a better way to do this?
Currently myFunction won't fire unless I call it from the debugger in the browser dev tools.
UPDATE:
Problem solved by adding a stopAnimating() and restartAnimating() function to the large, animated headline script. This way we can call those specific functions from within the scroll if/else.
JS:
$(window).scroll(function() {
var scroll = $(this).scrollTop();
if (scroll >= 200) {
$('.nav-wrapper').removeClass('transparent').addClass('opaque');
stopAnimating();
}
else {
$('.nav-wrapper').removeClass('opaque').addClass('transparent');
restartAnimating();
}
});
animate-headline.js:
//set animation timing
var stop
var animationDelay = 2500,
//loading bar effect
barAnimationDelay = 3800,
barWaiting = barAnimationDelay - 1000, //3000 is the duration of the transition on the loading bar - set in the scss/css file
//letters effect
lettersDelay = 50,
//type effect
typeLettersDelay = 150,
selectionDuration = 500,
typeAnimationDelay = selectionDuration + 800,
//clip effect
revealDuration = 600,
revealAnimationDelay = 1500;
initHeadline();
function initHeadline() {
//insert <i> element for each letter of a changing word
singleLetters($('.cd-headline.letters').find('b'));
//initialise headline animation
animateHeadline($('.cd-headline'));
stop = false;
}
function stopAnimating() {
stop = true;
}
function restartAnimating() {
stop = false;
}
function singleLetters($words) {
$words.each(function(){
var word = $(this),
letters = word.text().split(''),
selected = word.hasClass('is-visible');
for (i in letters) {
if(word.parents('.rotate-2').length > 0) letters[i] = '<em>' + letters[i] + '</em>';
letters[i] = (selected) ? '<i class="in">' + letters[i] + '</i>': '<i>' + letters[i] + '</i>';
}
var newLetters = letters.join('');
word.html(newLetters).css('opacity', 1);
});
}
function animateHeadline($headlines) {
var duration = animationDelay;
$headlines.each(function(){
var headline = $(this);
if(headline.hasClass('loading-bar')) {
duration = barAnimationDelay;
setTimeout(function(){ headline.find('.cd-words-wrapper').addClass('is-loading') }, barWaiting);
} else if (headline.hasClass('clip')){
var spanWrapper = headline.find('.cd-words-wrapper'),
newWidth = spanWrapper.width() + 10
spanWrapper.css('width', newWidth);
} else if (!headline.hasClass('type') ) {
//assign to .cd-words-wrapper the width of its longest word
var words = headline.find('.cd-words-wrapper b'),
width = 0;
words.each(function(){
var wordWidth = $(this).width();
if (wordWidth > width) width = wordWidth;
});
headline.find('.cd-words-wrapper').css('width', width);
};
//trigger animation
setTimeout(function(){ hideWord( headline.find('.is-visible').eq(0) ) }, duration);
});
}
function hideWord($word) {
var nextWord = takeNext($word);
if($word.parents('.cd-headline').hasClass('type')) {
var parentSpan = $word.parent('.cd-words-wrapper');
parentSpan.addClass('selected').removeClass('waiting');
setTimeout(function(){
parentSpan.removeClass('selected');
$word.removeClass('is-visible').addClass('is-hidden').children('i').removeClass('in').addClass('out');
}, selectionDuration);
setTimeout(function(){ showWord(nextWord, typeLettersDelay) }, typeAnimationDelay);
} else if($word.parents('.cd-headline').hasClass('letters')) {
var bool = ($word.children('i').length >= nextWord.children('i').length) ? true : false;
hideLetter($word.find('i').eq(0), $word, bool, lettersDelay);
showLetter(nextWord.find('i').eq(0), nextWord, bool, lettersDelay);
} else if($word.parents('.cd-headline').hasClass('clip')) {
$word.parents('.cd-words-wrapper').animate({ width : '2px' }, revealDuration, function(){
switchWord($word, nextWord);
showWord(nextWord);
});
} else if ($word.parents('.cd-headline').hasClass('loading-bar')){
$word.parents('.cd-words-wrapper').removeClass('is-loading');
switchWord($word, nextWord);
setTimeout(function(){ hideWord(nextWord) }, barAnimationDelay);
setTimeout(function(){ $word.parents('.cd-words-wrapper').addClass('is-loading') }, barWaiting);
} else {
switchWord($word, nextWord);
setTimeout(function(){ hideWord(nextWord) }, animationDelay);
}
}
function showWord($word, $duration) {
if($word.parents('.cd-headline').hasClass('type')) {
showLetter($word.find('i').eq(0), $word, false, $duration);
$word.addClass('is-visible').removeClass('is-hidden');
} else if($word.parents('.cd-headline').hasClass('clip')) {
$word.parents('.cd-words-wrapper').animate({ 'width' : $word.width() + 10 }, revealDuration, function(){
setTimeout(function(){ hideWord($word) }, revealAnimationDelay);
});
}
}
function hideLetter($letter, $word, $bool, $duration) {
$letter.removeClass('in').addClass('out');
if(!$letter.is(':last-child')) {
setTimeout(function(){ hideLetter($letter.next(), $word, $bool, $duration); }, $duration);
} else if($bool) {
setTimeout(function(){ hideWord(takeNext($word)) }, animationDelay);
}
if($letter.is(':last-child') && $('html').hasClass('no-csstransitions')) {
var nextWord = takeNext($word);
switchWord($word, nextWord);
}
}
function showLetter($letter, $word, $bool, $duration) {
$letter.addClass('in').removeClass('out');
if(!$letter.is(':last-child')) {
setTimeout(function(){ showLetter($letter.next(), $word, $bool, $duration); }, $duration);
} else {
if($word.parents('.cd-headline').hasClass('type')) { setTimeout(function(){ $word.parents('.cd-words-wrapper').addClass('waiting'); }, 200);}
if(!$bool) { setTimeout(function(){ hideWord($word) }, animationDelay) }
}
}
function takeNext($word) {
if(stop == true) {
return $word.parent().children().eq(0);
}
else {
return (!$word.is(':last-child')) ? $word.next() : $word.parent().children().eq(0);
}
}
function takePrev($word) {
return (!$word.is(':first-child')) ? $word.prev() : $word.parent().children().last();
}
function switchWord($oldWord, $newWord) {
$oldWord.removeClass('is-visible').addClass('is-hidden');
$newWord.removeClass('is-hidden').addClass('is-visible');
}

Here's a way:
$(window).scroll(function() {
return ($(this).scrollTop() < 200) && $(window).myFunction();
});
The function will only execute under 200px scrollTop position.
JS Fiddle Demo
Edit Updated with your code:
$(document).scroll(function() {
var scroll = $(this).scrollTop();
return ( scroll < 200
&& $(window).wordAnimate()
&& $('.logo').removeClass('opaque').addClass('transparent')
)
|| $('.logo').removeClass('transparent').addClass('opaque');
});

Related

Commenting out JS gives dev console error?

I'm trying to comment out a block of code in my site's main.js file, since it makes my sticky header jump in a funny way upon scrolling.
When I comment out the sticky header section, it fixes the jumpy header issue.
However, it also throws the following error in Firefox or Chrome developer console:
Uncaught ReferenceError: jQuery is not defined
Here is the original unedited code:
jQuery(function ($) {
// Sticky Header
if ($('body').hasClass('sticky-header')) {
var header = $('#sp-header');
if($('#sp-header').length) {
var headerHeight = header.outerHeight();
var stickyHeaderTop = header.offset().top;
var stickyHeader = function () {
var scrollTop = $(window).scrollTop();
if (scrollTop > stickyHeaderTop) {
header.addClass('header-sticky');
} else {
if (header.hasClass('header-sticky')) {
header.removeClass('header-sticky');
}
}
};
stickyHeader();
$(window).scroll(function () {
stickyHeader();
});
}
if ($('body').hasClass('layout-boxed')) {
var windowWidth = header.parent().outerWidth();
header.css({"max-width": windowWidth, "left": "auto"});
}
}
// go to top
$(window).scroll(function () {
if ($(this).scrollTop() > 100) {
$('.sp-scroll-up').fadeIn();
} else {
$('.sp-scroll-up').fadeOut(400);
}
});
$('.sp-scroll-up').click(function () {
$("html, body").animate({
scrollTop: 0
}, 600);
return false;
});
// Preloader
$(window).on('load', function () {
$('.sp-preloader').fadeOut(500, function() {
$(this).remove();
});
});
//mega menu
$('.sp-megamenu-wrapper').parent().parent().css('position', 'static').parent().css('position', 'relative');
$('.sp-menu-full').each(function () {
$(this).parent().addClass('menu-justify');
});
// Offcanvs
$('#offcanvas-toggler').on('click', function (event) {
event.preventDefault();
$('.offcanvas-init').addClass('offcanvas-active');
});
$('.close-offcanvas, .offcanvas-overlay').on('click', function (event) {
event.preventDefault();
$('.offcanvas-init').removeClass('offcanvas-active');
});
$(document).on('click', '.offcanvas-inner .menu-toggler', function(event){
event.preventDefault();
$(this).closest('.menu-parent').toggleClass('menu-parent-open').find('>.menu-child').slideToggle(400);
});
//Tooltip
$('[data-toggle="tooltip"]').tooltip();
// Article Ajax voting
$('.article-ratings .rating-star').on('click', function (event) {
event.preventDefault();
var $parent = $(this).closest('.article-ratings');
var request = {
'option': 'com_ajax',
'template': template,
'action': 'rating',
'rating': $(this).data('number'),
'article_id': $parent.data('id'),
'format': 'json'
};
$.ajax({
type: 'POST',
data: request,
beforeSend: function () {
$parent.find('.fa-spinner').show();
},
success: function (response) {
var data = $.parseJSON(response);
$parent.find('.ratings-count').text(data.message);
$parent.find('.fa-spinner').hide();
if(data.status)
{
$parent.find('.rating-symbol').html(data.ratings)
}
setTimeout(function(){
$parent.find('.ratings-count').text('(' + data.rating_count + ')')
}, 3000);
}
});
});
// Cookie consent
$('.sp-cookie-allow').on('click', function(event) {
event.preventDefault();
var date = new Date();
date.setTime(date.getTime() + (30 * 24 * 60 * 60 * 1000));
var expires = "; expires=" + date.toGMTString();
document.cookie = "spcookie_status=ok" + expires + "; path=/";
$(this).closest('.sp-cookie-consent').fadeOut();
});
$(".btn-group label:not(.active)").click(function()
{
var label = $(this);
var input = $('#' + label.attr('for'));
if (!input.prop('checked')) {
label.closest('.btn-group').find("label").removeClass('active btn-success btn-danger btn-primary');
if (input.val() === '') {
label.addClass('active btn-primary');
} else if (input.val() == 0) {
label.addClass('active btn-danger');
} else {
label.addClass('active btn-success');
}
input.prop('checked', true);
input.trigger('change');
}
var parent = $(this).parents('#attrib-helix_ultimate_blog_options');
if( parent ){
showCategoryItems( parent, input.val() )
}
});
$(".btn-group input[checked=checked]").each(function()
{
if ($(this).val() == '') {
$("label[for=" + $(this).attr('id') + "]").addClass('active btn btn-primary');
} else if ($(this).val() == 0) {
$("label[for=" + $(this).attr('id') + "]").addClass('active btn btn-danger');
} else {
$("label[for=" + $(this).attr('id') + "]").addClass('active btn btn-success');
}
var parent = $(this).parents('#attrib-helix_ultimate_blog_options');
if( parent ){
parent.find('*[data-showon]').each( function() {
$(this).hide();
})
}
});
function showCategoryItems(parent, value){
var controlGroup = parent.find('*[data-showon]');
controlGroup.each( function() {
var data = $(this).attr('data-showon')
data = typeof data !== 'undefined' ? JSON.parse( data ) : []
if( data.length > 0 ){
if(typeof data[0].values !== 'undefined' && data[0].values.includes( value )){
$(this).slideDown();
}else{
$(this).hide();
}
}
})
}
$(window).on('scroll', function(){
var scrollBar = $(".sp-reading-progress-bar");
if( scrollBar.length > 0 ){
var s = $(window).scrollTop(),
d = $(document).height(),
c = $(window).height();
var scrollPercent = (s / (d - c)) * 100;
const postition = scrollBar.data('position')
if( postition === 'top' ){
// var sticky = $('.header-sticky');
// if( sticky.length > 0 ){
// sticky.css({ top: scrollBar.height() })
// }else{
// sticky.css({ top: 0 })
// }
}
scrollBar.css({width: `${scrollPercent}%` })
}
})
});
The portion I want to comment out is just the "sticky header" block.
I tried to do so like this:
jQuery(function ($) {
// Sticky Header
/* if ($('body').hasClass('sticky-header')) {
var header = $('#sp-header');
if($('#sp-header').length) {
var headerHeight = header.outerHeight();
var stickyHeaderTop = header.offset().top;
var stickyHeader = function () {
var scrollTop = $(window).scrollTop();
if (scrollTop > stickyHeaderTop) {
header.addClass('header-sticky');
} else {
if (header.hasClass('header-sticky')) {
header.removeClass('header-sticky');
}
}
};
stickyHeader();
$(window).scroll(function () {
stickyHeader();
});
}
if ($('body').hasClass('layout-boxed')) {
var windowWidth = header.parent().outerWidth();
header.css({"max-width": windowWidth, "left": "auto"});
}
}
*/
// go to top
$(window).scroll(function () {
if ($(this).scrollTop() > 100) {
$('.sp-scroll-up').fadeIn();
} else {
$('.sp-scroll-up').fadeOut(400);
}
});
$('.sp-scroll-up').click(function () {
$("html, body").animate({
scrollTop: 0
}, 600);
return false;
});
// Preloader
$(window).on('load', function () {
$('.sp-preloader').fadeOut(500, function() {
$(this).remove();
});
});
//mega menu
$('.sp-megamenu-wrapper').parent().parent().css('position', 'static').parent().css('position', 'relative');
$('.sp-menu-full').each(function () {
$(this).parent().addClass('menu-justify');
});
// Offcanvs
$('#offcanvas-toggler').on('click', function (event) {
event.preventDefault();
$('.offcanvas-init').addClass('offcanvas-active');
});
$('.close-offcanvas, .offcanvas-overlay').on('click', function (event) {
event.preventDefault();
$('.offcanvas-init').removeClass('offcanvas-active');
});
$(document).on('click', '.offcanvas-inner .menu-toggler', function(event){
event.preventDefault();
$(this).closest('.menu-parent').toggleClass('menu-parent-open').find('>.menu-child').slideToggle(400);
});
//Tooltip
$('[data-toggle="tooltip"]').tooltip();
// Article Ajax voting
$('.article-ratings .rating-star').on('click', function (event) {
event.preventDefault();
var $parent = $(this).closest('.article-ratings');
var request = {
'option': 'com_ajax',
'template': template,
'action': 'rating',
'rating': $(this).data('number'),
'article_id': $parent.data('id'),
'format': 'json'
};
$.ajax({
type: 'POST',
data: request,
beforeSend: function () {
$parent.find('.fa-spinner').show();
},
success: function (response) {
var data = $.parseJSON(response);
$parent.find('.ratings-count').text(data.message);
$parent.find('.fa-spinner').hide();
if(data.status)
{
$parent.find('.rating-symbol').html(data.ratings)
}
setTimeout(function(){
$parent.find('.ratings-count').text('(' + data.rating_count + ')')
}, 3000);
}
});
});
// Cookie consent
$('.sp-cookie-allow').on('click', function(event) {
event.preventDefault();
var date = new Date();
date.setTime(date.getTime() + (30 * 24 * 60 * 60 * 1000));
var expires = "; expires=" + date.toGMTString();
document.cookie = "spcookie_status=ok" + expires + "; path=/";
$(this).closest('.sp-cookie-consent').fadeOut();
});
$(".btn-group label:not(.active)").click(function()
{
var label = $(this);
var input = $('#' + label.attr('for'));
if (!input.prop('checked')) {
label.closest('.btn-group').find("label").removeClass('active btn-success btn-danger btn-primary');
if (input.val() === '') {
label.addClass('active btn-primary');
} else if (input.val() == 0) {
label.addClass('active btn-danger');
} else {
label.addClass('active btn-success');
}
input.prop('checked', true);
input.trigger('change');
}
var parent = $(this).parents('#attrib-helix_ultimate_blog_options');
if( parent ){
showCategoryItems( parent, input.val() )
}
});
$(".btn-group input[checked=checked]").each(function()
{
if ($(this).val() == '') {
$("label[for=" + $(this).attr('id') + "]").addClass('active btn btn-primary');
} else if ($(this).val() == 0) {
$("label[for=" + $(this).attr('id') + "]").addClass('active btn btn-danger');
} else {
$("label[for=" + $(this).attr('id') + "]").addClass('active btn btn-success');
}
var parent = $(this).parents('#attrib-helix_ultimate_blog_options');
if( parent ){
parent.find('*[data-showon]').each( function() {
$(this).hide();
})
}
});
function showCategoryItems(parent, value){
var controlGroup = parent.find('*[data-showon]');
controlGroup.each( function() {
var data = $(this).attr('data-showon')
data = typeof data !== 'undefined' ? JSON.parse( data ) : []
if( data.length > 0 ){
if(typeof data[0].values !== 'undefined' && data[0].values.includes( value )){
$(this).slideDown();
}else{
$(this).hide();
}
}
})
}
$(window).on('scroll', function(){
var scrollBar = $(".sp-reading-progress-bar");
if( scrollBar.length > 0 ){
var s = $(window).scrollTop(),
d = $(document).height(),
c = $(window).height();
var scrollPercent = (s / (d - c)) * 100;
const postition = scrollBar.data('position')
if( postition === 'top' ){
// var sticky = $('.header-sticky');
// if( sticky.length > 0 ){
// sticky.css({ top: scrollBar.height() })
// }else{
// sticky.css({ top: 0 })
// }
}
scrollBar.css({width: `${scrollPercent}%` })
}
})
});
This is effectively commenting out the section and fixing the header bug, but it's also throwing the jQuery not defined error. Is there a more appropriate method for commenting out the section?
Note that the same error occurs if I simply delete the entire sticky header block.
Thank you from a newbie for any help!
Simply try single line comments for each line in the code block. If you have VS Code or similar IDE, then it should do it for you. Select all the lines and press CTRL + / or CMD + / (Mac).
// if ($('body').hasClass('sticky-header')) {
// var header = $('#sp-header');
// if($('#sp-header').length) {
// var headerHeight = header.outerHeight();
// var stickyHeaderTop = header.offset().top;
// var stickyHeader = function () {
// var scrollTop = $(window).scrollTop();
// if (scrollTop > stickyHeaderTop) {
// header.addClass('header-sticky');
// } else {
// if (header.hasClass('header-sticky')) {
// header.removeClass('header-sticky');
// }
// }
// };
// stickyHeader();
// $(window).scroll(function () {
// stickyHeader();
// });
// }
// if ($('body').hasClass('layout-boxed')) {
// var windowWidth = header.parent().outerWidth();
// header.css({"max-width": windowWidth, "left": "auto"});
// }
// }

Too Many classes assigned to divs on click

I manage the design for this company, they had someone else write the code for these tabs and it keeps adding too many "active" classes on inactive tabs.
I have been trying to fix this for hours, but this seems overly complicated.
This is the result on the page and on the code. https://drive.google.com/drive/folders/1cxNscwXqKpeUvvuKwKsgdoAIiVNzYKwL?usp=sharing
Thank you for your help!
<script>
jQuery(document).ready(function() {
// ======================================================================
var IngredientsViewer = {
init: function() {
this.setupEventListeners();
this.adjustHeights();
},
// ====================================================================
switchProduct: function(e) {
var $target = jQuery(e.currentTarget);
var $navs = jQuery('.js-ingredients-product-nav');
var $lists = jQuery('.js-ingredients-product-content');
var id = $target.data('id');
var $list;
if ($target.hasClass('active')) { return; }
$navs.removeClass('active');
$target.addClass('active');
this.scrollToIngredients();
$lists.each(function(i, list) {
$list = jQuery(list);
if ($list.hasClass('active')) {
$list.removeClass('active');
(function($list) {
setTimeout(function() {
$list.addClass('mobile-hide');
}, 300);
})($list);
} else {
(function($list) {
setTimeout(function() {
$list.removeClass('mobile-hide');
}, 250);
})($list);
(function($list) {
setTimeout(function() {
$list.addClass('active');
}, 300);
})($list);
}
});
},
// ====================================================================
switchList: function(e) {
var $target = jQuery(e.currentTarget);
var $wrapper = $target.closest('.js-ingredients-product-content');
var $navs = $wrapper.find('.js-ingredients-nav-item');
var $lists = $wrapper.find('.js-ingredients-list');
var id = $target.data('id');
var $list;
if ($target.hasClass('active')) { return; }
$navs.removeClass('active');
$target.addClass('active');
$lists.each(function(i, list) {
$list = jQuery(list);
if ($list.hasClass('active')) {
$list.removeClass('active');
(function($list) {
setTimeout(function() {
$list.addClass('mobile-hide');
}, 300);
})($list);
} else {
(function($list) {
setTimeout(function() {
$list.removeClass('mobile-hide');
}, 250);
})($list);
(function($list) {
setTimeout(function() {
$list.addClass('active');
}, 300);
})($list);
}
});
},
// ====================================================================
switchDescription: function(e) {
var $target = jQuery(e.currentTarget);
var $description = jQuery('.js-ingredients-description');
var template = this.createDescriptionTemplate({
title: $target.data('title'),
details1: $target.data('details-1'),
details2: $target.data('details-2')
});
if (template) {
$description.removeClass('show');
this.openModal();
setTimeout(function() {
$description.html(template);
$description.addClass('show');
}, 300);
}
},
// ====================================================================
scrollToIngredients: function() {
var ingredients = jQuery('.js-product-content-wrapper')[0];
var offset;
if (ingredients && window.innerWidth <= 900) {
offset = this.getOffsetTop(ingredients) - 50;
if (navigator.userAgent.match(/(iPod|iPhone|iPad|Android)/)) {
setTimeout(function() {
window.scrollTo(0, offset);
}, 300);
} else {
jQuery('html').animate({ scrollTop: offset }, 300);
}
}
},
// ======================================================================
getOffsetTop: function(el) {
var top = 0;
while(el) {
top += el.offsetTop;
el = el.offsetParent;
}
return top;
},
// ====================================================================
createDescriptionTemplate: function(data) {
var template = '';
var subTemplate;
if (data.title && data.details1) {
template += '<h3>What is <span>' + data.title + '</span>?</h3>';
template += '<div>' + data.details1 + '</div>';
}
if (data.details2) {
template += '<h3>Why did we choose it?</h3>';
template += '<div>' + data.details2 + '</div>';
}
return template;
},
// ====================================================================
adjustHeights: function() {
this.adjustIngredientHeights();
},
// ====================================================================
adjustIngredientHeights: function() {
var $wrapper = jQuery('.js-ingredient-label');
var $inner = jQuery('.js-ingredient-label-inner');
var heights = $inner.map(function(i, p) { return p.offsetHeight; });
var max = Math.max.apply(Math, heights);
if ($inner.length && max) {
$wrapper.css({ 'minHeight': max + 'px' });
}
},
// ====================================================================
openModal: function() {
if (window.innerWidth <= 900) {
jQuery('.js-ingredients-modal').fadeIn(400);
}
},
// ====================================================================
closeModal: function(e) {
jQuery(e.currentTarget).fadeOut(400);
},
// ====================================================================
setupEventListeners: function() {
jQuery(document).on('click', '.js-ingredients-nav-item', this.switchList.bind(this));
jQuery(document).on('click', '.js-ingredients-list-item', this.switchDescription.bind(this));
jQuery(document).on('click', '.js-ingredients-modal', this.closeModal.bind(this));
jQuery(document).on('click', '.js-ingredients-product-nav', this.switchProduct.bind(this));
jQuery(window).on('resize', this.adjustHeights.bind(this));
}
};
// ======================================================================
Object.create(IngredientsViewer).init();
// ======================================================================
});
</script>

Uncaught type error: .vegas is not a function

I'm trying to load my landing page but it is not loading my .vegas function in my custom.js file. The vegas function is created in the file jquery.vegas.js. This seems to be the problem, so how do I change the order of how the scripts are called within my Rails app in the asset pipeline? Can I change the order of how it is called in the application.js file?
Custom.js file where the .vegas function is being called
(function($){
// Preloader
$(window).load(function() {
$('#status').fadeOut();
$('#preloader').delay(350).fadeOut('slow');
$('body').delay(350).css({'overflow':'visible'});
});
$(document).ready(function() {
// Image background
$.vegas({
src:'assets/images/bg1.jpg'
});
$.vegas('overlay', {
src:'assets/images/06.png'
});
var countdown = $('.countdown-time');
createTimeCicles();
$(window).on('resize', windowSize);
function windowSize(){
countdown.TimeCircles().destroy();
createTimeCicles();
countdown.on('webkitAnimationEnd mozAnimationEnd oAnimationEnd animationEnd', function() {
countdown.removeClass('animated bounceIn');
});
}
Application.js file
//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require_tree .
Jquery.vegas.js file where the vegas function resides(At the very bottom)
(function($) {
var $background = $("<img />").addClass("vegas-background"), $overlay = $("<div />").addClass("vegas-overlay"), $loading = $("<div />").addClass("vegas-loading"), $current = $(), paused = null, backgrounds = [], step = 0, delay = 5e3, walk = function() {}, timer,
methods = {
init: function(settings) {
var options = {
src: getBackground(),
align: "center",
valign: "center",
fade: 0,
loading: true,
load: function() {},
complete: function() {}
};
$.extend(options, $.vegas.defaults.background, settings);
if (options.loading) {
loading();
}
var $new = $background.clone();
$new.css({
position: "fixed",
left: "0px",
top: "0px"
}).bind("load", function() {
if ($new == $current) {
return;
}
$(window).bind("load resize.vegas", function(e) {
resize($new, options);
});
if ($current.is("img")) {
$current.stop();
$new.hide().insertAfter($current).fadeIn(options.fade, function() {
$(".vegas-background").not(this).remove();
$("body").trigger("vegascomplete", [ this, step - 1 ]);
options.complete.apply($new, [ step - 1 ]);
});
} else {
$new.hide().prependTo("body").fadeIn(options.fade, function() {
$("body").trigger("vegascomplete", [ this, step - 1 ]);
options.complete.apply(this, [ step - 1 ]);
});
}
$current = $new;
resize($current, options);
if (options.loading) {
loaded();
}
$("body").trigger("vegasload", [ $current.get(0), step - 1 ]);
options.load.apply($current.get(0), [ step - 1 ]);
if (step) {
$("body").trigger("vegaswalk", [ $current.get(0), step - 1 ]);
options.walk.apply($current.get(0), [ step - 1 ]);
}
}).attr("src", options.src);
return $.vegas;
},
destroy: function(what) {
if (!what || what == "background") {
$(".vegas-background, .vegas-loading").remove();
$(window).unbind("*.vegas");
$current = $();
}
if (!what || what == "overlay") {
$(".vegas-overlay").remove();
}
clearInterval(timer);
return $.vegas;
},
overlay: function(settings) {
var options = {
src: null,
opacity: null
};
$.extend(options, $.vegas.defaults.overlay, settings);
$overlay.remove();
$overlay.css({
margin: "0",
padding: "0",
position: "fixed",
left: "0px",
top: "0px",
width: "100%",
height: "100%"
});
if (options.src === false) {
$overlay.css("backgroundImage", "none");
}
if (options.src) {
$overlay.css("backgroundImage", "url(" + options.src + ")");
}
if (options.opacity) {
$overlay.css("opacity", options.opacity);
}
$overlay.prependTo("body");
return $.vegas;
},
slideshow: function(settings, keepPause) {
var options = {
step: step,
delay: delay,
preload: false,
loading: true,
backgrounds: backgrounds,
walk: walk
};
$.extend(options, $.vegas.defaults.slideshow, settings);
if (options.backgrounds != backgrounds) {
if (!settings.step) {
options.step = 0;
}
if (!settings.walk) {
options.walk = function() {};
}
if (options.preload) {
$.vegas("preload", options.backgrounds);
}
}
backgrounds = options.backgrounds;
delay = options.delay;
step = options.step;
walk = options.walk;
clearInterval(timer);
if (!backgrounds.length) {
return $.vegas;
}
var doSlideshow = function() {
if (step < 0) {
step = backgrounds.length - 1;
}
if (step >= backgrounds.length || !backgrounds[step - 1]) {
step = 0;
}
var settings = backgrounds[step++];
settings.walk = options.walk;
settings.loading = options.loading;
if (typeof settings.fade == "undefined") {
settings.fade = options.fade;
}
if (settings.fade > options.delay) {
settings.fade = options.delay;
}
$.vegas(settings);
};
doSlideshow();
if (!keepPause) {
paused = false;
$("body").trigger("vegasstart", [ $current.get(0), step - 1 ]);
}
if (!paused) {
timer = setInterval(doSlideshow, options.delay);
}
return $.vegas;
},
next: function() {
var from = step;
if (step) {
$.vegas("slideshow", {
step: step
}, true);
$("body").trigger("vegasnext", [ $current.get(0), step - 1, from - 1 ]);
}
return $.vegas;
},
previous: function() {
var from = step;
if (step) {
$.vegas("slideshow", {
step: step - 2
}, true);
$("body").trigger("vegasprevious", [ $current.get(0), step - 1, from - 1 ]);
}
return $.vegas;
},
jump: function(s) {
var from = step;
if (step) {
$.vegas("slideshow", {
step: s
}, true);
$("body").trigger("vegasjump", [ $current.get(0), step - 1, from - 1 ]);
}
return $.vegas;
},
stop: function() {
var from = step;
step = 0;
paused = null;
clearInterval(timer);
$("body").trigger("vegasstop", [ $current.get(0), from - 1 ]);
return $.vegas;
},
pause: function() {
paused = true;
clearInterval(timer);
$("body").trigger("vegaspause", [ $current.get(0), step - 1 ]);
return $.vegas;
},
get: function(what) {
if (what === null || what == "background") {
return $current.get(0);
}
if (what == "overlay") {
return $overlay.get(0);
}
if (what == "step") {
return step - 1;
}
if (what == "paused") {
return paused;
}
},
preload: function(backgrounds) {
var cache = [];
for (var i in backgrounds) {
if (backgrounds[i].src) {
var cacheImage = document.createElement("img");
cacheImage.src = backgrounds[i].src;
cache.push(cacheImage);
}
}
return $.vegas;
}
};
function resize($img, settings) {
var options = {
align: "center",
valign: "center"
};
$.extend(options, settings);
if ($img.height() === 0) {
$img.load(function() {
resize($(this), settings);
});
return;
}
var vp = getViewportSize(), ww = vp.width, wh = vp.height, iw = $img.width(), ih = $img.height(), rw = wh / ww, ri = ih / iw, newWidth, newHeight, newLeft, newTop, properties;
if (rw > ri) {
newWidth = wh / ri;
newHeight = wh;
} else {
newWidth = ww;
newHeight = ww * ri;
}
properties = {
width: newWidth + "px",
height: newHeight + "px",
top: "auto",
bottom: "auto",
left: "auto",
right: "auto"
};
if (!isNaN(parseInt(options.valign, 10))) {
properties.top = 0 - (newHeight - wh) / 100 * parseInt(options.valign, 10) + "px";
} else if (options.valign == "top") {
properties.top = 0;
} else if (options.valign == "bottom") {
properties.bottom = 0;
} else {
properties.top = (wh - newHeight) / 2;
}
if (!isNaN(parseInt(options.align, 10))) {
properties.left = 0 - (newWidth - ww) / 100 * parseInt(options.align, 10) + "px";
} else if (options.align == "left") {
properties.left = 0;
} else if (options.align == "right") {
properties.right = 0;
} else {
properties.left = (ww - newWidth) / 2;
}
$img.css(properties);
}
function loading() {
$loading.prependTo("body").fadeIn();
}
function loaded() {
$loading.fadeOut("fast", function() {
$(this).remove();
});
}
function getBackground() {
if ($("body").css("backgroundImage")) {
return $("body").css("backgroundImage").replace(/url\("?(.*?)"?\)/i, "$1");
}
}
function getViewportSize() {
var elmt = window, prop = "inner";
if (!("innerWidth" in window)) {
elmt = document.documentElement || document.body;
prop = "client";
}
return {
width: elmt[prop + "Width"],
height: elmt[prop + "Height"]
};
}
$.vegas = function(method) {
if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === "object" || !method) {
return methods.init.apply(this, arguments);
} else {
$.error("Method " + method + " does not exist");
}
};
$.vegas.defaults = {
background: {},
slideshow: {},
overlay: {}
};
})(jQuery);
The assets are compiled alphabetically in the pipeline. So you could either rename the files to compile in the order you like, or you can remove
//= require_tree .
in your application.js and require all of your assets manually in the order you choose. Hopefully that helps a little.

How to stop document.ready from exection in jquery

My query in the below code is --- I used a function slider in document.ready.Now my query is that when I click 'dot1' The function slider in the document.ready to stop execute until the function is called again. How to achieve this?Can anyone help me.....
Thanking you in advance.
here is my code:
var imgValue;
var value;
var flag;
function ClickEvent() {
$('span[id^="dot"]').click(function (event) {
event.stopPropagation();
var Clickid = $(event.target)[0].id;
$('.image1').css('display', 'none');
$('.innerdiv').css('display', 'none');
switch (Clickid) {
case 'dot1':
{
debugger;
SliderTimer = null;
clearInterval(SliderTimer);
flag = 0;
value = 1;
ImageLoad(value);
//setTimeout(SlideImage(), 150000);
//alert("dot1 Clicked");
break;
}
case 'dot2':
{
//alert("dot2 Clciked");
//setTimeout(SlideImage(), 5000);
value = 2;
ImageLoad(value);
//setTimeout(SlideImage(), 150000);
//alert("dot2 Clicked");
break;
}
case 'dot3':
{
//alert("dot3 Clicked");
//setTimeout(SlideImage(), 5000);
value = 3;
ImageLoad(value);
//setTimeout(SlideImage(), 150000);
//alert("dot3 Clicked");
break;
}
}
});
}
function ImageLoad(count) {
$('* span').css('background-color', '#ccc');
$('.Dots #dot' + count).delay(4500).css('background-color', "Black");
$('.image #img' + count).show('fade', { direction: 'right' }, 1000);
$('.image #indiv' + count).delay(1500).show('fade', 1000);
$('.image #indiv' + count).delay(2500).hide('fade', { direction: 'left' }, 1000);
$('.image #img' + count).delay(4500).hide('fade', { direction: 'left' }, 1000);
}
function LoadPage() {
$('.image #img1').show('fade', 1000);
$('* span').css('background-color', '#ccc');
$('.Dots #dot1').css('background-color', 'Black');
}
$(document).ready(function Slider() {
var sc = $('.image img').size();
LoadPage();
value = 1;
setInterval(SliderTimer, 5000);
ClickEvent();
});
var SliderTimer = function SliderImage() {
var sc = $('.image img').size();
ImageLoad(value);
if (value == sc) {
value = 1;
}
else {
value += 1;
}
}
</script>
Use clearInterval :
var timer = setInterval(function() { ... }, 666);
...
$('#butt').click(function(){
clearInterval(timer);
});
EDIT : here's how your code would look :
var sliderTimer;
function ClickEvent() {
...
switch (Clickid) {
case 'dot1':
{
clearInterval(sliderTimer);
...
}
...
$(document).ready(function Slider() {
...
sliderTimer = setInterval(SliderTimer, 5000);
ClickEvent();
});
function SliderImage() {
var sc = $('.image img').size();
ImageLoad(value);
if (value == sc) {
value = 1;
}
else {
value += 1;
}
}

S3Slider jQuery Stop After One Rotation

I'm using an S3Slider on WordPress. I'd like it to stop after one rotation, but can't seem to figure out the setting.
The following code is used in the slider.js file. Right now it's live at http://beaconwc.com on the frontpage, would like it to show the two slides and then stop until the user refreshes the page.
(function($){
$.fn.s3Slider = function(vars) {
var element = this;
var timeOut = (vars.timeOut != undefined) ? vars.timeOut : 4000;
var current = null;
var timeOutFn = null;
var faderStat = true;
var mOver = false;
var capOpacity = vars.captionOpacity || .7;
var items = $("#" + element[0].id + "Content ." + element[0].id + "Image");
var itemsSpan = $("#" + element[0].id + "Content ." + element[0].id + "Image div");
itemsSpan.css({
'opacity': capOpacity,
'display': 'none'
});
items.each(function(i) {
$(items[i]).mouseover(function() {
mOver = true;
});
$(items[i]).mouseout(function() {
mOver = false;
fadeElement(true);
});
});
var fadeElement = function(isMouseOut) {
var thisTimeOut = (isMouseOut) ? (timeOut/2) : timeOut;
thisTimeOut = (faderStat) ? 10 : thisTimeOut;
if(items.length > 0) {
timeOutFn = setTimeout(makeSlider, thisTimeOut);
} else {
console.log("Poof..");
}
}
var makeSlider = function() {
current = (current != null) ? current : items[(items.length-1)];
var currNo = jQuery.inArray(current, items) + 1
currNo = (currNo == items.length) ? 0 : (currNo - 1);
var newMargin = $(element).width() * currNo;
if(faderStat == true) {
if(!mOver) {
$(items[currNo]).fadeIn((timeOut/6), function() {
if($(itemsSpan[currNo]).css('bottom') == 0) {
$(itemsSpan[currNo]).slideUp((timeOut/6), function() {
faderStat = false;
current = items[currNo];
if(!mOver) {
fadeElement(false);
}
});
} else {
$(itemsSpan[currNo]).slideDown((timeOut/6), function() {
faderStat = false;
current = items[currNo];
if(!mOver) {
fadeElement(false);
}
});
}
});
}
} else {
if(!mOver) {
if($(itemsSpan[currNo]).css('bottom') == 0) {
$(itemsSpan[currNo]).slideDown((timeOut/6), function() {
$(items[currNo]).fadeOut((timeOut/6), function() {
faderStat = true;
current = items[(currNo+1)];
if(!mOver) {
fadeElement(false);
}
});
});
} else {
$(itemsSpan[currNo]).slideUp((timeOut/6), function() {
$(items[currNo]).fadeOut((timeOut/6), function() {
faderStat = true;
current = items[(currNo+1)];
if(!mOver) {
fadeElement(false);
}
});
});
}
}
}
}
makeSlider();
};
})(jQuery);
Thanks!
Source
http://www.serie3.info/s3slider/

Categories

Resources