How to stop document.ready from exection in jquery - javascript

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;
}
}

Related

Call function to update 'onclick' parameters after 3 seconds

I have this code and not everything working as expected:
ORYGINAL CODE - START
function reminder_set_now$id(this_val,this_change) {
$( '#set_reminder' ).on({
mousedown: function() {
$(this).data('timer', setTimeout(function() {
if (this_change = 1) {
alert('1!');
sr_change_click_e1();
}
else if (this_change = 2) {
alert('2!');
sr_change_click_e2();
}
else {
alert('3!');
sr_change_click_e3();
}
}, 3000));
},
mouseup: function() {
clearTimeout( $(this).data('timer') );
}
});
}
function sr_change_click_e1() {
var clickfun = $("#set_reminder").attr("onClick");
var funname = clickfun.substring(0,clickfun.indexOf("("));
$("#set_reminder").attr("onclick",funname+"(\'2\',\'2\')");
}
function sr_change_click_e2() {
var clickfun = $("#set_reminder").attr("onClick");
var funname = clickfun.substring(0,clickfun.indexOf("("));
$("#set_reminder").attr("onclick",funname+"(\'3\',\'3\')");
}
function sr_change_click_e3() {
var clickfun = $("#set_reminder").attr("onClick");
var funname = clickfun.substring(0,clickfun.indexOf("("));
$("#set_reminder").attr("onclick",funname+"(\'1\',\'1\')");
}
Reminder
ORYGINAL CODE - END
And 2 issues with it:
Alert1 doesnt display after I hold for 3 seconds for the first time but if I click on it first and then hold it with the second click.
every other hold display always alert1 not 2 and then 3
UPDATED CODE - START
function reminder_set_now(this_val,this_change) {
var t_change = this_change;
$( '#set_reminder' ).on({
mousedown: function() {
$(this).data('timer', setTimeout(function() {
if(t_change == 1) {
sr_change_click_e1();
}
else if (t_change == 2) {
sr_change_click_e2();
}
else {
sr_change_click_e3();
}
}, 3000));
},
mouseup: function() {
clearTimeout( $(this).data('timer') );
}
});
}
function sr_change_click_e1() {
var clickfun = $("#set_reminder").attr("onmousedown");
var funname = clickfun.substring(0,clickfun.indexOf("("));
$("#set_reminder").attr("onmousedown",funname+"(\'2\',\'2\')");
}
function sr_change_click_e2() {
var clickfun = $("#set_reminder").attr("onmousedown");
var funname = clickfun.substring(0,clickfun.indexOf("("));
$("#set_reminder").attr("onmousedown",funname+"(\'3\',\'3\')");
}
function sr_change_click_e3() {
var clickfun = $("#set_reminder").attr("onmousedown");
var funname = clickfun.substring(0,clickfun.indexOf("("));
$("#set_reminder").attr("onmousedown",funname+"(\'1\',\'1\')");
}
Reminder
UPDATED CODE - END
Any suggestions where I am wrong please.

Resume a function after clearInterval

