animation starts before preloading CSS and Images [duplicate] - javascript

I wrote a JavaScript class called MyClass in which I've defined a method closeThis
MyClass = function() {
this.closeThis = function() {
document.getElementById("hidePane").style.display = 'none';
}
}
Now, in my html, i'm trying to call that as follows...
<script type="text/javascript">
function callThis() {
var myclassObj = new MyClass();
document.getElementById("closeButton").onclick = myclassObj.closeThis();
}
</script>
The above callThis will be called when I clicked on a button. The problem here is, onclick event on top of clsoeButtion is getting called automatically when page loads. What could be wrong in this?

You're calling the function right away.
When you leave the parentheses on the function reference, what you're basically saying is:
Evaluate the closeThis function and assign the result to onclick
when what you really want to do is assign the function reference to the click handler:
document.getElementById("closeButton").onclick = myclassObj.closeThis;
Leave out the parentheses instead, and you'll bind the closeThis function to the onclick. What this instead says is:
Assign the function closeThis to the click handler.
You are essentially assigning the function to the variable as a first-class object, or a reference to a function.
As an aside, my personal preference is to always use an anonymous function wrapper. Sometimes you need to be able to pass parameters into your function, and this makes sure that you can more easily do so:
document.getElementById("closeButton").onclick =
function() {
myclassObj.closeThis();
};

it should be
document.getElementById("closeButton").onclick = myclassObj.closeThis;
not myclassObj.closeThis();
myclassObj.closeThis() will call the function then assign value to onclick

You need to remove () from it otherwise it gets called immediately because that's how you call a function by suffixing (), so simply remove these braces:
document.getElementById("closeButton").onclick = myclassObj.closeThis;

Related

using an argument in a function called by an event (onclick) using JavaScript

I'm trying to create an onclick event using JavaScript. I would like the onclick event to trigger a function. What I'm finding is that if I call the function without an argument or the parenthesis, the function is called when the element is clicked.
But if I try adding an argument to the function, the function is called immediately, before the element is even clicked.
What I've discovered is that if I use an anonymous function, and place the function that I want to be called by the onclick event within the anonymous function, it works!
I don't understand why. There has to be something about the logic that I'm missing.
I'm new to programming, and I would greatly appreciate any help in understanding why I can't simply call a function with an argument from an onclick event.
Thanks
Here is the code I have that works
window.onload = init;
function init() {
var divSelect = document.querySelector(".basic");
divSelect.onclick = function () {addRed(divSelect)};
}
function addRed(el) {
var divClass = el.getAttribute("class");
if (divClass == "basic red") {
el.setAttribute("class", "basic");
}
else {
el.setAttribute("class", "basic red");
}
}
If you're doing divSelect.onclick = addRed(divSelect); what's happening is that it calls addRed(divSelect), and sets the return value of that as the onclick. That's all fine if you actually return the function you want, but in most cases, it's not. That's why you need to wrap it in an anonymous function.
The other option is to use Function.bind():
divSelect.onclick = addRed.bind( // bind a context and pre-fill arguments
divSelect, // the context, can be anything in this case
divSelect); // the pre-filled argument

How functions get invoked in this code?

