Quick Description:
I'm aware that using $(this) in a function won't work because it's not within the right scope. I've also seen other similar questions. I just still can't figure out how to fix my scenerio.
Goal: I'm trying to build a panoramic photo viewer with jQuery. I have it working, but I need multiple instances. So I need to target only the one I'm hovering on.
Code:
jsFiddle: http://jsfiddle.net/kthornbloom/5J3rh/
Simplified Code:
var hoverInterval;
function doStuff() {
/* The next line is the one in question */
$(this).animate({
/* stuff happening */
});
}
$(function() {
$('.pan-wrap').hover(
function() {
/* stuff happening */
hoverInterval = setInterval(doStuff, 250);
},
function() {
clearInterval(hoverInterval);
});
});
You have scope issues, this in the doStuff is window context.
Use proxy()
hoverInterval = setInterval($.proxy(doStuff,this), 250);
You can explicitly pass this into doStuff:
setInterval(function() {
doStuff(this);
}, 250);
And in doStuff you can do:
function doStuff(element) {
...
}
Or you can explicitly set the value of this for doStuff like so:
setInterval(function() {
doStuff.call(this);
}, 250);
Then you can still use $(this) inside doStuff without changing any of its arguments. For more information on call, see Function.prototype.call and its friend Function.prototype.apply.
Related
Wow.. to get real information about 'this' is not easy as google basically ignores the word.
The code opens an image from a database using the information from thumbnail.. the onlick works, and the hover code works, but I can't figure out how to get 'this' from the mouseenter to be used in the showModal function.
function showModal() {
$("body").css("overflow-y", "hidden");
$(".small").removeClass("smallHover");
$(".modal").fadeIn(200);
var altLong = $(this).attr("alt");
var altSplit = altLong.split("#");
$(".picTitle").text(altSplit[0]);
var srclong = $(this).attr("src");
var srcshort = srclong.split("_");
var srcextension = srclong.split(".");
$(".big").attr("src", srcshort[0]+'.'+srcextension[1]);
}
$(".small").click(showModal);
var timer;
$(".small").mouseenter(function() {
timer = setTimeout(function(){
$(this).showModal(); // **<--this is the line that doesnt work**
}, 2000);
}).mouseleave(function() {
clearTimeout(timer);
});
also if you could explain why you would use $(this) as a jquery object instead of just 'this' and how they differ, that would be great. Thanks in advance~!
There are two separate aspects to this.
Getting the right this in the setTimeout callback
Calling showModal with that this
#1 is addressed by this question's answers. You have several options, the simplest in this case (for now) probably being to use a variable:
$(".small").mouseenter(function() {
var _this = this; // ***
timer = setTimeout(function(){
$(_this).showModal(); // ***
}, 2000);
}).mouseleave(function() {
clearTimeout(timer);
});
...but that code still won't work, because showModal isn't a property of jQuery objects, it's a standalone function. To call it with a specific this, you'd use Function.prototype.call:
$(".small").mouseenter(function() {
var _this = this;
timer = setTimeout(function(){
showModal.call(_this); // ***
}, 2000);
}).mouseleave(function() {
clearTimeout(timer);
});
(Alternately, change showModal to accept the element as a parameter and then just pass it as an argument.)
More on this in this question's answers as well, as well as this (old) post on my anemic little blog.
this will also work if you could change your showModel function like this :
$.fn.showModal = function() {
$("body").css("overflow-y", "hidden");
$(".small").removeClass("smallHover");
$(".modal").fadeIn(200);
...
}
and inside timer method
$(this).showModal();
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 was trying to organize my jquery code so i created an object literal, but now the focusTextArea is not working and my textarea value is not updating.
Thanks for your help.
html
<textarea id="test"></textarea>
javascript
(function($,window,document,undefined){
var TEX = {
inputField: $("textarea#test"),
/* Init all functions */
init: function()
{
this.focusTextArea();
},
/* Function update textarea */
focusTextArea: function()
{
this.inputField.text('test');
},
}
$(document).ready(function(){
TEX.init();
});
})(jQuery,window,document);
jsfiddle
http://jsfiddle.net/vBvZ8/1/
First of all, you haven't included jQuery correctly in the fiddle. Also, I think you mean to place the code in the head of the document (because of the document.ready handler).
More importantly perhaps the selector $("textarea#test") is run before the document is ready and therefore won't actually find the element correctly. I would recommend assigning inputField in TEX.init:
(function($,window,document,undefined){
var TEX = {
/* Init all functions */
init: function()
{
this.inputField = $("#test");
this.focusTextArea();
},
/* Function update textarea */
focusTextArea: function()
{
this.inputField.text('test');
},
}
$(document).ready(function(){
TEX.init();
});
})(jQuery,window,document);
Updated example: http://jsfiddle.net/xntA2/1/
As a side note, textarea#test should be changed to just #test. The textarea bit is superfluous since there should be only one element on the page with id=test.
Alternative syntax to avoid looking for an element before it exists is to return the element from a function:
(function($,window,document,undefined){
var TEX = {
/* function won't look for element until called*/
inputField:function(){
return $("textarea#test")
},
init: function()
{
this.focusTextArea();
},
focusTextArea: function()
{
this.inputField().text('test');
},
}
$(document).ready(function(){
TEX.init();
});
})(jQuery,window,document);
DEMO: http://jsfiddle.net/vBvZ8/5/
I realize this is a simplified example...but you are also very close to creating a jQuery plugin and that may also be of benefit. Following provides same functionality as example:
(function($, window, document, undefined) {
$.fn.focusTextArea = function() {
return this.each(function(){
$(this).text('test');
})
};
})(jQuery, window, document);
$(function() {
$('textarea').focusTextArea()
});
DEMO: http://jsfiddle.net/vBvZ8/8/
Sorry for how stupid this is going to sound. My JS vocabulary is terrible and I had absolutely no idea what to search for.
I'm using jQuery.
So I've got this code:
var example = {
open: function(element){
alert(element.text());
},
init: function(){
$("a").click(example.open);
}
};
$(document).ready(function(){example.init();)
So here's the problem: I want to pass an argument to example.open() when I click the "a" element. It doesn't seem like I can, though. In order for the example.open method to just…exist on page-load and not just run, it can't have parentheses. I think. So there's no way to pass it an argument.
So I guess my question is…how do you pass an argument to a function that can't have parentheses?
Thanks so much.
Insert another anonymous function:
var example = {
open: function(element){
alert(element.text());
},
init: function(){
$("a").click(function()
{
example.open($(this));
});
}
};
You can also try this version because jQuery set the function's context (this) to the DOM element:
var example = {
open: function(){
alert($(this).text());
},
init: function(){
$("button").click(example.open);
}
};
Since jQuery binds the HTML element that raised the event into the this variable, you just have to pass it as a regular parameter:
var example = {
open: function(element){
alert(element.text());
},
init: function(){
$("a").click(function() {
// jQuery binds "this" to the element that initiated the event
example.open(this);
});
}
}
$(document).ready(function(){example.init();)
You can pass the anchor through its own handler:
var example = {
open: function( element ){
alert(element.text());
},
init: function(){
$("a").on("click", function() {
example.open( $(this) );
});
}
};
$(document).ready(function() {
example.init();
});
I don't understand what you actually want to do;
however, I can give a try:
var example = {
open: function(event){
event.preventDefault();
alert($(event.target).text()+' : '+event.data.x);
},
init: function(){
$("a").bind('click',{x:10},example.open);
}
};
$(example.init);
demo:
http://jsfiddle.net/rahen/EM2g9/2/
Sorry, I misunderstood the question.
There are several ways to handle this:
Wrap the call in a function:
$('a').click( function(){ example.open( $(this) ) } );
Where $(this) can be replaced by your argument list
Call a different event creator function, which takes the arguments as a parameter:
$('a').bind( 'click', {yourvariable:yourvalue}, example.open );
Where open takes a parameter called event and you can access your variable through the event.data (in the above it'd be event.data.yourvariable)
Errors and Other Info
However your element.text() won't just work unless element is a jQuery object. So you can jQueryify the object before passing it to the function, or after it's received by the function:
jQuery the passed object:
function(){ example.open(this) } /* to */ function(){ example.open($(this)) }
jQuery the received object:
alert(element.text()); /* to */ alert($(element).text());
That said, when calling an object without parameters this will refer to the object in scope (that generated the event). So, really, if you don't need to pass extra parameters you can get away with something like:
var example = {
open: function(){ // no argument needed
alert($(this).text()); // this points to element being clicked
},
init: function(){
$("a").click(example.open);
}
};
$(document).ready(function(){
example.init();
}); // your ready function was missing closing brace '}'
I've got following JavaScript functions but want to refactor the $(document).ready() as I've got 2 instance of it. How can I achieve this?
FlashMessenger = {
init: function() {
setTimeout(function() {
$(".flash").fadeOut("slow", function () {
$(".flash").remove();
});
}, 5000);
}
}
SelectLanguage = {
init: function() {
$('#selectLanguageId').change(function() {
$('#frmSelectLanguage').submit();
});
}
}
$(document).ready(FlashMessenger.init);
$(document).ready(SelectLanguage.init);
It’s perfectly acceptable to set multiple handlers for $(document).ready, although you may have a good reason to do otherwise that I’m not aware of. You might be interested in knowing that $(handler) can be used as shorthand for $(document).ready(handler):
$(FlashMessenger.init);
$(SelectLanguage.init);
If you really want them in one call though, try this:
$(function() {
FlashMessenger.init();
SelectLanguage.init();
});
First off, there's no reason you have to combine them.
But if you want to:
$(document).ready(function(jq){
FlashMessenger.init(jq);
SelectLanguage.init(jq);
});
Breaking it down:
Create a function to do all your init (it can be named or anonymous; the one above is anonymous).
Have it call the other init functions, passing in the jQuery instance that jQuery passes you just in case they use it.
You might choose to wrap each init call in a try/catch block as well, so that errors in one init don't prevent the next init from occuring, but that depends on your needs.
Just combine them into one call with an anonymous function:
$(document).ready(function()
{
FlashMessenger.init();
SelectLanguage.init();
});
$(document).ready(function() {
FlashMessenger.init();
SelectLanguage.init();
});
Option 1
FlashMessenger = {
init: function() {
setTimeout(function() {
$(".flash").fadeOut("slow", function () {
$(".flash").remove();
});
}, 5000);
}
}
SelectLanguage = {
init: function() {
$('#selectLanguageId').change(function() {
$('#frmSelectLanguage').submit();
});
}
}
$(function(){
FlashMessenger.init();
SelectLanguage.init();
});
Option 2
FlashMessenger = {
init: function() {
setTimeout(function() {
$(".flash").fadeOut("slow", function () {
$(".flash").remove();
});
}, 5000);
}
}
SelectLanguage = {
init: function() {
$('#selectLanguageId').change(function() {
$('#frmSelectLanguage').submit();
});
}
}
$(document).ready(function(){
FlashMessenger.init();
SelectLanguage.init();
});
Option 3
You actually don't need those 2 objects since the only hold the init methods, so here's the ultimate solution, in my opinion, unless you use those objects elsewhere.
$(function(){
$('#selectLanguageId').change(function() {
$('#frmSelectLanguage').submit();
});
setTimeout(function() {
$(".flash").fadeOut("slow", function () {
$(".flash").remove();
});
}, 5000);
})
I prefer 2 and 3 for this reason.
I think what the op is saying is, "If in the future I have a third function to be invoked at document.ready, then how do I do it without touching that piece of code?"
If you do not want multiple $(document).ready() calls, you could just create an array called startupHooks and add each method to it:
startupHooks[ startupHooks.length ] = myNewStartupHook;
and your startup script could look like
$(document).ready(function() {
for( var i=0; i<startupHooks.length; i++ ) {
startupHooks[i]();
}
}
I know that is not mighty useful, but if that appeals to you, you can do it this way.
Personally, I'd go with multiple $(document).ready() calls.
Personally I'd go for not using document.ready at all.
If you place the scripts at the end of your html-page(just before the tag) you can just write in any way you like.
Maybe this doesn't work for 0.01% of the scripts but it never failed to work for me.
Positive effect of this is that the initial HTML+CSS rendering goes faster.
You can also read about it on yahoo. http://developer.yahoo.com/performance/rules.html#js_bottom