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');
});
}
Related
I have this simple function that copies some html, and places it in another div.
If I put the code for the function in the click event it works fine, but when I move it into a function (to be used in multiple places) it no longer works.
Do you know why this is?
If I console.log($(this)); in the function it returns the window element.
function addHTMLtoComponent () {
var wrapper = $(this).closest(".wrapper");
var component = $(wrapper).find(".component");
var componentCodeHolder = $(wrapper).find('.target');
$(componentCodeHolder).text(component.html())
//console.log($(this));
}
$(".js_show_html").click(function () {
addHTMLtoComponent();
});
codepen here - http://codepen.io/ashconnolly/pen/ebe7a5a45f2c5bbe58734411b03e180e
Should i be referencing $(this) in a different way?
Regarding other answers, i need to put the easiest one:
$(".js_show_html").click(addHTMLtoComponent);
since you called the function manually the function doesn't know the "this" context, therefore it reverted back to use the window object.
$(".js_show_html").click(function () {
addHTMLtoComponent();
});
// Change to this
$(".js_show_html").click(function () {
// the call function allows you to call the function with the specific context
addHTMLtoComponent.call(this);
});
Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call
this in the context of the click() event is the element clicked. In the context of the function addHTMLtoComponent this no longer is a reference to the element clicked.
Try passing the clicked object to the function to maintain the object reference.
function addHTMLtoComponent ($obj) {
var $wrapper = $obj.closest(".wrapper");
var $component = $wrapper.find(".component");
var $componentCodeHolder = $wrapper.find('.target');
$componentCodeHolder.text($component.html());
}
$(".js_show_html").click(function () {
addHTMLtoComponent($(this));
});
The special keyword this, when you call a function by itself, is the window object (which is what you observed). For the behavior you need, just add a parameter to the function that loads the appropriate context:
function addHTMLtoComponent(context) {
var wrapper = $(context).closest(".wrapper");
var component = $(wrapper).find(".component");
var componentCodeHolder = $(wrapper).find('.target');
$(componentCodeHolder).text(component.html())
//console.log($(context));
}
$(".js_show_html").click(function() {
addHTMLtoComponent(this);
});
One thing you could consider is that addHTMLtoComponent() could be made into a jQuery function itself:
$.fn.addHTMLtoComponent = function() {
return this.each(function() {
var wrapper = $(this).closest(".wrapper");
var component = $(wrapper).find(".component");
var componentCodeHolder = $(wrapper).find('.target');
componentCodeHolder.text(component.html())
});
}
Now you can call it like any other jQuery method:
$(".js_show_html").click(function () {
$(this).addHTMLtoComponent();
});
The value of this in a jQuery method will be the jQuery object itself, so you don't need to re-wrap it with $(). By convention (and when it makes sense), jQuery methods operate on all elements referred to by the root object, and they return that object for further chained operations. That's what the outer return this.each() construction does.
Inside the .each() callback, you've got a typical jQuery callback situation, with this being set successively to each member of the outer jQuery object.
You have to pass the element as parameter to this function.
eg:
<div onclick="addHTMLtoComponent ($(this))"></div>
var fbToggle = document.getElementById("fbToggle");
and later in the script
fbToggle.addEventListener("click", toggle("fbContainer"));
Console tells me that fbToggle is NULL
This is in the document though.
<input type="checkbox" id="fbToggle">
I wasnt using eventListener before, so maybe there is a special order of declaration i'm missing ?
EDIT :
entire js :
function toggle(target) {
var obj = document.getElementById(target);
display = obj.style.display;
if (display == "none") {display = "block"}
else {display = "none"}
}
function init() {
var fbToggle = document.getElementById("fbToggle");
var twitToggle = document.getElementById("twitToggle");
var pinToggle = document.getElementById("pinToggle");
console.log(fbToggle); // NULL
fbToggle.addEventListener("click", toggle("fbContainer"));
twitToggle.addEventListener("click", toggle("twitContainer"));
pinToggle.addEventListener("click", toggle("pinContainer"));
}
window.onload = init();
HTML is way too long.but JS is in head, called from external file. Also i'm not in quirk mode.
It is not clear where "later in the script" is. If it is in different scope definitely it is not going to work. Suggesting you to keep everything in a global object if possible so that you can access from different places in the script.
window.globals = {};
window.globals.fbToggle = document.getElementById("fbToggle");
window.globals.fbToggle.addEventListener("click", function () {
toggle("fbContainer")
});
function toggle(container) {
alert(container);
}
http://jsfiddle.net/ST938/
Another point is addEventListener expects a function or function idenitifier, NOT a function call.
addEventListener("click", toggle("fbContainer")); // wrong
addEventListener("click", toggle); // correct
So if you want to pass a parameter
window.globals.fbToggle.addEventListener("click", function () {
toggle("fbContainer")
});
function toggle(container) {
alert(container);
}
In JavaScript, putting brackets after a function name causes it to be called. If you want to reference a function without calling it you must not put brackets after the name:
window.onload = init(); // this calls init() immediately
window.onload = init; // this correctly stores init in window.onload
The same applies to toggle(). If you need to pre-specify some of the arguments you can wrap it in an anonymous function:
fbToggle.addEventListener("click", function() { toggle("fbContainer"); });
or you can use bind:
fbToggle.addEventListener("click", toggle.bind(null, "fbContainer"));
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);
});
How can I pass parameters to a function declared like something = function(){};
window.prototype.initInterface = function(){
this.mainPane = document.createElement('div');
this.mainPane.style.border="5px solid grey";
this.mainPane.style.margin="0px";
this.mainPane.style.width="420px";
this.mainPane.style.height="600px";
this.exitButton = document.createElement('input');
this.exitButton.setAttribute("type", "button");
this.exitButton.setAttribute("value", "exit");
this.exitButton.onclick = function(){
document.body.removeChild(this.mainPane);
};
this.mainPane.appendChild(this.exitButton);
document.body.appendChild(this.mainPane);
}
When the user presses the exit button I want to remove the mainPane from the body of the html page.
this.exitButton.onclick = function(this.mainPage){
document.body.removeChild(this.mainPane);
};
Does not work
How can I do this?
For your exitButton.onclick function to have access to variables you create in the enveloping initInterface function you want a to create a closure in the exitButton.onclick function by returning a function that performs the action you want and passing that the variable.
exitButton.onclick = function () {
return (function() {
document.body.removeChild(mainPane);
})(mainPane);
};
Read more on how closures work here and here and see a working example fiddle.
Alternatively, you forget about closures and walk up the DOM from the button which triggers the event to your mainPane
exitButton.onclick = function() {
// in here "this" is the object that triggered the event, exitButton
document.body.removeChild(this.parentNode);
}
As an aside, window.prototype does not exist if you are doing this in a browser; window is the object at the top of prototype chain in browser scripting. You want just window.initInterface = function () {} which is the exact same thing as function initInterface() {} because everything you do in javascript in the browser becomes a property of window.
This function is the function w/o function name. It could only be used once and you may not easy to find out what parameters should be passed.
You can create another function like :
function go(a1){}
And call it like window.prototype.initInterface = go(a1);
Or you can get some DOM parameters in this unnamed function by using functions like getDocumentById("DOM ID") etc.
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