I even looked at this and this solution still didn't help me : Execute a function after X seconds in jquery
Here is my code:
// featured bounce
$('#featured .animated').hover(function() {
$(this).addClass('bounce');
setTimeout( function(){
$(this).removeClass('bounce');},
1300
);
});
The adding of the class works, but the setTimeout ordeal will not work. It won't even execute and not javascript error is thrown in the Chrome console. I feel like I have everything typed out correctly.. the class on the .animated object after the addClass() looks like this:
"animated bounce"
And the animation plays, but then it NEVER removes the "bounce" from the class attribute.
Any help?
Using Function.prototype.bind correctly, you can avoid cheap context hacks like var that = this.
// featured bounce
$('#featured .animated').hover(function() {
var elem = $(this);
elem.addClass('bounce');
setTimeout(elem.removeClass.bind(elem, 'bounce'), 1300);
});
Side Note: Function.prototype.bind is an ES5 addition and browser support needs to be considered. See the compatibility table at the bottom of the MDN article on the function.
The scope of this is pointing at window, not the element you expect.
$('#featured .animated').hover(function() {
var elem = $(this);
elem.addClass('bounce');
setTimeout( function(){
elem.removeClass('bounce');},
1300
);
});
$('#featured .animated').hover(function() {
$(this).addClass('bounce');
(function(that) {
setTimeout( function(){
// use `that` instead of `this`
$(that).removeClass('bounce');
}, 1300);
})(this); //pass `this` into this function
});
Related
I have a problem with my variable scope in a simple slider script that I´ve written (I don't want to use a readymade solution because of low-bandwidth). The slider script is called on statically loaded pages (http) as well as on content loaded through AJAX. On the statically loaded page (so no AJAX) the script seems to work perfect. However when called through AJAX the methods called can't find the elements of the DOM, which halts the necessay animation that is needed for the slider.
All the events are handled through even delegation (using jQuery's on() function), this however provided no solution. I'm quite sure it has something to do with the structure and variable scope of the script, but am unable to determine how to change the structure. So I'm looking for a solution that works in both situations (called normal or through AJAX).
I tried to declare the needed variables in every function, this however resulted in some akward bugs, like the multiplication of the intervals I set for the animation, because of the function scope. Hope somebody can help me in the right direction.
// Slider function
(function (window, undefined) {
var console = window.console || undefined, // Prevent a JSLint complaint
doc = window.document,
Slider = window.Slider = window.Slider || {},
$doc = $(doc),
sliderContainer = doc.getElementById('slider_container'),
$sliderContainer = $(sliderContainer),
$sliderContainerWidth = $sliderContainer.width(),
slider = doc.getElementById('slider'),
$slider = $(slider),
$sliderChildren = $slider.children(),
$slideCount = $sliderChildren.size(),
$sliderWidth = $sliderContainerWidth * $slideCount;
$sliderControl = $(doc.getElementById('slider_control')),
$prevButton = $(doc.getElementById('prev')),
$nextButton = $(doc.getElementById('next')),
speed = 2000,
interval,
intervalSpeed = 5000,
throttle = true,
throttleSpeed = 2000;
if (sliderContainer == null) return; // If slider is not found on page return
// Set widths according to the container and amount of children
Slider.setSliderWidth = function () {
$slider.width($sliderWidth);
$sliderChildren.width($sliderContainerWidth);
};
// Does the animation
Slider.move = function (dir) {
// Makes use of variables such as $sliderContainer, $sliderContainer width, etc.
};
// On ajax call
$doc.on('ajaxComplete', document, function () {
Slider.setSliderWidth();
});
// On doc ready
$(document).ready(function () {
Slider.setSliderWidth();
interval = window.setInterval('Slider.move("right")', intervalSpeed);
});
// Handler for previous button
$doc.on('click', '#prev', function (e) {
e.preventDefault();
Slider.move('left');
});
// Handler for next button
$doc.on('click', '#next', function (e) {
e.preventDefault();
Slider.move('right');
});
// Handler for clearing the interval on hover and showing next and pervious button
$doc.on('hover', '#slider_container', function (e) {
if (e.type === 'mouseenter') {
window.clearInterval(interval);
$sliderControl.children().fadeIn(400);
}
});
// Handler for resuming the interval and fading out the controls
$doc.on('hover', '#slider_control', function (e) {
if (e.type !== 'mouseenter') {
interval = window.setInterval('Slider.move("right")', intervalSpeed);
$sliderControl.children().fadeOut(400);
}
});
})(window);
The HTML example structure:
<div id="slider_control">
<a id="next" href="#next"></a>
<a id="prev" href="#prev"></a>
</div>
<div id="slider_container">
<ul id="slider">
<li style="background-color:#f00;">1</li>
<li style="background-color:#282">2</li>
<li style="background-color:#ff0">3</li>
</ul>
</div>
I notice you have
Slider.setSliderWidth = function() {
$slider.width($sliderWidth);
$sliderChildren.width($sliderContainerWidth);
};
which is called on ajax complete.
Does you ajax update the DOM giving a new DOM element that you could get to by doc.getElementById('slider')? Then your var slider and jquery var $slider are likely pointing to things that no longer exist (even if there is a dom element with slider as the id). To rectify, whenever the ajax is invoked that replaces that element, reinitialize slider and $slider to point to the new jquery wrapped element using the same initialization you have.
slider = doc.getElementById('slider');
$slider = $(slider);
Edit:
I'm not sure where you're going with the variable scope issue, but take a look at this example.
<pre>
<script>
(function(){
var a = "something";
function x (){
a += "else";
}
function y() {
a = "donut";
}
function print (){
document.write(a +"\n");
}
print ();
x();
print ();
y();
print ();
x();
print ();
})();
document.write(typeof(a) + "\n");
</script>
</pre>
It outputs into the pre tag
something
somethingelse
donut
donutelse
undefined
This isn't all that different from what you're already doing. As long as a is not a parameter of a method and is not declared with var in a nested scope, all references to a in code defined within your function(window,undefined){ ...} method will refer to that a, given that a is defined locally by var to that method. Make sense?
To begin, surely you can replace all the getElementById using a jQuery approach. i.e. replace $(doc.getElementById('next')) with $('#next')
I think that when you use on it doesn't search the element for the selector as you are assuming. So you would have to use:
$doc.on('click', '#slider_control #prev',function(e){
e.preventDefault();
Slider.move('left');
});
Wait, what gets loaded through Ajax? The slider-html code? In that case, the Slider has already been 'created' and a lot of your variables will point to nowhere (because these DOM elements did not existed when the variables were initialized). And they will never do so either.
I have this javascript code:
$(function(){
var currentCarouselItem = 1; //set carousel to first slide
var runCarousel = 1;
$(window).load(function(){
setTimeout('autoScroll()', 10000);
});
function autoScroll(num){
if (runCarousel == 1) {
$('.carouselItem.' + currentCarouselItem).animate({left: '975px'}, 'slow', function(){
$(this).removeClass('active');
$(this).attr('style','');
var nextItem = currentCarouselItem + 1;
if (nextItem == 7) {
nextItem = 1;
}
$('.carouselItem.' + nextItem).animate({left: '110px'}, 'slow', function(){
$(this).addClass('active');
})
})
}
}
})
Whenever I run the site it throws a console error: Uncaught ReferenceError: autoScroll is not defined
Any idea why it thinks it is not defined?
setTimeout('autoScroll()', 10000);
Why put it in quotes?
setTimeout(autoScroll, 10000);
That's for starters.
Additionally, you have scoping issues here.
I could try answering it for you, but I think this guy does a lot better job:
JQuery, setTimeout not working
I think this is because your autoScroll function is inside closure created by outermost $(function(){}). Therefore eval (used to evaluate your string in setTimeout) can't find it, as it runs in a 'global' scope.
You can move the definition of autoScroll outside.
Also, as jcolebrand suggested, remove quotes.
I think it is because when you pass in a string as the first argument for setTimeout() that javascript basically runs eval() from the global scope on that string. autoScroll lives within the scope of $(function() { }) and therefore can't be "seen" from the global scope.
Try changing it to setTimeout(autoScroll, 10000);
There a couple of problems with your code, but the reason that the autoScroll function is not defined is that it defined within the scope of your document ready function, but is executed via eval after the document ready has gone out of scope without the proper closure.
$('.carouselItem.' + currentCarouselItem).animate({left: '975px'}, 'slow', function(){
$(this).removeClass('active');
$(this).attr('style','');
var nextItem = currentCarouselItem + 1;
if (nextItem == 7) {
nextItem = 1;
}
$('.carouselItem.' + nextItem).animate({left: '110px'}, 'slow', function(){
$(this).addClass('active');
});
});
For starters you need a semi colon at the end of functions like this,
I'm trying to get my head around to understand how to use closures in connection with jQuery event functions.
My current problem is to round shapes on the screen and make them stop and fade on mouseover and fade and restart on mouse out. I've to use imagemaps to create a round mouseover sensitive area. While the animation works fine I'm having trouble to make use of closures on the mouseover function as i would like it to be.
Given this setup:
(function($){
$.fn.xyz = function( option ) {
// override defaults with specified option
option = $.extend( {}, $.fn.xyz.option, option );
return this.each(function(index, element) {
// run works fine.
function run(index) {
$(".ball:eq(" + index + ")").css({top: 500).startAnimation({ top: -500}, 1000, "linear", (function (i) {
return function() {
run(i);
}})(index));
}
//1 this version works great but I don't like the .parent().parent() especially as the animation requires
// just the ball I hover over gets the opacity assigned
$("area").mouseover(
function () {$(this).parent().parent().css('opacity', 0.5);}
);
//2 this version makes all balls transparent on page load
$("area").mouseover(
(function (activeElement) {
$(activeElement).css('opacity', 0.5);
})(this)
);
//3 this version makes all balls transparent on the first mouse over event
$("area").mouseover(
(function (activeElement) {
return function() {
$(activeElement).css('opacity', 0.5);
}
})(this)
);
//4 also this version affecs all balls and not just the one that is mouse overed
var activeBall = $(this);
$("area").mouseover(function () {
$(activeBall).css('opacity', 0.5);
}).mouseout(function () {
$(activeBall).css('opacity', 1);
});
run(index);
});
},
$.fn.xyz.option = {};
})(jQuery);
Why does version 2, 3, and 4 target all elements and not just the one which is actively hovered over. How would I make use of closures to have to avoid to make use of indexes or similar workarounds?
Many thanks!
You made it a Self Invoking Anonymous Function. Basically, called it automagically with the jQuery object. You also wrapped functions in functions...which I don't get. This should work:
(function($){
$.fn.xyz = function( option ) {
// override defaults with specified option
option = $.extend( {}, $.fn.xyz.option, option );
return this.each(function(index, element) {
// run works fine.
function run(index) {
$(".ball:eq(" + index + ")").css({top: 500).startAnimation({ top: -500}, 1000, "linear", (function (i) {
return function() {
run(i);
}})(index));
}
//1 this version works great but I don't like the .parent().parent() especially as the animation requires
// just the ball I hover over gets the opacity assigned
$("area").mouseover(
function () {$(this).parent().parent().css('opacity', 0.5);}
);
//2 this version makes all balls transparent on page load
$("area").mouseover(
(function (activeElement) {
$(activeElement).css('opacity', 0.5);
})
);
//3 this version makes all balls transparent on the first mouse over event
$("area").mouseover(
(function (activeElement) {
return function() {
$(activeElement).css('opacity', 0.5);
}
})
);
//4 also this version affecs all balls and not just the one that is mouse overed
var activeBall = $(this);
$("area").mouseover(function () {
$(activeBall).css('opacity', 0.5);
}).mouseout(function () {
$(activeBall).css('opacity', 1);
});
run(index);
});
},
$.fn.xyz.option = {};
})(jQuery);
Basically, SIAF is doing things like this:
(function(txt) { alert(txt); })('Hello world!');
You declare an anonymous function (it has no name), which accepts a parameter, and then with the parentheses at the end, you call it, and what's in the parens are the function's parameters.
So, when you said
(function (activeElement) {
return function() {
$(activeElement).css('opacity', 0.5);
}
})(this)
The compiler saw "activate the function with the this object as parameter". Seeing as how this would refer outside your declared function to the jQuery object, jQuery saw it as "change all elements I have with the .css function".
I had applied this slide mechanism to a page, and it worked fine for a while. I can't remember changing anything at all, but now it won't function properly.
Here is the code:
$(document).ready(function () {
var hash = window.location.hash.substr(1);
var href = $('#nav li a').each(function () {
var href = $(this).attr('href');
if (hash == href.substr(0, href.length)) {
var toLoad = hash + '.html #content';
$('#content').load(toLoad)
}
});
$('#nav li a').click(function () {
$("#story_pane").animate({
marginLeft: 360
}, 250);
$("#main_content").animate({
marginLeft: -600,
opacity: 0.3
}, 250);
$("#main_content").css();
});
alert("test");
var toLoad = $(this).attr('href') + ' #content';
$('#content').hide(1, loadContent);
$('#load').remove();
$('#story_pane').css("display", "block");
$('#story_pane').append('<span id="load"></span>');
$('#load').fadeIn(1);
window.location.hash = $(this).attr('href').substr(0, $(this).attr('href').length - 5);
function loadContent() {
$('#content').load(toLoad, '', showNewContent())
}
function showNewContent() {
$('#content').show(1, hideLoader());
}
function hideLoader() {
$('#load').hide();
}
return false;
});
Only the "test" alert executes properly, I had been looking for any brackets i forgot to close, or other syntax issues but i'm in a bit of a dead end. I do have the files backedup, but that's a last resort option, in case I can't fix this.
edit- works now, I deleted $("#main_content").css(); and added a click function which fixed it
Change this:
function loadContent() {
$('#content').load(toLoad,'',showNewContent) // remove the "()" here
}
The way you had that call to ".load()" coded, you were calling "showNewContent" at the time the load began, not when it finished. Same goes for the "showNewContent" function itself:
function showNewContent() {
$('#content').show(1,hideLoader); // again, remove "()" from "hideLoader"
}
It's important to keep clear the distinction between referring to a function by name when passing it as a parameter for some API that needs a callback, and the process of actually calling the function. In these cases, you need a reference to a function. (Yes, a function call can return a reference to a function, but that's not what's happening here.)
edit — Another significant problem you're going to have here is that the initial call to ".load()" to fetch the currently-relevant page based on the state of the nav will almost certainly not complete before the rest of that code has run. If there are any dependencies for the initialization on content loaded by that initial call to "load()", then that won't be in the DOM yet. You could fix this by stuffing all the code in the rest of the "ready" handler into the completion handler for that initial ".load()".
edit again — OK another problem is this line of code, right after the "alert()":
var toLoad = $(this).attr('href') + ' #content';
What is it that you expect this to be at this point? I think that jQuery will set this to refer to the "document" object, but you won't be able to get any "href" attribute from it like that. Maybe you want "window.location.href" there? I'm not sure what you're trying to accomplish, exactly.
This is what live and delegate are for.
What is the correct (modern) method for tapping into the window resize event that works in Firefox, WebKit, and Internet Explorer?
And can you turn both scrollbars on/off?
jQuery has a built-in method for this:
$(window).resize(function () { /* do something */ });
For the sake of UI responsiveness, you might consider using a setTimeout to call your code only after some number of milliseconds, as shown in the following example, inspired by this:
function doSomething() {
alert("I'm done resizing for the moment");
};
var resizeTimer;
$(window).resize(function() {
clearTimeout(resizeTimer);
resizeTimer = setTimeout(doSomething, 100);
});
$(window).bind('resize', function () {
alert('resize');
});
Here is the non-jQuery way of tapping into the resize event:
window.addEventListener('resize', function(event){
// do stuff here
});
It works on all modern browsers. It does not throttle anything for you. Here is an example of it in action.
Sorry to bring up an old thread, but if someone doesn't want to use jQuery you can use this:
function foo(){....};
window.onresize=foo;
Since you are open to jQuery, this plugin seems to do the trick.
Using jQuery 1.9.1 I just found out that, although technically identical)*, this did not work in IE10 (but in Firefox):
// did not work in IE10
$(function() {
$(window).resize(CmsContent.adjustSize);
});
while this worked in both browsers:
// did work in IE10
$(function() {
$(window).bind('resize', function() {
CmsContent.adjustSize();
};
});
Edit:
)* Actually not technically identical, as noted and explained in the comments by WraithKenny and Henry Blyth.
jQuery provides $(window).resize() function by default:
<script type="text/javascript">
// function for resize of div/span elements
var $window = $( window ),
$rightPanelData = $( '.rightPanelData' )
$leftPanelData = $( '.leftPanelData' );
//jQuery window resize call/event
$window.resize(function resizeScreen() {
// console.log('window is resizing');
// here I am resizing my div class height
$rightPanelData.css( 'height', $window.height() - 166 );
$leftPanelData.css ( 'height', $window.height() - 236 );
});
</script>
I consider the jQuery plugin "jQuery resize event" to be the best solution for this as it takes care of throttling the event so that it works the same across all browsers. It's similar to Andrews answer but better since you can hook the resize event to specific elements/selectors as well as the entire window. It opens up new possibilities to write clean code.
The plugin is available here
There are performance issues if you add a lot of listeners, but for most usage cases it's perfect.
I think you should add further control to this:
var disableRes = false;
var refreshWindow = function() {
disableRes = false;
location.reload();
}
var resizeTimer;
if (disableRes == false) {
jQuery(window).resize(function() {
disableRes = true;
clearTimeout(resizeTimer);
resizeTimer = setTimeout(refreshWindow, 1000);
});
}
hope it will help in jQuery
define a function first, if there is an existing function skip to next step.
function someFun() {
//use your code
}
browser resize use like these.
$(window).on('resize', function () {
someFun(); //call your function.
});
Besides the window resize functions mentioned it is important to understand that the resize events fire a lot if used without a deboucing the events.
Paul Irish has an excellent function that debounces the resize calls a great deal. Very recommended to use. Works cross-browser. Tested it in IE8 the other day and all was fine.
http://www.paulirish.com/2009/throttled-smartresize-jquery-event-handler/
Make sure to check out the demo to see the difference.
Here is the function for completeness.
(function($,sr){
// debouncing function from John Hann
// http://unscriptable.com/index.php/2009/03/20/debouncing-javascript-methods/
var debounce = function (func, threshold, execAsap) {
var timeout;
return function debounced () {
var obj = this, args = arguments;
function delayed () {
if (!execAsap)
func.apply(obj, args);
timeout = null;
};
if (timeout)
clearTimeout(timeout);
else if (execAsap)
func.apply(obj, args);
timeout = setTimeout(delayed, threshold || 100);
};
}
// smartresize
jQuery.fn[sr] = function(fn){ return fn ? this.bind('resize', debounce(fn)) : this.trigger(sr); };
})(jQuery,'smartresize');
// usage:
$(window).smartresize(function(){
// code that takes it easy...
});