I'm using some jQuery code to create tabs in which the page's content is broken up into (navigable from the top of the tab block) and am looking to do the following when a "next" or "previous" link (placed at the bottom of each tab's content) is clicked:
The page to scroll up to the top of the tab block (successfully implemented using ".scrollTo" plugin) over 750ms
Once scrolled, the tab to change to the corresponding "previous" or "next" tab (identified by a hashtag url) - 250ms later.
Using the following code:
$(".external_link").click(function() {
$.scrollTo(515, 750, {easing:'easeInOutQuad'});
setTimeout(changeTab($(this).attr("href")), 1000);
return false;
});
the two happen at the same time at the mo. If anyone could shed some light on what I'm doing wrong I'd be really appreciative.
The code in full:
$(document).ready(function() {
$(".tab_content").hide();
$("ul.content_tabs li:first").addClass("active").show();
$(".tab_content:first").show();
$('.content_tabs li').each(function(i) {
var thisId = $(this).find("a").attr("href");
thisId = thisId.substring(1,thisId.length) + '_top';
$(this).attr("id",thisId);
});
function changeTab(activeTab) {
$("ul.content_tabs li").removeClass("active");
$(activeTab + '_top').addClass("active");
$(".tab_content").hide();
$(activeTab).fadeIn();
}
//check to see if a tab is called onload
if (location.hash!=""){changeTab(location.hash);}
//if you call the page and want to show a tab other than the first, for instance index.html#tab4
$("ul.content_tabs li").click(function() {
if ($(this).hasClass("active"))
return false;
changeTab($(this).find("a").attr("href"));
return false;
});
$(".external_link").click(function() {
$.scrollTo(515, 750, {easing:'easeInOutQuad'});
setTimeout(changeTab($(this).attr("href")), 1000);
return false;
});
});
Am I right to be attempting to do this with setTimeout? My knowledge is incredibly limited.
setTimeout(changeTab($(this).attr("href")), 1000);
That's the wrong one, you have to put in a function, not the result of executing a function, and 250 ms makes more sense. changeTab is a function, changeTab(argument) is executing a function. So try
var that = $(this);
setTimeout(function() {changeTab(that.attr("href"))}, 250);
I think the reason they execute at the same time is because you call the changeTab-function directly when you set the timeout, and the previous function waits for 750ms before proceding.
You are passing a function call to setTimeout(). You need to pass a function reference. The call will get executed immediately, but a function reference will be executed when the timeout expires. Call setTimeout() like this:
setTimeout(function() { changeTab($(this).attr("href")); }, 1000);
Also, you should consider taking advantage of the onAfter option of the .scrollTo() plugin which indicates a function to be called when the scrolling is completed. It may make more sense to go:
$.scrollTo(515, 750, {
easing: 'easeInOutQuad',
onAfter: function () {
setTimeout(function() { changeTab($(this).attr("href")); }, 250);
}
});
Related
I want to make a one pager website, without using any third party libraries, like FullPage.js.
when scroll starts --> instead of waiting for the end of the natural scrolling, I want it to take no effect (so no visible scroll caused by the mouse) and to run my code instead. (so it could always go to next section, or previous one, without relying on the amount of the users scroll)
Do you have any idea how could I achieve this? My code snippet waits for the end of scroll, and then jumps to where it should, so it's not working as intended.
(the first section has a "current" class and then the code snippet works by manipulating the 100vh sections by adding/removing this class)
You can see the code snippet I am using below or here:
https://codepen.io/makiwara/pen/PoqjdNZ
Thank you very much for your help, have a nice day!
var script = document.createElement('script');script.src = "https://code.jquery.com/jquery-3.4.1.min.js";document.getElementsByTagName('head')[0].appendChild(script);
var timerId;
var scrollableElement = document.body; //document.getElementById('scrollableElement');
scrollableElement.addEventListener('wheel', checkScrollDirection);
function checkScrollDirection(event) {
var $current = $('.current');
if (checkScrollDirectionIsUp(event)) {
console.log('UP');
$prev = $current.prev();
if ($prev.length) {
clearTimeout(timerId);
timerId = setTimeout(function(){
$current.removeClass('current');
$prev.addClass('current');
$('body,html').animate({
scrollTop: $('.current').offset().top
}, 100);
}, 100)
}
} else {
console.log('Down');
$next = $current.next();
if ($next.length) {
clearTimeout(timerId);
timerId = setTimeout(function(){
$current.removeClass('current');
$next.addClass('current');
$('body,html').animate({
scrollTop: $('.current').offset().top
}, 100);
} , 100)
}
}
}
function checkScrollDirectionIsUp(event) {
if (event.wheelDelta) {
return event.wheelDelta > 0;
}
return event.deltaY < 0;
}
What you need is throttling the event listener, i.e. limit a function call only once per a time period.
What your code is doing is essentially debouncing i.e limit a function call only after a wait time period has passed.
Firstly ditch the timers you're using. You need to somehow block scrolling from happening more than once. The JavaScript part can be easy if you use Underscore.js's throttle function with one caveat though: It passes through subsequent events after the time period has passed. Luckily, its debouncing method accepts a third argument that gives the behavior you'd want:
scrollableElement.addEventListener(
"wheel",
_.debounce(checkScrollDirection, 200, true) // immediately call the function _once_
);
This third argument makes the debounced function behave like a throttled one, that is it will fire only once and at the same time it will fire immediately.
So assuming that your event handler is now free from the original timeout
function checkScrollDirection(event) {
var $current = $(".current");
if (checkScrollDirectionIsUp(event)) {
console.log("UP");
$prev = $current.prev("section");
if ($prev.length) {
$current.removeClass("current");
$prev.addClass("current");
$("body,html").animate(
{
scrollTop: $prev.offset().top
},
100
);
}
} else {
console.log("Down");
$next = $current.next("section");
if ($next.length) {
$current.removeClass("current");
$next.addClass("current");
$("body,html").animate(
{
scrollTop: $next.offset().top
},
100
);
}
}
}
btw, try to get into the habit of specifying selectors inside .next() and .prev() since jQuery will match all possible siblings, which most likely you don't want. In this case, codepen appends additional <script> elements and jQuery will match those as well.
Now if you try this, you'll notice that the window still responds to every scroll event. Scroll events are one of those events that cannot be cancelled so you need to disable it via CSS
The easiest way is to hide the overflow of the body
body { max-height: 100vh; overflow: hidden; }
And that's it. You may need to adjust the throttle waiting time period to match your preferences.
You can find a working version of the codepen here: https://codepen.io/vassiliskrikonis/pen/XWbgxLj
Heyo,
I was wondering if there would be a way to set a min-time to an onload function so that the div is shown min 2sec. Basicly the same as with min-width or min-height. If the site is taking longer than 2sec to load, the div will still be shown untill the site is fully loaded but when the site takes less than 2sec to load the div will still be displayed for a minimum of 2sec.
Here is my current code:
$(window).on('load', function() {
$('.preloader').delay(350).fadeOut('slow');
});
Try this:
$(window).on('load', function() {
setTimeout( function(){
$('.preloader').fadeOut('slow');
}, 2000 )
});
So I take it you want a function to be run when either: the page loads or after 2 seconds, whatever comes later.
First, define a function to be called:
function load_func() {
$('.preloader').delay(350).fadeOut('slow');
}
Then, let's define a way to call the function in either situation:
var pageLoaded = false;
var timeoutElapsed = false;
$(window).on('load', function() {
pageLoaded = true;
if (timeoutElapsed) {
load_func();
}
});
setTimeout(function() {
timeoutElapsed = true;
if (pageLoaded) {
load_func();
}
}, 2000);
This way, if the page loads before 2 seconds, it will wait the timeout to call the function.
Otherwise, if the page loads after 2 seconds, it will call it whenever that load event happened.
I am working on a currently working on a dropdown menu using jQuery. I have run into an issue where the Timeout function is not working at all. The code for it is:
$(document).ready(function() {
$('.has-sub').hover(
function() {
$('ul', this).stop(true, true).slideDown(500);
},
function() {
$('ul', this).stop(true, true).slideUp(400);
},
function() {
setTimeout(function() {
$('.has-sub').addClass("tap");
}, 2000);
},
function() {
$(this).removeClass("tap");
clearTimeout();
}
);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
What I trying to do is to create a hover delay for parent of the Dropdown. You would need to hover over the parent for 2 seconds for the Dropdown menu to appear. I also want to pair that with a Slidedown and Slideup effect.
The Slidedown and Slideup functions correctly but the Timeout does not work.
You can't just call clearTimeout() (which is not part of JQuery, by the way), you must provide it with an identifier for the timer you want to cancel.
Also, setTimeout() and clearTimeout() are not part of JQuery or JavaScript for that matter. They are methods of the window object, which is supplied by the browser. They are not part of the language (JavaScript) or the library (JQuery).
Additionally, the JQuery .hover() method takes 2 arguments and you are providing 4. I have combined them below, but not knowing exactly what you are trying to do, you may need to adjust that.
$(document).ready(function() {
// This will represent the unique ID of the timer
// It must be declared in a scope that is accessible
// to any code that will use it
var timerID = null;
$('.has-sub').hover(
function() {
// Clear any previously running timers, so
// we dont' wind up with multiples. If there aren't
// any, this code will do noting.
clearTimeout(timerID);
$('ul', this).stop(true, true).slideDown(500);
// Set the ID variable to the integer ID returned
// by setTimeout()
timerID = setTimeout(function() {
$('.has-sub').addClass("tap");
}, 2000);
},
function() {
$('ul', this).stop(true, true).slideUp(400);
$(this).removeClass("tap");
// Clear the particular timer based on its ID
clearTimeout(timerID);
}
);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
I have a jQuery dialog that appears and loads an external page. In that page i am running a setInterval() function that queries my server continuously every 1 second (AJAX). The problem is that when i close the dialog, the setInterval doesn't stop running.
here is the code for the dialog:
var theUrl = 'someUrl';
var popUp = document.createElement('div');
$(popUp).dialog({
width: 400,
height: 270,
title: "Some Title",
autoOpen: true,
resizable:false,
close: function(ev, ui) {
$(this).dialog('destroy');
},
modal: true,
open: function() {
$(this).load(theUrl);
}
});
I tried calling $(this).dialog('destroy') and $(this).remove() and document.body.removeChild(popUp) on close. nothing worked. is there anyway to 'unload' the loaded page?
setInterval returns a handler that you can pass to clearInterval to stop the function from running. Here's a basic example of how it works.
var handler = setInterval(function() {}, 2000);
clearInterval(handler);
For your example you'd want to call clearInterval in the close method of the ui.dialog.
Docs:
setInterval - https://developer.mozilla.org/en/window.setInterval
clearInterval - https://developer.mozilla.org/en/DOM/window.clearInterval
Edit
You will not be able to call clearInterval without the stored handler from setInterval, therefore if the call to setInterval is in another script the only way you're going to capture the handler is to override window.setInterval itself.
$(function() {
var originalSetInterval = window.setInterval;
var handlers = [];
window.setInterval = function() {
handlers.push(arguments[0]);
originalSetInterval(arguments);
};
$('whatever').dialog({
close: function() {
for (var i = 0; i < handlers.length; i++) {
clearInterval(handlers[i]);
}
handlers = [];
}
});
});
Note that the code to override window.setInterval must come before including the <script> tag to bring in the external file. Also this approach will clear all interval functions whenever clearInterval is called, therefore this is not ideal, but it's the only way you're going to accomplish this.
Question
The solution below is intended to slide down the groupDiv displaying div1 and enough space for div2 to slide in. It's all achieved by chaining the animations on the #Link.Click() element.
It seems to bug out, though, when the link is clicked rapidly. Is there a way to prevent this? By perhaps disabling the Click function until the chained animations are complete? I currently have checks in place, but they don't seem to be doing the job :(
Here's the code i'm using:
Custom animate functions.
//Slide up or down and fade in or out
jQuery.fn.fadeThenSlideToggle = function(speed, easing, callback) {
if (this.is(":hidden")) {
visibilityCheck("show", counter--);
return this.slideDown({duration: 500, easing: "easeInOutCirc"}).animate({opacity: 1},700, "easeInOutCirc", callback);
} else {
visibilityCheck("hide", counter++);
return this.fadeTo(450, 0, "easeInOutCirc").slideUp({duration: 500, easing: "easeInOutCirc", complete: callback});
}
};
//Slide off page, or into overflow so it appears hidden.
jQuery.fn.slideLeftToggle = function(speed, easing, callback) {
if (this.css('marginLeft') == "-595px") {
return this.animate({marginLeft: "0"}, speed, easing, callback);
} else {
return this.animate({marginLeft: "-595px"}, speed, easing, callback);
}
};
In the dom ready, i have this:
$('#Link').toggle(
function() {
if (!$("#div2 .tab").is(':animated')) {
$("#GroupDiv").fadeThenSlideToggle(700, "easeInOutCirc", function() {$('#div2 .tab').slideLeftToggle();});
}
},
function(){
if (!$("#groupDiv").is(':animated')) {
$('#div2 .tab').slideLeftToggle(function() {$("#groupDiv").fadeThenSlideToggle(700, "easeInOutCirc", callback);} );
}
}
);
HTML structure is this:
<div id="groupDiv">
<div id="div1">
<div class="tab"></div>
</div>
<div id="div2">
<div class="tab"></div>
</div>
</div>
The issue is your first animating the div#GroupDiv so your initial check if (!$("#div2 .tab").is(':animated')) will be false until the groupDiv has finished animated and the callback is fired.
You could maybe try
if (!$("#div2 .tab").is(':animated') && !$("#GroupDiv").is(':animated'))
however I doubt this will cover really quick clicking. The safest is to unbind the event using
$(this).unbind('toggle').unbind('click');
as the first line inside the if and you can then do away with the animated check. The downside to this is you will have to rebind using the callback you are passing through to your custom animation functions.
You can easily disable your links while animation is running
$('a').click(function () {
if ($(':animated').length) {
return false;
}
});
You can of course replace the $('a') selector to match only some of the links.
Animating something that can be clicked repeatedly is something to look out for because it is prone for errors. I take it that you Problem is that animations queue up and are executed even when you have stopped clicking. The way I solved it was to use the stop() function on an Element.
Syntax: jQuery(selector).stop(clearQueue,gotoEnd) //both parameters are boolean
More Info
When I click on a button, I first stop the animation and clear the Queue, then i proceed to define the new animation on it. gotoEnd can stay false (default value) but you can try tochange it to true if you want, you might like the result.
Usage Example: jQuery('button#clickMe').stop(true).animate({left:+=10}).
you can put this first thing inside the click event
$(element).css({ "pointer-events":"none"});
, and this in the callback function of the animation
$(element).css({ "pointer-events":"auto"});
you can unbind... but this should work too:
if (!$("#div2 .tab").is(':animated') && !$("#GroupDiv").is(':animated')) return;
I have recently made an AJAX jQuery plugin, featuring plenty of animation. The workaround to the AJAX animation bug that I have found is as follows.
$(options.linkSelector).click(function(e){
if ($("#yourNav").hasClass("disabled")) {
return false;
} else {
e.preventDefault();
$("#yourNav").addClass("disabled")
// Prepare DOM for new content
$(content).attr('id', 'content-old');
$('<div/>', {id: 'ajMultiLeft'}).css({'top': '100%'}).insertAfter('#content-old');
// Load new content
$(content).load(linkSrc+ ' ' +options.content+ ' > *', function() {
// Remove old content
$(content).animate({top: '100%'}, 1000, function(){
$(content-old).remove();
$("#yourNav").removeClass("disabled")
});
setBase();
}
What this does is makes the click event for each link respond to nothing whilst the parent div has a class of disabled. The disabled class is set by the function upon initial click and removed via a callback on the final animation.