I have this code:
jQuery(function($) { // DOM is ready
var $el = $("header tr"),
tot = $el.length,
c = 0;
var timer = setInterval(function() {
$el.removeClass("current").eq(++c % tot).addClass("current");
}, 3000);
$el.first().addClass("current");
$el.on({
mouseenter: function(e) {
clearInterval(timer);
}
});
$el.mouseout({
timer;
});
});
I want to suspend the function on mouseover and resume it on mouse out but I cant get the latter right. How can I resume it?
Thank you.
There are two ways:
Set a flag that the function being called by the interval checks, and have the function not do anything if it's "suspended."
Start the interval again via a new setInterval call. Note that the old timer value cannot be used for this, you need to pass in the code again.
Example of #1:
jQuery(function($) { // DOM is ready
var $el = $("header tr"),
tot = $el.length,
c = 0,
suspend = false; // The flag
var timer = setInterval(function() {
if (!suspend) { // Check it
$el.removeClass("current").eq(++c % tot).addClass("current");
}
}, 3000);
$el.first().addClass("current");
$el.on({
mouseenter: function(e) {
suspend = true; // Set it
},
mouseleave: function(e) {
suspend = false; // Clear it
}
});
});
Example of #2:
jQuery(function($) { // DOM is ready
var $el = $("header tr"),
tot = $el.length,
c = 0,
timer = 0;
// Move this to a reusable function
var intervalHandler = function() {
$el.removeClass("current").eq(++c % tot).addClass("current");
};
// Probably best to encapsulate the logic for starting it rather
// than repeating that logic
var startInterval = function() {
timer = setInterval(intervalHandler, 3000);
};
// Initial timer
startInterval();
$el.first().addClass("current");
$el.on({
mouseenter: function(e) {
clearInterval(timer); // Stop it
}
mouseleave: function(e) {
startInterval(); // Start it
}
});
});
Checkout these prototypes:
//Initializable
function Initializable(params) {
this.initialize = function(key, def, private) {
if (def !== undefined) {
(!!private ? params : this)[key] = (params[key] !== undefined) ? params[key] : def;
}
};
}
function PeriodicJobHandler(params) {
Initializable.call(this, params);
this.initialize("timeout", 1000, true);
var getTimeout = function() {
return params.timeout;
};
var jobs = [];
function Job(params) {
//expects params.job() function
Initializable.call(this, params);
this.initialize("timeout", getTimeout(), true);
this.initialize("instant", false);
var intervalID = undefined;
this.start = function() {
if (intervalID !== undefined) {
return;
}
if (this.instant) {
params.job(true);
}
intervalID = setInterval(function() {
params.job(false);
}, params.timeout);
};
this.stop = function() {
clearInterval(intervalID);
intervalID = undefined;
};
}
this.addJob = function(params) {
jobs.push(new Job(params));
return jobs.length - 1;
};
this.removeJob = function(index) {
jobs[index].stop();
jobs.splice(index, 1);
};
this.startJob = function(index) {
jobs[index].start();
};
this.stopJob = function(index) {
jobs[index].stop();
};
}
Initializable simplifies member initialization, while PeriodicJobHandler is able to manage jobs in a periodic fashion. Now, let's use it practically:
var pjh = new PeriodicJobHandler({});
//It will run once/second. If you want to change the interval time, just define the timeout property in the object passed to addJob
var jobIndex = pjh.addJob({
instant: true,
job: function() {
$el.removeClass("current").eq(++c % tot).addClass("current");
}
});
jQuery(function($) { // DOM is ready
var $el = $("header tr"),
tot = $el.length,
c = 0;
var timer = setInterval(function() {
$el.removeClass("current").eq(++c % tot).addClass("current");
}, 3000);
$el.first().addClass("current");
$el.on({
mouseenter: function(e) {
jobIndex.stop();
}
});
$el.mouseout({
jobIndex.start();
});
});
With Javascript, it is much easy and efficient.
You can change the interval in setInterval function.
It is checking whether suspend variable is false or true, here suspend variable is setting to true, if mouseEnter function is called and set to false if mouseLeave function is called.
var displayMsg = document.getElementById('msg').innerHTML;
var i = 0;
var suspend = false;
var sequence = setInterval(update, 100);
function update() {
if (suspend == false) {
var dispalyedMsg = '';
dispalyedMsg = displayMsg.substring(i, displayMsg.length);
dispalyedMsg += ' ';
dispalyedMsg += displayMsg.substring(0, i);
document.getElementById('msg').innerHTML = dispalyedMsg;
i++;
if (i > displayMsg.length) {
i = 0;
}
}
}
document.getElementById('msg').addEventListener('mouseenter', mouseEnter);
document.getElementById('msg').addEventListener('mouseleave', mouseLeave);
function mouseEnter() {
suspend = true;
}
function mouseLeave() {
suspend = false;
}
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
#msg {
width: 680px;
height: 100px;
border: 1px solid #ccc;
padding-left: 15px;
}
</style>
</head>
<body>
<div id="msg">
Today is only 15% discount. Hurry up to grab. Sale will end sooooooooooooon!!!!
</div>
<div id="output"></div>
<script src="marquee.js"></script>
</body>
</html>

