return a variable from .click() javascript function - javascript

First of all excuse for my weak english, I try to use the following javascript code and I want to return id variable and use it in other function, but it seem does not work correctly and does not return it, can someone help me out writting this
var idcb = $('.box').click(function() {
var id = $(this).attr('id');
return id;
});
I want to use var idcb in this function :
$(".hs").click(function() {
$(idhs).slideToggle("slow");
return false;
});
});

for that to work, the jquery click implementation would need to know that the function you pass it returns a value, and that it itself should return that value - which isn't the case.
instead, you could use some closure magic to do this easily. try this:
var idcb;
$('.box').click(function() {
idcb = $(this).attr('id');
});

You are passing an anonymous function to an event handler, you cannot return a value from this type of function. The solution is to use closures to get around this :
var idcb = null;
$('.box').click(function() {
idcb = $(this).attr('id');
});
The variable idcb will always be set to the id of the last .box that was clicked.

The function is given as a parameter to the click function and is run asynchronously when the user clicks on an element. So you can't return a value directly, since the function won't be run immediately. You can look up the id value another way, or pass it to a function to work with instead of returning it, or just do this:
var idcb = $('.box').click(function() {
var id = $(this).attr('id');
$(id).slideToggle("slow");
});

You cannot do it the way you are trying to. However, what you can do is use a variable that is accessible by both functions to share values between them.
var icdb = 'test';
function a() {
icdb = 'another value';
}
function b() {
console.log(icdb);
}
a();
b();
You could also call b from a and pass the variable as argument:
function a() {
b('test');
}
function b(icdb) {
console.log(icdb);
}
a();

your variable idcb contains the click handler !
you need to declare the vriable outside the handler and assign to it inside to make this work:
var idcb = null;
// ... whatever
$('.box').click(function() {
idcb = $(this).attr('id');
return true; // return 'true' from an event handler to indicate successful completion
});

Check this out
var id=null;
$('.box').click(function() {
id = $(this).attr("id");
});
$(".hs").click(function() {
$("#"+id).slideToggle("slow");
return false;
});

You could pass in the an object as a reference to the click function
and change the value from the callback. Another option is using closures
The caveat to this jsfiddle is that you have to call a .box element first.
http://jsfiddle.net/D6B73/2/
var idcb = {};
$('.box').click(idcb, function (event) {
event.data.value = $(this).attr('id');
console.log(idcb.value);
});
$('.hs').click(function() {
$('#'+idbc.value).slideToggle("slow");
});

You can do it this way:
$(".hs").on('click', function() {
var id = $('.box').attr('id');
alert(id);
});

Related

Use value from method in javascript object to use in setTimeout function

I have tried different things but I do seem to be looking something over that is too obvious. Trying to use the value a function(method) returns inside an object and use it in another method with setTimeout within that same object.
This is the html:
<h1>3000</h1>
The javascript (jQuery in this case):
var foo = {
getValue: function() {
var h1Text = $('h1').text();
h1Text = parseInt(h1Text);
return h1Text;
},
useValue: function() {
var time = this.getValue();
var alertIt = alert('Hello');
setTimeout(alertIt,time);
}
};
foo.useValue();
// log shows correct value
console.log(foo.getValue());
// returns a number
console.log(typeof(foo.getValue()));
The alert does show up, but on load rather than using those 3 seconds.
It does log the correct value and also says it's a number so I'm really not sure what I am doing wrong. Any help is appreciated. Thanks
In useValue() you call alert('Hello'), so it's executed immediately and the result is stored in alertIt variable. You should put it inside the function like this, as setTimeout expects a function as a first parameter:
var alertIt = function() {
alert('Hello');
}
setTimeout(alertIt,time);
setTiimeout expects function and not variable.
Also var alertIt = alert('Hello'); this will return undefined.
Note: var a = function() will call it and assign return value. To assign a function to a variable with parameter, use .bind
Try alert.bind(null, "hello");
For demo purpose, I have hardcoded value of delay and commented getValue code.
var foo = {
getValue: function() {
//var h1Text = $('h1').text();
//h1Text = parseInt(h1Text);
return true// h1Text;
},
useValue: function() {
var time = 3000//this.getValue();
var alertIt = alert.bind(null,'Hello');
setTimeout(alertIt, time);
}
};
foo.useValue();
// log shows correct value
console.log(foo.getValue());
// returns a number
console.log(typeof(foo.getValue()));

