Javascript .setTimeout() how to refer to a function - javascript

I have these codes:
$(function(){
$('.btn').click(function(){
$title = $(this).attr('title');
$.get('getOutput', {}, function(){
// success ajax get
// how to refer again to this function? Doing again the $('.btn').click event
setTimeout(// $('.btn').click(), 100);
});
});
})
I want to repeat the click event of the button. But my main question is, how would you refer the right function or event in setTimeout() ??

You can wrap it into an anonymous function.
setTimeout(function() {
$('.btn').click();
}, 100);
In case you want to trigger the event in the specific element you've clicked before, you'll need to store the current element in a variable since this value inside the anonymous function would be different.
$('.btn').click(function() {
var $el = $(this);
// ...your code...
setTimeout(function() {
$el.click();
}, 100);
});

You could wrap the time out call back in an anonymous function and just real call the click function in there.
setTimeout(function() {
$(".btn").click();
}, 100);

You can bind this inside the anonymous function with $.proxy() to be compatible with IE8 or use .bind() for modern browers.
setTimeout($.proxy(function(){
// this.click(); // if this = $(".btn")
}, this), 100);
To explain it properly:
$(function(){
var btn = $('.btn');
btn.click(function(ev){
var el = $(ev.currentTarget), // same as $(this) but too many "thisses" can be confusing ^^
title = el.prop('title');
$.get('getOutput', {}, function(){
// success ajax get
// how to refer again to this function? Doing again the $('.btn').click event
setTimeout($.proxy(function(){
this.click();
}, el), 100);
});
});
});

Instead of triggering the click event again, you may be better off naming the click event handler function and calling it again from within your setTimeout.
var handleButtonClick = function() {
$title = $(this).attr('title');
$.get('getOutput', {}, function() {
// success ajax get
setTimeout(handleButtonClick , 100);
});
};
$(function() {
$('.btn').click(handleButtonClick);
});

Related

How to set a jquery on() function only if it doesn't already existis?

I'm calling via ajax additional content where I add a jquery on() function for a click event. Each time I renew the content the event is also set again so at the end it get executed several times. How can I avoid this behavior?
How do I test if the click event is already set on the document?
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Click
<script>
// first ajax load
$(document).on('click', '.open-alert', function () {
alert('hello world!');
});
// second ajax load
$(document).on('click', '.open-alert', function () {
alert('hello world!');
});
</script>
I already try to just the jQuery.isFunction(), but I don't anderstand how to apply it in this case.
You can Unbind the click event , if you getting more than one time exectuated.
$(document).unbind('click').on("click", ".open-alert", function () {
//do stuff here
});
Or you can also use it
$(document).off("click", ".open-alert").on("click", ".open-alert", function () {
});
Using
$(document).on('click', '#element_id', function() {
//your code
});
Will check the DOM for matching elements every time you click (usually used for dynamically created elements with ajax)
But using
$('#element_id').on('click', function() {
//your code
});
Will only bind to existing elements.
If you use the 1st example, you only need to call it once, you can even call it before your ajax call since it will recheck for matching elements on each click.
<script>
$(document).on('click', '.open-alert', function () {
alert('hello world!');
});
// first ajax load
// second ajax load
...
</script>
In case you cannot bind the event to the specific DOM element (which might happen if you use Turbolinks for example) you can use a variable to check whether you set the event or not.
Local scope
var clickIsSet = false;
// any ajax load
$(document).on('click', '.open-alert', function () {
if ( clickIsSet ) {
alert('hello world!');
clickIsSet = true;
}
});
Global scope
I don't recommend to make clickIsSet global, but in case you are importing/exporting modules you can do that:
// main.js
window.clickIsSet = false;
// any-other-module.js
$(document).on('click', '.open-alert', function () {
if ( window.clickIsSet ) {
alert('hello world!');
window.clickIsSet = true;
}
});
jQuery check if event exists on element : $._data( $(yourSelector)[0], 'events' )
this return all of element events such : click , blur ,
focus,....
Important Note: $._data when worked that at least an event bind to element.
so now:
1.in your main script or first ajax script bind click event on element
<script>
$(document).on('click', '.open-alert', function () {
alert('hello world!');
});
</script>
2. in secound ajax:
var _data = $._data( $('.open-alert')[0], 'events' );
if(typeof _data != "undefined"){
var eventClick = $._data( $('.open-alert')[0], 'events' ).click
var hasEventClick = eventClick != null && typeof eventClick != "undefined";
if(!hasEventClick){
$(document).on('click', '.open-alert', function () {
alert('hello world!');
});
}
}
I get Confuse about your question but as far as understand your question I have three suggestions:
Use Id element (as #Mokun write the answer)
Use Common Function for call functionality instead use through the click event.(Make Sure of function does not overwrite your content by calling).
Use of flag variable (or global variable for your tracking event) in jquery and identify your function call for particular execution.

jQuery : $("#id") doesn't work in a function

I've a problem with my jQuery function.
This code works:
$("input.read_picture").on('keyup', function () {
$("#load_picture").attr('src', $(this).val());
$("#load_picture").error(function(){
$(this).attr('src', 'http://www.rnc-ci.net/images/joomlart/demo/default.jpg');
});
$("#show_picture").css('display', 'block');
});
But when I want to store my function not into my jQuery event, it doesn't work. Nothing displays.
Here is the code that doesn't work:
function changePicture(url) {
$("#load_picture").attr('src', url);
$("#load_picture").error(function(){
$(this).attr('src', 'http://www.rnc-ci.net/images/joomlart/demo/default.jpg');
});
$("#show_picture").css('display', 'block');
}
$("input.read_picture").on('keyup', changePicture($(this).val()));
Thanks for your help!
This,
$("input.read_picture").on('keyup', changePicture($(this).val()));
will call the function as soon as handler is loaded.
Use a callback,
$("input.read_picture").on('keyup', function(){
changePicture($(this).val())
});
jQuery .on handler expects function as a second argument. You are invoking function, not passing it as argument. Invoked function does not return anything hence undefined is being passed as handler function.
Instead of calling a function, just pass function name which hold function definition. You can access value in the function body as this.value or $(this).val() as this refers to DOM-Element on which event is invoked.
function changePicture() {
var url = this.value;
$("#load_picture").attr('src', url);
$("#load_picture").error(function() {
$(this).attr('src', 'http://www.rnc-ci.net/images/joomlart/demo/default.jpg');
});
$("#show_picture").css('display', 'block');
}
$("input.read_picture").on('keyup', changePicture);
Or with your current implementation, changePicure must return a function to be invoked as a handler function for keyup
function changePicture(url) {
return function() {
$("#load_picture").attr('src', url);
$("#load_picture").error(function() {
$(this).attr('src', 'http://www.rnc-ci.net/images/joomlart/demo/default.jpg');
});
$("#show_picture").css('display', 'block');
};
}
$("input.read_picture").on('keyup', changePicture('ANY_VALUE AS $(this).val() will not wors due to invalid context of this'));

Javascript clearInterval with button click

I'm having issues getting clearInterval to work when I try to bind it to a button click. Also, apparently the function is starting on it's own... Here's my code
var funky = setInterval(function() {
alert('hello world');
}, 2000);
$('#start').click(function() {
funky();
});
$('#stop').click(function() {
clearInterval(funky);
});
Here's a js fiddle
You have forgot to add jquery library and have made wrong assignment, it needs to be inside callback function.
Working example:
var funky;
$('#start').click(function() {
funky = setInterval(function() {
alert('hello world');
}, 2000);
});
$('#stop').click(function() {
clearInterval(funky);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="start">start</button>
<button id="stop">stop</button>
First off, yes, when you assign a variable to a function, it self invokes.
Secondly, your click events are not working because you need assign the interval to the variable on the click, not invoke the function - there is no function to invoke, as you would see if you looked at your developer console.
Lastly, it is good practice to wrap the jQuery code in the document ready function to ensure all of your event handlers get bound properly.
$(function () {
var funky;
$('#start').click(function() {
funky = setInterval(function() {
alert('hello world');
}, 1000);
});
$('#stop').click(function() {
clearInterval(funky);
});
});
You're saving the wrong value. Try this:
var funky = function() {
alert('hello world');
}
var funkyId = setInterval(funky, 2000);
$('#start').click(function() {
funky();
});
$('#stop').click(function() {
clearInterval(funkyId);
});
Here I am giving you the idea.
declare a variable e.g. let x;
create a function which you want to bind with setInterval.
e.g.
function funky() {
alert("Hello World");
}
assign start.onclick to a function which will assign the setInterval to x.
e.g start.onclick = function(){
clearInterval(x); // to prevent multiple interval if you click more than one
x = setInterval(funky, 2000); // assign the setInterval to x
};
assign stop.onclick to clearInterval(x) to stop the interval.
e.g. stop.onclick = function() {
clearInterval(x); // to stop the interval
};
That's it. Easy right.

Binding 'this' and getting this

$('.btn-delete').on('click', this.confirm.bind(this));
Above, on click it runs:
p.confirm = function(e) {
if(!$(this).hasClass('danger')){
$(this).addClass('danger');
$(this).bind('mouseleave',function(){
$(this).removeClass('danger');
$(this).unbind('mouseleave');
});
}
else{
this.delete();
}
};
I'm having trouble with this. I need this to get the button but I also need this to access another method (this.delete). I've tried bind but it faisl to work.
Any ideas?
Assuming I'm understanding your question correctly, you want to be able to pass the clicked element as this to the p.confirm function. You should be able to do this by using call, or by using p.confirm as the handler:
// using call
$('.btn-delete').on('click', function (e) {
p.confirm.call(this, e);
});
// as handler
$('.btn-delete').on('click', p.confirm);
Assuming that this.delete is actually p.delete, just use call in the handler to pass the clicked element as this to the delete method:
p.confirm = function (e) {
var self = $(this); // cache lookup, "this" is the clicked element
if (!self.hasClass('danger')) {
self.addClass('danger');
self.bind('mouseleave', function () {
self.removeClass('danger');
self.unbind('mouseleave');
});
} else {
p.delete.call(this); // pass clicked element to use as "this" in p.delete
}
};

How to attach Event Listeners to only newly created elements?

When I fire a function I want it to apply listeners just to elements I pass, particular this jQuery element.
addEventListeners(this);
function addEventListeners(el) {
$(el).mouseenter(function() {
$(this).stop(true,true).switchClass("", "HIGHLIGHT", 400, "easeInOutQuad");
});
$(el).mouseleave(function() {
$(this).stop(true,true).switchClass("HIGHLIGHT", "", 400, "easeInOutQuad");
});
}
It fires from AJAX result:
$.post(url,{el:wartosc_inputa},function(returned) {
var data = $(returned).hide();
$("#listaElementow").prepend(data);
data.slideDown();
loading();
addEventListeners(this);
});
How to code it good? This code is not passing variables from addEventListeners(this); to function.
in the ajax callback function "this" will be the ajax object i think and no longer an element so you need to save "this" in a variable before the ajax starts.
that = this;
$.post(url,{el:wartosc_inputa},function(returned) {
var data = $(returned).hide();
$("#listaElementow").prepend(data);
data.slideDown();
loading();
addEventListeners(that);
});
Judging from the context of the rest of your success handler, I assume returned is the DOM element you're attempting to bind your handlers to. Assuming this is the case:
$.post(url,{el:wartosc_inputa},function(returned) {
var data = $(returned).hide();
$("#listaElementow").prepend(data);
data.slideDown();
loading();
addEventListeners(data[0]);
// change this ^^^^
// pass the DOM element here, or
// change the addEventListeners function to take a jquery element
});
this in that context is not what you expect it to be. Try this:
var self = this;
$.post(url,{el:wartosc_inputa},function(returned) {
var data = $(returned).hide();
$("#listaElementow").prepend(data);
data.slideDown();
loading();
addEventListeners(self);
});

Categories