Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
2
rated 0 times [  9] [ 7]  / answers: 1 / hits: 21571  / 14 Years ago, wed, october 13, 2010, 12:00:00

I'm trying to use jQuery's $(this) inside of Fancybox's onComplete event, but I'm running into trouble. Here's my javascript code:



$('a.iframe').fancybox({  
centerOnScroll: true,
onComplete: function(){
var self = $(this);
var title = self.title;
alert(title.text());
}
});


I have simplified the code above to get my point across, but I actually would love to use $(this) for several reasons that I won't go into here.



Fancybox's documentation shows examples of using this instead of $(this)within its documentation, but I didn't see any examples where either were used inside of onComplete or other events. I of course tried using this, much to no avail.



Does anyone know how I can reference the triggered a.iframe element by using $(this) or any other means within the onComplete event?



Edit:
I got this to work using Blackcoat's suggestion, and here's the final syntax that worked:



$('a.iframe').fancybox({
centerOnScroll: true,
onComplete: function( links, index ){
var self = $(links[index]);
var title = self.find('.title').text();
alert(title);
}
});

More From » jquery

 Answers
17

Bitmanic,



Sadly, you're out of luck using this, but you can still reference the current link. Define your callback to accept an array of links selected by jQuery as its first parameter, and an index as the second parameter:



  $('a.iframe').fancybox({  
centerOnScroll: true,
onComplete: function( links, index ){
var self = $(links[index]);
var title = self.title;
alert(title.text());
}
});


Here's how Fancybox invokes the onComplete hander:



if ($.isFunction(currentOpts.onComplete)) {
currentOpts.onComplete(currentArray, currentIndex, currentOpts);
}


They aren't using Javascript's call or apply to invoke this function as a method of an object. In other words, this will refer to the global scope of your application (i.e. the document object), so you can't use it to refer back to the object being acted upon (shame on them). Instead, they pass three parameters to the callback for specifying context: currentArray (the selected object), currentIndex, and currentOpts.


[#95343] Saturday, October 9, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tyreese

Total Points: 739
Total Questions: 95
Total Answers: 98

Location: Belize
Member since Mon, Jun 20, 2022
2 Years ago
;