I can't understand the order of execution takes place here:
<script>
$(function(){
function f(id){
document.body.innerHTML += "<p>executing handler for div " + id + "</p>";
}
document.getElementById("div1").onclick = function(){
f("1");
}
document.getElementById("div2").onclick = function(){
f("2");
}
document.getElementById("div3").onclick = function(){
f("3");
}
});
</script>
What I want to know is how the 'function' and 'f' are called? Is it like when someone click on 'div' then function gets invoked? If it is so, why the function is on the right side of "=" operator?
When someone clicks on div1 the onclick method triggers function f with a passed value of 1. Ditto when div2/3 are clicked on, f is called with those values.
All f does is change the content of the page to show a message.
I'm not sure why this is using document.body.innerHTML though, I would normally expect to see a div that shows a message, such as document.getElementById('message').innerHTML.
I have a feeling (without checking) that document.body.innerHTML will change the whole content of the page to the value that f outputs. I doubt that is the desired result.
Explained in comments, line by line:
<script>
// this is a jQuery shorthand for $(document).ready. That means, that this function is executed automatically, when the DOM is ready
$(function(){
// declaration of a function that will be executed when it's called from somewhere. 'id' is an argument that can be passed
function f(id){
document.body.innerHTML += "<p>executing handler for div " + id + "</p>";
}
// 'onclick' is an event handler. When you click the div container with the id 'div1', then the function, set after '=', gets executed
document.getElementById("div1").onclick = function(){
// call the function that you declared above with the argument "1"
f("1");
}
document.getElementById("div2").onclick = function(){
f("2");
}
document.getElementById("div3").onclick = function(){
f("3");
}
});
</script>
If I'm understanding you correctly based on your question of "why the function is on the right side of = operator?", your question really related to = function(){ in the following code.
document.getElementById("div1").onclick = function(){
f("1");
}
What this code is doing is assigning an anonymous function to the onclick property of the div1 element.
When a user clicks on the div1 element, this anonymous function is executed. Within the anonymous function, a call is made to the function f passing the string "1".
The reason the anonymous function is needed is because if you were to exclude this and simply have this:
document.getElementById("div1").onclick = f("1");
Rather than calling the f function when the element is clicked, you would immediately call the f function and set the returned value (undefined) to the onclick property. By wrapping it in an anonymous function, you get the desired effect of calling f with the given parameter when the element is clicked.
According to what you have asked
$(function(){
});
gets executed on load of a page
if you want to call function f() you need to call as
$(function(){
f();
});
$(function(){...} is the jQuery function for document.ready. This function is executed as soon as all of the DOM is ready. It is a feature of jQuery. You don't call it explicitly - jQuery handles that for you.
The f() function is attached to the click handlers (onclick) that are defined for the three div elements. When they are clicked, they trigger the f() function.
The function is on the right side of an assignment because what the code is actually saying is replace the default onclick function with the one defined.

addEventListner is triggerd before the HTMLElement is clicked

I'm using an addEventListner method on a HTMLElement inside a function that is called on onLoad. However, the method gets executed even before i try the click event in the html page.
function setConfigurationMenu(){
var navConfigure = document.querySelector(".navConfigure");
var navBody = navConfigure.querySelector(".body");
var navTop = navConfigure.querySelector(".top");
navTop.addEventListener("click", alert("jow"));
}
So what's going on here, any ideas?
thx,
This is happening because you are executing the alert function and passing its return value (which is undefined) as parameter to the addEventListener method. You actually need to pass a function to it.
navTop.addEventListener("click", functionToBeTriggered);
As alert expects a parameter that is your text, you might want to wrap it into an anonymous function that calls it. For example:
navTop.addEventListener("click", function() {
alert("jow")
});
This happens because you pass function result instead of function handler, try anonymous function for this:
navTop.addEventListener("click", function() {
alert("jow");
});
In other words in your case you just invoke function, but you need to pass handler for this.

function called on page load not jquery .click

This function gets called on page load, not when .somebutton is clicked. I'm not sure why. I want to be able to pass the variables so that I may use this function in multiple places with different values. Thank you very much.
var i = "this be i";
var u = "this be u";
function dosomething (var1, var2){
console.log(var1 + " and " + var2);
}
$(".somebutton").click(dosomething(i,u));
You are passing value returned by dosomething(i,u) to click handler. This is why it ise executing without clicking, it is happening as soon as you call your function (that is: dosomething(i,u)). You need to wrap your function call inside anonymous function:
$(".somebutton").click(function() { dosomething(i,u); } );
You can only pass a function by reference using the method in your example (ie. without parameters). The reason your function works on load is because it is immediately invoked due to the trailing () brackets.
If you need to pass parameters you need to wrap it in an anonymous function, like this:
// on click:
$(".somebutton").click(function() {
dosomething(i, u);
});
// on page load:
dosomething(i, u);
In JavaScript doing
$(".somebutton").click(dosomething(i,u));
will not assign the function to your click event, but will rather call the function and assign whatever result the function returns. You need to reference your function instead :
$(".somebutton").click(dosomething);
If you need to pass variables to your function, then you need to wrap the said function inside another anonymous one :
$(".somebutton").click(function() { dosomething(i, u); });

Passing jQuery .click() a function as a variable

I'm working with a tabbed interface and have the following jQuery function set up to handle the click events of my tabs.
$(document).ready(function () {
$('a#foo').click(function() {
//content, various calls
return false;
});
});
The above is an example of one of my tabs, the others are also within the same document ready block. What I needed to do was make it so the currently selected tab could not be re-clicked and that in some other cases I could manually disable tabs if needed. I achieved this via the following:
$('a#play').unbind('click');
This works fine, and it certainly disables the tabs but the problem then becomes rebinding the click action that was once there. I achieved this via the bind function:
$('a#foo').bind('click', function() {
//the same content and calls as before
return false;
});
This also works fine, but it has become exceedingly cluttered as I have added tabs to my UI. The immediate solution appears to be to create the function as a variable and then pass it into the initial click creation and into the binding event. Like so:
var Foo = new function() {
//same content and calls as before
return false;
}
$('a#foo').click(Foo());
$('a#foo').bind(Foo());
This, for one reason or another, seems to be causing browser crashing issues. Is it not possible to pass a function as a var in this case or am I just doing it wrong? Alternatively, is there a better way to achieve the results I'm looking for? Thanks.
$('a#foo').click(Foo());
$('a#foo').bind(Foo());
The Foo gives you the function, but adding ()'s after it means you are calling the function instead of passing the function itself. Since you're calling the function, false ends up getting passed to click and bind, obviously not doing anything. Some of your other problems might result from the fact that you simulating switching to that tab twice (calling the event handler twice).
var Foo = function() {
//same content and calls as before
return false;
}
$('a#foo').click(Foo);
$('a#foo').bind(Foo);
^^ should do what you want.
Alternatively, is there a better way to achieve the results I'm looking for?
Currently all we really know about your design is that you are calling using a click event handler to switch tabs. That part is awesome, but we'll need more info to give you the deeper answer you really want. If you post the code inside Foo we should be able to help a bit more. :D
EDIT: credit to SLaks♦ for noticing the new in the function declaration that I missed. I'll add a little more detail to his explanation:
When you write var foo = new
function(...) { ... }, you're making a
function literal, then calling it as a
constructor.
It's equivalent to
var SomeClass = function(...) { ... };
var foo = new SomeClass;
without the SomeClass dummy variable.
The function() {} is an anonymous function as you would expect. new in javascript is a little more confusing. When you call a function and precede it with new, you are using that function to instantiate an instance of a class defined in the function. In JS, unlike most other languages, the entire definition of a class is in one constructor function, from which you set all the instance variables, like so:
Foo = function() {
this.a = "lala";
this.b = 5;
}
To make instance methods of the 'class', you use the prototype attribute. However I just realized I've gotten super off-topic. Read more on that here and here. :D
You need to remove new from the function definition and stop calling the function when using it.
When you write var foo = new function(...) { ... }, you're making a function literal, then calling it as a constructor.
It's equivalent to
var SomeClass = function(...) { ... };
var foo = new SomeClass;
without the SomeClass dummy variable.
You need to simply assign the function literal to the variable.
When you write .click(foo()), you're calling foo, and passing the result to click.
Unless foo returns a function, that's not what you want to do.
You need to pass foo itself by removing the parentheses.
So firstly, click accepts a function, but you call without the () as click runs the function when ready. By adding the () you call it straight up.
Secondly, bind takes a string (what event you are binding to) AND a function (as above)...
Use the following:
function Foo() {
//same content and calls as before
return false;
}
$('a#foo').click(Foo);
$('a#foo').bind('click', Foo);
Hope that helps :)
Try:
var foo = function() // not "new function", as this creates an object!
{
return false;
}
$("a#foo").click(foo); // not "Foo()", as you can't call an object!
As for a better way to achieve the result you're looking for, you could have a class on every tab, such as .tab. That way, you can just do:
$("a.tab").click(function() { return false; });
... without having to fluff around with a lot of ids.
Take a different approach, and do not unbind().
I assume the tabs are all in a common container. If so, just use the delegate()(docs) method to place a handler on the container.
Here's a generic code example:
$('#container').delegate('.tab:not(.selected)', 'click', function() {
$(this).addClass('selected')
.siblings('selected').removeClass('selected');
// rest of the tab code
});
This will only trigger clicks on .tab elements that do not have the .selected class. You'll need to modify for your specific code.
Adding the parenthesis calls the function, but if you wanted to make it cool and stuff, you could make it so that Foo returned the function to be bound.
function Foo(){
return function(){
//your onclick event handler here.
};
}
$('a#bar').bind(Foo())
This makes use of one on javascript's function programming aspects, closures, which is cool, but not as efficient as some of the other answers. You should do some research about closures, as they can be used to make some cool stuff.
http://www.javascriptkit.com/javatutors/closures.shtml

Categories