Passing $(this) to jQuery .hover() functions - javascript

I wrote a simple tooltip functionality, to be seen here.
The thing is, in both handler functions set in .hover() I need access to $(this) and other 2 variables based on it. In order do achieve that, I declare the same 3 variables in both handlers:
$('a').hover(
function () {
var $this = $(this);
var link_offset = $this.offset();
var link_tooltip = $this.data('tooltip');
// Rest of the code
},
function () {
var $this = $(this);
var link_offset = $this.offset();
var link_tooltip = $this.data('tooltip');
// Rest of the code
}
);
DRY principle should be respected, so my question is: Is there other and smarter/less dirty way of passing the same variables set to both functions within .hover()?
Obvioulsy, the variables can't be global (and globals are evil anyway).
Any ideas how to achieve this with jQuery or pure JS?

Call one named function inside the anonymous callbacks:
$('a').hover(function() {
hoverFunc($(this), true)
}, function() {
hoverFunc($(this), false)
});
function hoverFunc($this, is_hovered) {
var link_offset = $this.offset();
var link_tooltip = $this.data('tooltip');
if (is_hovered) {
console.log('ok')
// do something
} else {
console.log('out')
// do something else
};
}
http://jsfiddle.net/mblase75/8njk2m32/

Related

What is the best way for defining functions in loops? - JavaScript

I want to know which way for defining functions in loops is better? I always use the first way. Is it correct? or there is another way for this case?
Please guide me, I use the first way a lot in my codes, I wonder if it is true?
$('.elements').each(function(){
// elements
var $t = $(this), $anotherEl = $t.find('.el2'), $anotherEl2 = $t.find('.el3');
// variables
var isVisble = $t.is(':visible'), isLand = $t.hasClass('.land');
function doSomething(){
$t.width($anotherEl.width() + $anotherEl2.width());
// other codes ...
}
doSomething();
$(window).resize(doSomething);
});
or
function doSomething(par1, par2, par3, par4){
var $t = par1 , $anotherEl = par2, $anotherEl2 = par3;
$t.width($anotherEl.width() + $anotherEl2.width());
// other codes ...
}
$('.elements').each(function(){
// elements
var $t = $(this), $anotherEl = $t.find('.el2'), $anotherEl2 = $t.find('.el3');
// variables
var isVisble = $t.is(':visible'), isLand = $t.hasClass('.land');
doSomething($t, $anotherEl, $anotherEl2, isLand);
$(window).resize(function(){
doSomething($t, $anotherEl, $anotherEl2, isLand);
});
});
Thanks for advance.
Why doing this in loops? As this can be done without using loops like:
function doSomething(){
$('.elements').each(function(){
// elements
var $t = $(this), $anotherEl = $t.find('.el2'), $anotherEl2 = $t.find('.el3');
// variables
var isVisble = $t.is(':visible'), isLand = $t.hasClass('.land');
// now do something with the vars here.
});
}
$(window).resize(doSomething).resize(); // <---trailing .resize() triggers on dom ready.
Problems i see with your approach are:
Using .each() loop defining same function again and again, executing same function and binding resize event in each iteration.
Second one seems a bit better but partially because of .resize bindings.

What does Jquery.Recup mean?

