This question already has answers here:
Pass correct "this" context to setTimeout callback?
(6 answers)
Closed 6 years ago.
I have an event for click-and-hold on a dynamic element
var timeoutId = 0;
$(document).on('mousedown', '.createbtn', function(){
timeoutId = setTimeout(showNewInfoCreateDlg, 1000);
}).on('mouseup mouseleave', '.createbtn', function() {
clearTimeout(timeoutId);
});
and the function is "showNewInfoCreateDlg"
I need to know what is the id of the element that was clicked-and-held
function showNewInfoCreateDlg(){
alert($(this).attr('id'));
}
The function alerts "undefined"
Here is the jsfiddle for my problem:
JsFiddle
Explicitly bind it to the function:
var timeoutId = 0;
$(document).on('mousedown', '.createbtn', function(){
timeoutId = setTimeout(showNewInfoCreateDlg.bind(this), 1000);
}).on('mouseup mouseleave', '.createbtn', function() {
clearTimeout(timeoutId);
});
To clarify: The bind() function will, well, bind the value of its first argument to the this variable inside showNewInfoCreateDlg. This is called explicit binding.
Related
This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 4 years ago.
hi I want to use 'this' variable in setInterval in a jquery function
I write '// this code don't work' after don't worked line
(function($)
{
$.fn.rotate=function () {
var counter=0;
var timer=setInterval(function () {
counter++;
var transform='rotate('+counter+'deg)';
$(this).css('transform',transform); // this code dont work
if(counter>=300)
clearInterval(timer);
},1);
return this;
};
$('#socialNetworks i').rotate();
}(jQuery))
thanks Alot
Using the arrow function when defining the function maintains the this context in which the function has been called. Thus you would be able to access this inside the function correctly.
( $ => {
$.fn.rotate=function () {
var counter=0;
var timer=setInterval(function () {
counter++;
var transform='rotate('+counter+'deg)';
$(this).css('transform',transform); // this code dont work
if(counter>=300)
clearInterval(timer);
},1);
return this;
};
$('#socialNetworks i').rotate();
})(jQuery)
This question already has answers here:
Pass correct "this" context to setTimeout callback?
(6 answers)
Closed 5 years ago.
Here is my code.
document.getElementById("t-option").addEventListener("click", function () {
setTimeout(function () {
myFunction(this);
}, 1500)
});
I want "this" to return the "t-option". It is a radio button and I want to know each time which one has been called.
Maybe there is a complete alternative way to do this, I don't know.
This might help you.
function myFunction(self)
{
console.log(self);
}
var option = document.getElementById("t-option");
option.addEventListener("click", function(){
var self = this;
setTimeout(function() { myFunction(self);}, 1500);
});
<input type="checkbox" id="t-option">
This question already has answers here:
How can I pass a parameter to a setTimeout() callback?
(29 answers)
Pass correct "this" context to setTimeout callback?
(6 answers)
Closed 9 years ago.
I am trying to show a div of information on a bar graph if the user hovers over the bar for a second. The answers on this site have gotten me to this point
var timer;
$(".session_hover").on({
'mouseover': function () {
timer = setTimeout(function () {
$(this).children('.session_info').css({'top':175,'right':20}).fadeIn('fast');
}, 1000);
},
'mouseout' : function () {
clearTimeout(timer);
}
});
The above code works when I replace $(this) with $(".session_hover") but then, of course it triggers all the other $(".session_hover") on the page.
How can I pass $(this) into my setTimeout function so that it only applies to the child element of the div I am hovering over?
Thanks for your help!
Try creating a closure around a variable to capture $(this), and then use it in your function:
'mouseover': function () {
var $this = $(this);
timer = setTimeout(function () {
$this.children('.session_info').css({'top':175,'right':20}).fadeIn('fast');
}, 1000);
},
Note that in modern browsers, you can also provide this as a parameter to setTimeout, like this:
'mouseover': function () {
timer = setTimeout(function (t) {
$(t).children('.session_info').css({'top':175,'right':20}).fadeIn('fast');
}, 1000, this);
},
However, if you want this to work in IE < 9, you need to use one of the polyfill techniques described in this MDN article.
Like this:
var timer;
$(".session_hover").on({
var self = this;
'mouseover': function () {
timer = setTimeout(function () {
$(self).children('.session_info').css({'top':175,'right':20}).fadeIn('fast');
}, 1000);
},
'mouseout' : function () {
clearTimeout(timer);
}
});
You need to hold a reference to this outside the setTimeout.
var timer;
$(".session_hover").on({
'mouseover': function () {
var ctx = this;
timer = setTimeout(function () {
$(ctx).children('.session_info').css({'top':175,'right':20}).fadeIn('fast');
}, 1000);
},
'mouseout' : function () {
clearTimeout(timer);
}
});
Another alternative is to use bind which is part of ECMAScript 5 (IE9+).
var timer;
$(".session_hover").on({
'mouseover': function () {
timer = setTimeout((function () {
$(this).children('.session_info').css({'top':175,'right':20}).fadeIn('fast');
}).bind(this), 1000);
},
'mouseout' : function () {
clearTimeout(timer);
}
});
Here's a demo using Bind
This question already has answers here:
Pass correct "this" context to setTimeout callback?
(6 answers)
Closed 9 years ago.
I have a piece of javascript code:
var intervalId;
intervalId = setInterval(fetchData, 2000);
$('.campaign-select li').on("click", "a", function(event)
{
window.clearInterval(intervalId);
intervalId = setInterval(fetchData_id($(this).data('campaign-id')), 2000);
});
The first setInterval was correct, the function fetchData is correctly loaded each 2 seconds.
But when I click the .campaign-select li a element, the fetchData_id is executed but only once, not repeated as expected with setInterval.
Any help?
Thanks.
You can't pass parameter in the setInterval function.
That being said, you should try this :
$('.campaign-select li').on("click", "a", function(event){
window.clearInterval(intervalId);
var $this = $(this)
intervalId = setInterval(function(){
fetchData_id($this.data('campaign-id'))
}), 2000);
});
This question already has answers here:
How to removeEventListener that is addEventListener with anonymous function?
(5 answers)
Closed 10 years ago.
Is there any possibility to unbind anonymous callback function ...
link.addEventListener("click", function () {
//Any piece of code
}, true);
link.removeEventListener("click", function () {
//Any piece of code
});
Thanks,
Ajain
No. Because those to anonymouse functions are actually different. It is the same reason why { a: 1 } === { a: 1 } returns false.
You need to do the following:
var func = function () { ... };
element.addEventListener( 'click', func, false );
element.removeEventListener( 'click', func, false );
Yes. You can do this by saving a handle to the anonymous event handler function somewhere using arguments.callee and later using this saved reference to unbind the same.
// binding
var el = document.getElementById('foo');
el.addEventListener('click', function(e) {
alert('Hi');
// this is where we save a handle to the anonymous handler
// arguments.callee gives us a reference to this function
el['_ev'] = arguments.callee;
}, false);
// unbinding
var el = document.getElementById('foo'), handler = el['_ev'];
if(handler) {
// here we use the saved reference to unbind it
el.removeEventListener('click', handler);
el['_ev'] = false;
}
Demo: http://jsfiddle.net/jrXex/2/
Functions are identified by pointer. You have no pointer to your anonymous function, so you have nothing to pass to remove() to tell it which function to remove.
Simply passing a duplicate function doesn't do it, because the duplicate has a different pointer.
You need to stick with assigning the function to a variable, then passing that variable to remove().