Combining two Javascript functions to one window.onload not working

I have two functions that I want to run on window.onload event but only the last function seems to work so far. One function is for an image slider and the other one retrieves data from a google spreadsheet cell.
function fun1() { //image slider
var ul;
var li_items;
var imageNumber;
var imageWidth;
var prev, next;
var currentPostion = 0;
var currentImage = 0;
function init() {
ul = document.getElementById('image_slider');
li_items = ul.children;
imageNumber = li_items.length;
imageWidth = li_items[0].children[0].clientWidth;
ul.style.width = parseInt(imageWidth * imageNumber) + 'px';
prev = document.getElementById("prev");
next = document.getElementById("next");
prev.onclick = function() {
onClickPrev();
};
next.onclick = function() {
onClickNext();
};
}
function animate(opts) {
var start = new Date;
var id = setInterval(function() {
var timePassed = new Date - start;
var progress = timePassed / opts.duration;
if (progress > 1) {
progress = 1;
}
var delta = opts.delta(progress);
opts.step(delta);
if (progress == 1) {
clearInterval(id);
opts.callback();
}
}, opts.delay || 17);
}
function slideTo(imageToGo) {
var direction;
var numOfImageToGo = Math.abs(imageToGo - currentImage);
direction = currentImage > imageToGo ? 1 : -1;
currentPostion = -1 * currentImage * imageWidth;
var opts = {
duration: 1000,
delta: function(p) {
return p;
},
step: function(delta) {
ul.style.left = parseInt(currentPostion + direction * delta * imageWidth * numOfImageToGo) + 'px';
},
callback: function() {
currentImage = imageToGo;
}
};
animate(opts);
}
function onClickPrev() {
if (currentImage == 0) {
slideTo(imageNumber - 1);
} else {
slideTo(currentImage - 1);
}
}
function onClickNext() {
if (currentImage == imageNumber - 1) {
slideTo(0);
} else {
slideTo(currentImage + 1);
}
}
}
function fun2() {
// Google spreadsheet js
google.load('visualization', '1', {
callback: function() {
var query = new google.visualization.Query('https://docs.google.com/spreadsheets/d/1sA7M5kG6Xo8YScD1Df38PIA_G0bvhGRdqoExXg0KJTs/gviz/tq?tqx=out:html&tq?gid=0&headers=0&range=A1:C');
query.send(displayData);
}
});
function displayData(response) {
numRows = response.getDataTable().getValue(0, 0);
document.getElementById('data').innerHTML = numRows;
}
}
var addFunctionOnWindowLoad = function(callback) {
if (window.addEventListener) {
window.addEventListener('load', callback, false);
} else {
window.attachEvent('onload', callback);
}
}
addFunctionOnWindowLoad(fun1);
addFunctionOnWindowLoad(fun2);
This is the answer I've tried link but I can't seem to figure out where I'm going wrong.
This is what I ended up doing, and now all the functions work.
var ul;
var li_items;
var imageNumber;
var imageWidth;
var prev, next;
var currentPostion = 0;
var currentImage = 0;
function init() {
ul = document.getElementById('image_slider');
li_items = ul.children;
imageNumber = li_items.length;
imageWidth = li_items[0].children[0].clientWidth;
ul.style.width = parseInt(imageWidth * imageNumber) + 'px';
prev = document.getElementById("prev");
next = document.getElementById("next");
prev.onclick = function() {
onClickPrev();
};
next.onclick = function() {
onClickNext();
};
}
function animate(opts) {
var start = (new Date());
var id = setInterval(function() {
var timePassed = (new Date()) - start;
var progress = timePassed / opts.duration;
if (progress > 1) {
progress = 1;
}
var delta = opts.delta(progress);
opts.step(delta);
if (progress == 1) {
clearInterval(id);
opts.callback();
}
}, opts.delay || 17);
//return id;
}
function slideTo(imageToGo) {
var direction;
var numOfImageToGo = Math.abs(imageToGo - currentImage);
// slide toward left
direction = currentImage > imageToGo ? 1 : -1;
currentPostion = -1 * currentImage * imageWidth;
var opts = {
duration: 1000,
delta: function(p) {
return p;
},
step: function(delta) {
ul.style.left = parseInt(currentPostion + direction * delta * imageWidth * numOfImageToGo) + 'px';
},
callback: function() {
currentImage = imageToGo;
}
};
animate(opts);
}
function onClickPrev() {
if (currentImage === 0) {
slideTo(imageNumber - 1);
} else {
slideTo(currentImage - 1);
}
}
function onClickNext() {
if (currentImage == imageNumber - 1) {
slideTo(0);
} else {
slideTo(currentImage + 1);
}
}
window.onload = init;
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
if (oldonload) {
oldonload();
}
func();
}
}
}
function fun2() {
// Google spreadsheet js
google.load('visualization', '1', {
callback: function() {
var query = new google.visualization.Query('https://docs.google.com/spreadsheets/d/1sA7M5kG6Xo8YScD1Df38PIA_G0bvhGRdqoExXg0KJTs/gviz/tq?tqx=out:html&tq?gid=0&headers=0&range=A1:C');
query.send(displayData);
}
});
function displayData(response) {
numRows = response.getDataTable().getValue(0, 0);
document.getElementById('data').innerHTML = numRows;
}
}
addLoadEvent(fun2);
addLoadEvent(function() {
});
I found this function a while ago and believe it or not, I still need to use it every so often. addEventLoad() Just call addEventLoad while passing the function to load.
"The way this works is relatively simple: if window.onload has not already been assigned a function, the function passed to addLoadEvent is simply assigned to window.onload. If window.onload has already been set, a brand new function is created which first calls the original onload handler, then calls the new handler afterwards."
This snippet will load 3 functions on window.onload
Snippet
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
if (oldonload) {
oldonload();
}
func();
}
}
}
function alert1() {
alert("First Function Loaded");
}
function alert2() {
alert("Second Function Loaded");
}
function alert3(str) {
alert("Third Function Loaded; Msg: " + str);
}
addLoadEvent(alert1);
addLoadEvent(alert2);
addLoadEvent(function() {
alert3("This works");
});
<script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script>

