I have small problem with a submit button.. When it's clicked I want it to perform different actions, but two later than the other one. I have been trying to use a setTimeout from Javascript and place some of the actions I want it to perform in a different function, but then my code doesn't work anymore because it doesn't know what 'this' is anymore. Any help please?
function test(){
$(this).addClass("voted");
$(this).val('lighted up');
}
$(".stem").click(function() {
$(this).parent().parent().parent().find(".red").addClass("filltherm");
setTimeout(test,1500);
});
Store a reference to this in _this and pass that as a parameter to temp.
function test(el) {
$(el).addClass("voted");
$(el).val('lighted up');
}
$(".stem").click(function() {
var _this = this;
$(this).parent().parent().parent().find(".red").addClass("filltherm");
setTimeout(function () {
test(_this);
}), 1500);
});
$(this) will be undefined in function test as $(this) refers to the current element whose event has occurred and your function is separate thing, use a variable to store reference of it.
do like this:
var temp;
$(".stem").click(function() {
temp = $(this);
$(this).parent().parent().parent().find(".red").addClass("filltherm");
setTimeout(test,1500);
});
function test(){
temp.addClass("voted");
temp.val('lighted up');
}
You need to store a variable holding the value of this:
function test($el){
$el.addClass("voted");
$el.val('lighted up');
}
$(".stem").click(function() {
var $el = $(this);
$el.parent().parent().parent().find(".red").addClass("filltherm");
setTimeout(function() {
test($el);
}, 1500);
});
You can use the proxy method to specify what this shold be for the function call:
setTimeout($.proxy(test, this),1500);
Related
I've written some code that when you click a button it adds an instance of a function to an array,
var objects = [];
$(document).on("click", ".addButton", function(){
objects.push(new newObject(1));
});
function newObject(amount){
setInterval(function(){
addValue(amount);
}, 1000);
}
So then every second each new object created keeps running the addValue function every second adding the amount.
The problem is when I try and destroy that function with objects.pop() it deletes the object but the setInterval doesn't stop running.
How do I make it destroy everything in that function and stop it from running?
There is nothing quite like that in JS for setInterval. I would suggesting declaring a method to handle clean up.
// "Class" declaration
function newObject(amount) {
var id = setInterval(function() {
addValue(amount);
}, 1000);
this.kill = function() {
clearInterval(id);
}
}
// "Public" api for the data structure
var objects = [];
function addNewObject() {
objects.push(new newObject(1));
}
function destroyLastObject() {
objects.pop().kill();
}
// Event bindings
$(document).on("click", ".addButton", addNewObject);
$(document).on("click", ".removeButton", destroyLastObject);
Completely untested, but along these lines should work.
EDIT
This, imo, is a great resource for learning about different patterns within javascript - long but well well worth the read: https://addyosmani.com/resources/essentialjsdesignpatterns/book/
You got to find something to check against to clear the interval. I am clearing based on array length. It only executes once.
// you got to find something to check against to clear the interval
var objects = [];
document.addEventListener("click", function(){
console.log('click');
objects.push(new newObject(1));
});
function newObject(amount){
var interval= setInterval(function(){
if(objects.length !==0){
clearInterval(interval);
}
}, 1000);
}
I have an object that I have a few functions inside that I am using setTimout inside. I'm trying to clear the timeout using clearTimeout.. but I'm not hitting it right.
var ExpireSession = {
killSession: function () {
var TESTVAR2 = setTimeout(function () {
window.location.href = "error/expired.aspx";
}, 15000);
},
stopTimers: function (){
clearTimeout(ExpireSession.killSession.TESTVAR2)
}
}
Before 15 seconds I am triggering: ExpireSession.stopTimers(); but it does not stop it. Any ideaas what I am doing wrong here?
var TESTVAR2 is a variable that is local to the function it is declared within. It is not a property of an object.
If you want to access it as a property of an object, then you must define it as such:
ExpireSession.killSession.TESTVAR2 = setTimeout(function () {
(You might be able to make use of this depending on how you call the function).
Because JavaScript has functional scope, TESTVAR2 will only be defined within killSession. To reference it, you can set it as a property of ExpireSession:
killSession: function () {
this._TESTVAR2 = setTimeout(function () {
window.location.href = "error/expired.aspx";
}, 15000);
},
stopTimers: function () {
clearTimout(this._TESTVAR2);
}
I have the javascript code for a link click:
document.getElementById('giddy').onclick = function {
alert(this.href);
};
and I want to separate the function part of it...I have
document.getElementById('giddy').onclick = poro(this);
function poro(yyyy) {
alert(yyyy.href);
};
But it is not working (says undefined in the alert)...what am I doing wrong?
You don't need to pass this as a parameter. this will be the context for the function when it is called. You should just have:
document.getElementById('giddy').onclick = poro;
function poro() {
alert(this.href);
};
Get rid of (this) and use this in the function instead of yyyy.
document.getElementById('giddy').onclick = poro;
function poro() {
alert(this.href);
};
You're immediately calling the poro function.
Essentially, you're telling Javascript that the element's onclick value will equal the result of calling the poro(this [window] ) function.
To get around this, you can wrap the poro(this) function inside an empty function, like so:
document.getElementById('giddy').onclick = function(){poro(this)} function poro(yyyy) { alert(yyyy.href); };
You may also want to consider using an eventListener, as it allows room for expansion.
Almost there! You should do:
document.getElementById('giddy').onclick = function(){ poro(this); }
function poro(yyyy) {
alert(yyyy.href);
};
Note poro(this); wrapped in an anonymous function.
I'd recommend using addEventListener instead of the onclick method.
Try this:
var giddy = document.getElementById('giddy');
giddy.addEventListener('click', function(e) { poro(this); }, false);
function poro(yyyy) {
alert(yyyy.href);
}
since you are using jquery use :
$('#giddy').click(function(){ poro($(this));});
or you can use the bind() function
$("#giddy").bind("click", $(this), poro);
I have a function that listens for a click on the screen and fires a callback. It is part of a Helper object (which is why is preceded by the term Helper in my sample code. That is irrelevant however.
var Helper = {
bodyClickListener: function(fn) {
var window = document.getElementsByTagName('body')[0];
window.click();
CORE.dom.on(window, 'click', function(event) {
CORE.dom.off(window, 'click');
fn(event);
});
}
}
I need to be able to pass a function into this function with a parameter that has been previously set.
function someFunction() {
var popup = document.getElementById('tagResultsPopup');
Helper.bodyClickListener(function(popup) {
return function(event) {
event.stopPropagation();
removePopup(popup);
};
}(document.getElementById('tagResultsPopup')));
function removePopup(element) {
if(element) {
element.parentNode.removeChild(element);
}
};
}
The code above works, but you'll notice that I have to set the popup variable inside of the callback function. It has already been set above. How do I pass a reference to the earlier variable into the callback function.
If I understand your question correctly, you don't need to do much. You can just use the popup variable defined outside.
var popup = document.getElementById('tagResultsPopup');
Helper.bodyClickListener(function(event) {
event.stopPropagation();
//Don't set it
//var popup = document.getElementById('tagResultsPopup');
removePopup(popup);//popup will refer to the correct variable
});
The function that you are passing to bodyClickListener is a closure. You can simply reference 'popup' inside that function without any problem. You don't have to create a new variable.
The answer was to use closure in this way:
Helper.bodyClickListener(function(popup) {
return function(event) {
event.stopPropagation();
removePopup(popup);
};
}(document.getElementById('tagResultsPopup')));
That way the callback function has access to the variable I pass into the parameter function. So here, the return is actually the function I am passing as the callback.
Is this how you define a function in jQuery?
$(document).ready( function () {
var MyBlah = function($blah) { alert($blah); };
});
Now to call the function I do:
MyBlah('hello');
First of all, your code works and that's a valid way of creating a function in JavaScript (jQuery aside), but because you are declaring a function inside another function (an anonymous one in this case) "MyBlah" will not be accessible from the global scope.
Here's an example:
$(document).ready( function () {
var MyBlah = function($blah) { alert($blah); };
MyBlah("Hello this works") // Inside the anonymous function we are cool.
});
MyBlah("Oops") //This throws a JavaScript error (MyBlah is not a function)
This is (sometimes) a desirable behavior since we do not pollute the global namespace, so if your function does not need to be called from other part of your code, this is the way to go.
Declaring it outside the anonymous function places it in the global namespace, and it's accessible from everywhere.
Lastly, the $ at the beginning of the variable name is not needed, and sometimes used as a jQuery convention when the variable is an instance of the jQuery object itself (not necessarily in this case).
Maybe what you need is creating a jQuery plugin, this is very very easy and useful as well since it will allow you to do something like this:
$('div#message').myBlah("hello")
See also: http://www.re-cycledair.com/creating-jquery-plugins
No, you can just write the function as:
$(document).ready(function() {
MyBlah("hello");
});
function MyBlah(blah) {
alert(blah);
}
This calls the function MyBlah on content ready.
No.
You define the functions exactly the same way you would in regular javascript.
//document ready
$(function(){
myBlah();
})
var myBlah = function(blah){
alert(blah);
}
Also: There is no need for the $
You can extend jQuery prototype and use your function as a jQuery method.
(function($)
{
$.fn.MyBlah = function(blah)
{
$(this).addClass(blah);
console.log('blah class added');
};
})(jQuery);
jQuery(document).ready(function($)
{
$('#blahElementId').MyBlah('newClass');
});
More info on extending jQuery prototype here: http://api.jquery.com/jquery.fn.extend/
jQuery.fn.extend({
zigzag: function () {
var text = $(this).text();
var zigzagText = '';
var toggle = true; //lower/uppper toggle
$.each(text, function(i, nome) {
zigzagText += (toggle) ? nome.toUpperCase() : nome.toLowerCase();
toggle = (toggle) ? false : true;
});
return zigzagText;
}
});
The following example show you how to define a function in jQuery. You will see a button “Click here”, when you click on it, we call our function “myFunction()”.
$(document).ready(function(){
$.myFunction = function(){
alert('You have successfully defined the function!');
}
$(".btn").click(function(){
$.myFunction();
});
});
You can see an example here: How to define a function in jQuery?
That is how you define an anonymous function that gets called when the document is ready.