Getting "This" into a namespace in Javascript

I'm sure this should be a simple question but I'm still learning so here it goes:
I have some code to run a function on click to assign the clicked element's ID to a variable but I don't know how to pass the "this.id" value to the namespace without making a global variable (which I thought was bad).
<script>
fsa = (function() {
function GetTemplateLoc() {
templateId = document.activeElement.id;
alert(templateId + templateId2);
}
return {
GetTemplateLoc: GetTemplateLoc,
}
})();
//call the functions
$(document).on('click', '.template', function () {
fsa.GetTemplateLoc();
});
</script>
and HTML with random picture:
<img id="template-1" class="template" src="http://fc02.deviantart.net/fs70/f/2010/028/c/b/cb21eda885b4cc6ee3f549a417770596.png"/>
<img id="template-2" class="template" src="http://fc02.deviantart.net/fs70/f/2010/028/c/b/cb21eda885b4cc6ee3f549a417770596.png"/>
The following would work:
var fsa = (function() {
function GetTemplateLoc() {
var templateId = this.id;
alert(templateId);
}
return {
GetTemplateLoc: GetTemplateLoc,
}
})();
//call the functions
$(document).on('click', '.template', fsa.GetTemplateLoc);
jQuery generally calls functions you pass as event handlers with this set to the DOM object the event is associated with.
In this case it will call GetTemplateLoc() with this set to either .template element, so you can use this directly in the function and don't need to pass any parameters.
Important tip: Always declare variables using var. JavaScript has no automatic function-local scope for variables, i.e. every variable declared without var is global, no matter where you declare it. In other words, forgetting var counts as a bug.
Try this : You can directly use this.id to pass id of the clicked element where this refers to the instance of clicked element.
<script>
fsa = (function() {
function GetTemplateLoc(templateId ) {
//templateId = document.activeElement.id;
alert(templateId + templateId2);
}
return {
GetTemplateLoc: GetTemplateLoc,
}
})();
//call the functions
$(document).on('click', '.template', function () {
fsa.GetTemplateLoc(this.id);
});
</script>
If you're able to use jQuery within the GetTemplateLoc function, you could do something like this:
var fsa = (function() {
function GetTemplateLoc($trigger) {
var templateId = $trigger.attr('id'),
templateId2 = $($trigger.siblings('.template')[0]).attr('id');
alert(templateId + ' ' + templateId2);
}
return {
GetTemplateLoc: GetTemplateLoc,
}
})();
$(document).on('click', '.template', function () {
fsa.GetTemplateLoc($(this));
});
You can set GetTemplateLoc to expect a jQuery object as a parameter (the dollar sign at the beginning of $trigger can be used to distinguish it as a jQuery object rather than any other data type, it's not necessary but can help clarify things sometimes).
templateId will store the value of the clicked image's ID, and templateId2 will store the value of the other image's ID. I also added a space between the two variables in the alert.
If you can't use jQuery within GetTemplateLoc, you could do something like this:
var fsa = (function() {
function GetTemplateLoc(trigger) {
var templateId = trigger.id;
var templateId2 = trigger.nextElementSibling == null ? trigger.previousElementSibling.id : trigger.nextElementSibling.id;
alert(templateId + ' ' + templateId2);
}
return {
GetTemplateLoc: GetTemplateLoc,
}
})();
This time, the .template that triggered the event is passed into GetTemplateLoc, but this time it's not a jQuery object. templateId is assigned to the trigger's ID and then templateId2 is assigned in a ternary. First, the nextElementSibling of trigger is checked to see if it's null. If it is, we know that trigger is the second of the two .template elements. Therefore we can set templateId2 to the ID of trigger's previous sibling. If trigger's nextElementSibling is not null, then we know that trigger is the first template and we populate templateId2 with the ID of nextElementSibling. This exact method will only work with two .template's, if there are more you'll need some additional/different logic, probably to retrieve all .template IDs and then loop through them to add them to the alert message. Hope this helps.

How to get selector's variable on Onclick

When a selector is assigned to a variable, I need to get that variable name on onclick I have created a Fiddle as an example
var $main_img1 = $("<div/>").addClass('add1').appendTo($('#main_container'));
var $main_img2 = $("<div/>").addClass('add2').appendTo($('#main_container'));
$main_img1.click(function()
{
get_id()
});
$main_img2.click(function()
{
get_id()
});
function get_id(event)
{
console.log($(this))
alert('i need to get selector variable on click')
}
Output should be $main_img1 and $main_img2 when I click on the corresponding div
Here is a solution, but not sure how you are going to use it
Used Array to get the variable name.
JS
var arr = new Array();
arr[0] = '$main_img1';
arr[1] = '$main_img2';
var $main_img1 = $("<div/>").addClass('add1 add').appendTo($('#main_container'));
var $main_img2 = $("<div/>").addClass('add2 add').appendTo($('#main_container'));
$main_img1.click(function()
{
get_id($(this))
});
$main_img2.click(function()
{
get_id($(this))
});
function get_id(event)
{
alert(arr[$('.add').index(event)]);
}
Update : No array needed.
function get_id(event)
{
///var temp = '$main_img' + (parseInt($('.add').index(event)) + 1);
var temp = '$main_img' + (parseInt($('#main_container > div').index(event)) + 1);
alert(temp);
console.log(eval(temp));
}
Updated DEMO
I suggest a workaround.. see if it helps you. Add a hidden element inside the corresponding divs and add the variable names as text to it. I slightly modified your method get_id() to get the variable name from your divs hidden element.
function get_id()
{
console.log($(this))
var selVar= $(this).parent().find('input:hidden:first').text();
alert('selector variable' + selVar);
}
this will work for you.
You could maybe guessing from the class of the element you click on it and use reflexivity.
To know the element you click on it, just use event.target where event is a variable passed in the click function. Look at this fiddle for an example.
The get_id method now looks like this:
function get_id(event) {
console.log(event.target)
}
The value returned by event.target is the same as the value returned by the variable you declare it ($main_img1 or $main_img2).

How to access properties of function within function

How do I access isExpanded, collapsedHeight and expandedHeight inside the jQuery click handler for element.The way it's written now won't work because this means something else inside the click handler than it does outside of it.
function CoolSelect(element)
{
this.element=element;
this.isExpanded=false;
this.collapsedHeight=$(element).height();
this.expandedHeight=this.collapsedHeight+$('ul',element).height();
$(this.element).click(function()
{
var newHeight;
if(this.isExpanded){newHeight=this.collapsedHeight;}
else{newHeight=this.expandedHeight;}
$(this.element).animate({height:newHeight},100,'liniar');
});
}
Thank you.
Copy the value of this to another variable in the outer function.
var that = this;
Then use that in the inner function.
You need to save a reference to this.
This code uses var that = this;
function CoolSelect(element)
{
this.element=element;
this.isExpanded=false;
this.collapsedHeight=$(element).height();
this.expandedHeight=this.collapsedHeight+$('ul',element).height();
var that = this;
$(this.element).click(function()
{
var newHeight;
if(that.isExpanded){newHeight=that.collapsedHeight;}
else{newHeight=that.expandedHeight;}
$(that.element).animate({height:newHeight},100,'liniar');
});
}

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