Start stop function on scroll event within if/else statement

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');
});

Why isn't .is(":hover") working?

I have this code to fade out some stuff on a page after you don't move your mouse for a second or so:
idleTime = 0;
var idleInterval = setInterval(function() {
idleTime++;
if (idleTime > 1) {
var isHovered = $('.fade-outs').is(":hover");
if(isHovered == false) {
$('.fade-outs').stop().fadeOut();
}
}
}, 1000);
$(document).bind('mousemove mousedown', function(e) {
idleTime = 0;
$('.fade-outs').fadeIn();
});
But, I am getting the following error with $('.fade-outs').is(":hover"); part:
Error: Syntax error, unrecognized expression: hover [http://localhost:5545/assets/js/jquery.min.js:3]
Does anyone know why I am getting this error?
I would try something like this instead:
var idleTimer;
function startTimer() {
stopTimer();
idleTimer = setInterval(function() {
$('.fade-outs').stop().fadeOut();
}, 1000);
}
function stopTimer() {
idleTimer && clearInterval(idleTimer);
}
$(document).on('mousemove', startTimer);
$('.fade-outs').on({
mouseleave: startTimer,
mouseenter: stopTimer,
mousemove: function(e) {
e.stopPropagation();
}
});​
Demo: http://jsfiddle.net/Blender/urzug/4/
Try changing it to this:
idleTime = 0;
var idleInterval = setInterval(function() {
idleTime++;
if (idleTime > 1) {
var isHovered = $('.fade-outs').is(".hover");
if(isHovered == false) {
$('.fade-outs').stop().fadeOut();
}
}
}, 1000);
$(document).bind('mousemove mousedown', function(e){
idleTime = 0;
$('.fade-outs').fadeIn();
});
$('.fade-outs').hover(funciton() { $(this).toggleClass('hover') });

Categories

Resources