well i'm confuse about the line witch says "$.Recup ..." I don't know why it is named the same as the plugin name and what it's for.
(function ($) {
$.fn.Recup = function () {
var parametros = {
};
var tsic = true;
$.Recup = function (opciones) {
var Metodos = {
};
return Metodos;
};
$.Recup.anterior = function () {
};
$.Recup.siguiente = function () {
}
})(jQuery);
I'm refering to this code, What does $.Recup exactly do?it would be perfect if someone gives me an example please
$.Recup = function (opciones) {
var Metodos = {
};
return Metodos;
};
In this case it appears to be a questionable plugin design - especially since $.Recup is not assigned until $.fn.Recup is first called.
However, if it is "appropriately and/or well written" is another question that requires context of (intended) usage. For what it is worth, I would reject this code as written as it smells of misunderstood design and widely scoped side-effects.
Anyway, the way the function is assigned determines how the method can be called.
// let $ be jQuery, then:
$.fn.foo = function () { console.log("foo") }
$.bar = function () { console.log("bar") }
$.foo() // TypeError: $.foo is not a function
$.bar() // -> "bar"
$("sel").foo() // -> "foo"
$("sel").bar() // TypeError: $(..).bar is not a function
That is, $.fn.foo is like .each() - it does something based on the currently selected elements (which are represented by this). On the other hand, $.bar is like jQuery.each() - it provides a way to iterate over a general collection but is not related to a specific set of (previously) selected elements.
In general, a plugin should only add a single entry to $.fn, but directly adding to $ may be useful to expose utility functions - it should definitely be done with care.
Here are two approaches that fix the issue of incorrectly leaked data:
$.fn.Recup = function () {
var parametros = ..
var tsic = true;
// Most trivial change; then use recup in this scope
// (or child scopes) only. There is no $.Recup - yay!
var recup = function (opciones) {
};
// ..
}
Or, just expose as local methods:
$.fn.Recup = function () {
var parametros = ..
var tsic = true;
function anterior () {
}
function siguiente () {
}
// Just use simple functions in scope
}
This is a jQuery plugin.
jQuery.fn is an alias to jQuery's prototype. So this line lets you call the Recup function on instances of jQuery :
$('#myid').Recup();
Here's the documentation on creating jQuery plugins.

cannot access function within function in javascript

I need to know what I am doing wrong because I cannot call the internal functions show or hide?
(function()
{
var Fresh = {
notify:function()
{
var timeout = 20000;
$("#notify-container div").get(0).id.substr(7,1) == "1" && (show(),setTimeout(hide(),timeout));
var show = function ()
{
$("body").animate({marginTop: "2.5em"}, "fast", "linear");
$("#notify-container div:eq(0)").fadeIn("slow");
},
hide = function()
{
$("#notify-container div").hide();
}
}//END notify
}
window.Fresh = Fresh;
})();
Fresh.notify();
thanks, Richard
UPDATE
If you wanted to be able to do something like: Fresh.notify.showMessage(), all you need to do is assign a property to the function notify:
var Fresh = {notify:function(){return 'notify called';}};
Fresh.notify.showMessage = function () { return this() + ' and showMessage, too!';};
Fresh.notify();//notify called
Fresh.notify.showMessage();//notify called and showMessage, too!
This will point to the function object here, and can be called as such (this() === Fresh.notify();). That's all there is too it.
There's a number of issues with this code. First of all: it's great that you're trying to use closures. But you're not using them to the fullest, if you don't mind my saying. For example: the notify method is packed with function declarations and jQuery selectors. This means that each time the method is invoked, new function objects will be created and the selectors will cause the dom to be searched time and time again. It's better to just keep the functions and the dom elements referenced in the closure scope:
(function()
{
var body = $("body");
var notifyDiv = $("#notify-container div")[0];
var notifyDivEq0 = $("#notify-container div:eq(0)");
var show = function ()
{
body.animate({marginTop: "2.5em"}, "fast", "linear");
notifyDivEq0.fadeIn("slow");
};
var hide = function()
{//notifyDiv is not a jQ object, just pass it to jQ again:
$(notifyDiv).hide();
};
var timeout = 20000;
var Fresh = {
notify:function()
{
//this doesn't really make sense to me...
//notifyDiv.id.substr(7,1) == "1" && (show(),setTimeout(hide,timeout));
//I think this is what you want:
if (notifyDiv.id.charAt(6) === '1')
{
show();
setTimeout(hide,timeout);//pass function reference
//setTimeout(hide(),timeout); calls return value of hide, which is undefined here
}
}//END notify
}
window.Fresh = Fresh;
})();
Fresh.notify();
It's hard to make suggestions in this case, though because, on its own, this code doesn't really make much sense. I'd suggest you set up a fiddle so we can see the code at work (or see the code fail :P)
First, you're trying to use show value when it's not defined yet (though show variable does exist in that scope):
function test() {
show(); // TypeError: show is not a function
var show = function() { console.log(42); };
}
It's easily fixable with moving var show line above the point where it'll be called:
function test() {
var show = function() { console.log(42); };
show();
}
test(); // 42
... or if you define functions in more 'traditional' way (with function show() { ... } notation).
function test() {
show();
function show() { console.log(42); };
}
test(); // 42
Second, you should use this instead:
... && (show(), setTimeout(hide, timeout) );
... as it's the function name, and not the function result, that should be passed to setTimeout as the first argument.
You have to define show and hide before, also change the hide() as they said.
The result will be something like this:
(function()
{
var Fresh = {
notify:function()
{
var show = function()
{
$("body").animate({marginTop: "2.5em"}, "fast", "linear");
$("#notify-container div:eq(0)").fadeIn("slow");
},
hide = function()
{
$("#notify-container div").hide();
},
timeout = 20000;
$("#notify-container div").get(0).id.substr(7,1) == "1" && ( show(), setTimeout(hide,timeout) );
}//END notify
}
window.Fresh = Fresh;
})();
Fresh.notify();
I think order of calling show , hide is the matter . I have modified your code . It works fine . Please visit the link
http://jsfiddle.net/dzZe3/1/
the
(show(),setTimeout(hide(),timeout));
needs to at least be
(show(),setTimeout(function() {hide()},timeout));
or
(show(),setTimeout(hide,timeout));

prototype this selector

If I'm using the following function :
clusters.prototype.shop_iqns_selected_class = function() {
if(this.viewport_width < 980) {
$(this.iqns_class).each(function() {
$(this.iqn).on('click', function() {
if($(this).hasClass('selected')) {
$(this).removeClass('selected');
} else {
$(this).addClass('selected');
}
});
});
}
}
To add a property to the clusters function, I know that using this.viewport_width I'm referring to the parent function where I have this.viewport_width defined, but when I'm using the jQuery selector $(this), am I referring to the parent of the $.on() function ?
In JavaScript, this is defined entirely by how a function is called. jQuery's each function calls the iterator function you give it in a way that sets this to each element value, so within that iterator function, this no longer refers to what it referred to in the rest of that code.
This is easily fixed with a variable in the closure's context:
clusters.prototype.shop_iqns_selected_class = function() {
var self = this; // <=== The variable
if(this.viewport_width < 980) {
$(this.iqns_class).each(function() {
// Do this *once*, you don't want to call $() repeatedly
var $elm = $(this);
// v---- using `self` to refer to the instance
$(self.iqn).on('click', function() {
// v---- using $elm
if($elm.hasClass('selected')) {
$elm.removeClass('selected');
} else {
$elm.addClass('selected');
}
});
});
}
}
There I've continued to use this to refer to each DOM element, but you could accept the arguments to the iterator function so there's no ambiguity:
clusters.prototype.shop_iqns_selected_class = function() {
var self = this; // <=== The variable
if(this.viewport_width < 980) {
// Accepting the args -----------v -----v
$(this.iqns_class).each(function(index, elm) {
// Do this *once*, you don't want to call $() repeatedly
var $elm = $(elm);
// v---- using `self` to refer to the instance
$(self.iqn).on('click', function() {
// v---- using $elm
if($elm.hasClass('selected')) {
$elm.removeClass('selected');
} else {
$elm.addClass('selected');
}
});
});
}
}
More reading (posts in my blog about this in JavaScript):
Mythical methods
You must remember this
Don't use this all throughout the code. Methods like $.each give you another reference:
$(".foo").each(function(index, element){
/* 'element' is better to use than 'this'
from here on out. Don't overwrite it. */
});
Additionally, $.on provides the same via the event object:
$(".foo").on("click", function(event) {
/* 'event.target' is better to use than
'this' from here on out. */
});
When your nesting runs deep, there's far too much ambiguity to use this. Of course another method you'll find in active use is to create an alias of that, which is equal to this, directly inside a callback:
$(".foo").on("click", function(){
var that = this;
/* You can now refer to `that` as you nest,
but be sure not to write over that var. */
});
I prefer using the values provided by jQuery in the arguments, or the event object.

jQuery binding function on focus

I'm writing a little plugin for jQuery and so far I've got this:
(function($){
$.fn.extend({
someFunction: function() {
return this.each(function() {
var obj = $(this);
obj.focus(someInternalFunction(obj));
});
}
});
function someInternalFunction(obj) {
};
})(jQuery);
The problem is, when i attach someFunction to the object, the object gets focus and binding of someInternalFunction on focus event fails.
Then I tried to bind function to wrap the function call in the other function:
obj.focus(function() {
someInternalFunction($(this));
});
This code works, but it isn't pretty at all. Is it possible to bind function on focus without wrapping it in the other function?
$.fn.bindFocus() = function(){
var internalFunction = function(){
var $this = $(this),
self = this;
// try do stuff here
};
return this.each(function(){
$(this).bind('focus', internalFunction);
});
}
$('#myElement').bindFocus();
Hope it'll help ?
EDT. Sorry, first time get you wrong :)
Here:
obj.focus(someInternalFunction(obj));
^^^^^
... you're calling the function, meaning that its return value is the thing that actually ends up being passed to focus(). Instead you want to pass a function to focus(). Given the fact that you want to pass obj to someInternalFunction, you'll have to define an additional function to wrap it all:
obj.focus(function(){
someInternalFunction(obj);
});
Just to make things clear:
var x = function() { return 3; }; // Defining a function
x; // -> this is a function reference
x(); // -> this is 3

Categories

Resources