In my javascript code ( which is too long , so i can`t put it here ), functions are calling more than once , like suppose :
$("#button").bind({ click : Call }); // bind the Call with button click event
function Call()
{
alert("This message shows me more than once when i clicked the button");
}
if this alert message shows me more than once it means function Call() is calling more than once. Can anybody guess or tell me what's going on in my code? (Please don't ask me for code)
Works for me: http://jsfiddle.net/aC8Bm/
I'm guessing that you are binding more than once somewhere.
Also, I'd recommend either returning false from the Call function, or stopping event propagation.
One more thing: avoid naming functions with an uppercase -- that's reserved for constructor functions by convention.
You're hooking the event handler to the button the number of times 'Call' is being called. Do you have this code in something like a template or partial file?
Instead of doing this inside any function:
$("#button").bind({ click : Call });
Place the following somewhere outside:
$("#button").live("click", Call);
It will bind once for all existing and ever added #button
Related
When I call editWorkout function for the first time, the variable 'workout' gets passed in the editWorkout2 function, but then, during the second time, when the same thing happens, but in this case 'workout' has new value, this value for some reason won't change in editWorkout2 function. How can I fix that?
function editWorkout(e, workout) {
e.stopImmediatePropagation();
saveBtn.addEventListener("click", function (e) {
console.log(workout);
editWorkout2(e, workout);
}.bind(this)
);
}
on each call of your editWorkout function, you're adding a new event listener to your "saveBtn" element with the same event type.
I recommend you read the usage notes of addEventListener.
So, the problem was as follows: because during the second call and all of the consecutive calls of the function editWorkout the event listener was going on top of the previous one, for some reason variable workout was not changing in that eventListener as a parameter. So I removed event listener in the editWorkout2 function, and everything started working fine
I have an event listener on an object which fires a function when the object changes.
This is the code:
window.parent.document.getElementById('campval').addEventListener("change", getscriptbuttons1());
This works perfectly the first time that the object changes however, all consecutive changes do not trigger the event listener.
Is this the normal behaviour of Javascript? What can I do to rectify this issue?
No, the event listener should get fired every time.
I think this error is due because you are calling the function instead of passing it as a parameter:
getscriptbuttons1 // passes the function
getscriptbuttons1() // calls the function and passes whatever it returns
Did you mean? :
window.parent.document.getElementById('campval').addEventListener("change", getscriptbuttons1);
No, they do not get destroyed. You have to remove them manually. The issue is that you are actually calling the function in the event listener. You need to change it to this: (no parens, don't call it)
window.parent.document.getElementById('campval').addEventListener("change", getscriptbuttons1);
A few weeks ago I was painfully able to dynamically add buttons to an HTML DOM object that has its own .on('click'.. handler, and use e.stopPropgation to stop these new child elements from firing the event.
The weird thing I did was call a function without any parenthesis. I have no idea why I did this or why it works, or why it does not work when I do attach parenthesis. I want to know if I am doing something by fluke and not design (and now I will add comments to it).
It goes as such:
//Container is the parent element
// var buttons stores the buttons with class 'buttons'
$('.container').on('click', function(){
$(buttons).appendTo($(this)).fadeIn(500).find('.buttons').click(tableButton);
});
function tableButton(e){
e.stopPropagation();
//do stuff
}
I can't figure out why I wrote the call to tableButton with no arguements or why it works perfectly. I tried to change the syntax to
.find('.buttons').on('click', function(e){
tableButton(e);
});
but then it no longer works.
Any help appreciated!
It works because you're passing a function to the click handler rather than calling the function yourself (the ()) An example of that:
var testFunction = function(msg) {
alert(msg);
}
var functionCaller = function(functionToCall) {
functionToCall('hello!');
}
functionCaller(testFunction);
functionCaller passes the message argument to testFunction(), but we only pass testFunction to functionCaller (without arguments)
For the part which doesn't work, isn't the function name tableButton() instead of tableButtons()?
See http://jsfiddle.net/g2PAn/
You don't actually call it, you just declare it and the arguments it accepts. The click callback is called with an argument indeed, but not by you.
The problem probably comes from the fact that jQuery calls your function with the element clicked bound as this, you could call table button like this:
.find('.buttons').on('click', function(e){
tableButton.call(this, e);
});
When you are using events in your HTML, and you include a small bit of JavaScript, what is that called? Is it called a "JavaScript attribute function", just a "JavaScript attribute", or what? ex:
<button onClick="location.href='some_place'">click me</button>
When using events, and you use the return keyword, what is that called? Is there some specific piece of terminology that is used to describe this? I am aware of what it does and how it works, I just do not know what to call it. ex:
<button onClick="return someFunction();">click me</button>
Can these two pieces of JavaScript be combined into one in this attribute? I would like to combine my first two examples into one. When the button is clicked, I want to call a JavaScript function. If the function returns "true", I want the location.href to fire. If the function returns "false", I do not want the location.href to fire.
onclick is the event Handler
return is the return statement once the function reaches the return statement it will stop executing
combining the two function may look like this
function someFunction(){
var x = someBool;
if(x){
location.href='some_place'
}else{
return false;
}
}
onclick is a HTML Attribute that binds an event to the element. The value of the attribute is the body of the event handler. You can write anything you want there, but you're limited by the fact that you need to escape quotes " in your code, otherwise the HTML parser will think that you've finished defining the attribute value.
So your code can be:
<button onclick="if(someFunction()) location.href='some_place';"></button>
but, like Sam Creamer pointed out, you don't need a button for it. You can do it with an a href:
if someFunction returns false, the click event will be canceled, and you won't be redirected anywhere.
If you want more code in the attribute, a more practical way is to do this:
onclick="return someOtherFunction()"
, where someOtherFunction contains all your code.
Or like this JS code:
document.getElementById("the_id_of_the_element").onclick=function() {/* your code here */};
, however this might not work on older browsers (other code is necessary):
function bindEvent(element, type, handler) {
if(element.addEventListener) {
element.addEventListener(type, handler, false);
} else {
element.attachEvent('on'+type, handler);
}
}
bindEvent(document.getElementById("the_id_of_the_element"), 'click', function() {/*Your code here*/ });
You can also use jQuery to bind events, which does exactly the same
$("#the_id_of_the_element").on("click", function() {/*your code here*/});
$("#the_id_of_the_element").on("click", function() {/*some other code*/});
//both will execute
Inline JavaScript, bound to an event.
Same, but explicitly returning a value, like any other JavaScript function can. Here it may affect behavior, e.g., stopping normal event processing if the function returns false.
Just write the location value in the function you're calling.
#3 is a little tricky, though, because a function that doesn't explicitly return a value is returning undefined, which, depending on context, may not be a reasonable thing to do. In this case you might want to explicitly return true to keep things clear.
I am taking a web development class. Today the teacher gave us a piece of code that raised some questions that I haven't been able to satisfactorily solve through my own searching. The code in question was essentially this:
<script>
function selectmouse(e){
...
...
}
document.onmousedown = selectmouse;
</script>
My first question, is this a legitimate way of calling functions? Is this something that is done? I am of course familiar with the typical way of calling functions from HTML elements, for example
<body onmousedown="selectmouse(event)">
The code was supposed to be calling the function and passing it the event object for the onmousedown. After playing with the code for a while I found a few unusual things.
First, if I put parenthesis after the function call, like I am used to doing (i.e. selectmouse();), then the function resolved immediately upon loading the page, with a value of 'undefined' for the variable. This makes intuitive sense to me, because I assume the browser is treating it like a variable assignment and therefore calling the function as it parses the code, as it normally would to assign a variable.
However the part that is weird to me happened when I deleted the '()' and left it as it is coded above. In this instance it seemed to function like she wanted it to. It would call the function when the mouse was pressed in any part of the body, and it sent the event object as the variable for the function. But I can't figure out why. I can't find reference to anything similar to it online, and I've never seen anything like it before. Is this a legitimate way to do something like this? Or is this bad code that happens to be working for some reason and would probably cause problems in the future? Why is it working?
document.onmousedown = selectmouse; //note: never do this except in old browsers
However the part that is weird to me happened when I deleted the '()' and left it as it is coded above. In this instance it seemed to function like she wanted it to.
That's not weird. You are passing the reference of the function to the browser, not executing it.
For example, you have this function:
function callback(){
alert("clicked!");
}
document.body.onclick = callback;
You pass the reference to onclick and the browser will know what function to call when the event is triggered. But if you do it like this:
document.body.onclick = callback();
This will be evaluated into:
document.body.onclick = alert("clicked!");
//Note that this is simplified explanation to visualize what is happening.
//The returned value of alert() is not assigned to onclick.
//To be exact the returned value of callback() is the one that is being assigned.
//Similar to:
// ...onclick = (function(){ alert("clicked!"); })();
Then you will see an alert, and the browser will continue executing the rest of the code:
document.body.onclick = undefined;
<body onmousedown="selectmouse(event)"> <!-- Don't do this too -->
The parentheses are necessary because this code is not executed instantly. It is only executed when the event is triggered.
Anyway, you shouldn't attach events both using .onmousedown or onmousdown="...". There is a better way of doing it:
element.addEventListener("mousedown", callback, false);
Reason: If you use the onmousedown property, you can only attach one mousedown event. In most cases you would want to attach more than one.
Also attaching events inline might cause security problems (cross-site scripting), and that is exactly why Google decided to prohibit all developers from using them in developing Chrome apps/extensions.
This is legitimate code and is working as it should.
The way you are comfortable with is just a method we tried while the web was evolving, but at present we should better use the second way you showed, although its changed bit more to make you understand it in a better way using event bindings.
When you do
function selectmouse(e){
...
...
}
javascript will create a variable named selectmouse and save the function in that variable. So selectmouse is a variable of type function with the function body as its value.
document on the other hand can be related to class or specifically an object which is an instance. Each document and each HTML element or DOM node can have in it variables to store the functions to be called on user events like onmousedown.
so when doing
document.onmousedown = selectmouse;
we are inturn saying
when mousedown happens in document, the function named selectmouse
should be called
If you do
document.onmousedown = selectmouse();
it means
run the function selectmouse immediately and get the result, assign
the result to onmousedown event of the DOM Node document.
And if you ask why this is taken apart from the form
<body onmousedown="selectmouse(event)">
To answer in a simple way, HTML is Hyper Text Markup Language, its sole purpose is to represent formatted data, the quick evolution of web inturn made it deranged with behaviours like this and presentation code like inline css. So to make behaviour and presentation out of HTML and thus a better design we do this.
Please take time to take a look at how you can bind a function to an event which is the current tradeoff in doing this same thing.
For a detailed explanation please check the events sectio of ppk blog here
I think that is correct, because the function is being called within the script as if it were an object, to me is not the best way to do it, I would have like this (with jquery):
$(document).mousedown(function (event) {
// here the content of the function
});
<body onmousedown="selectmouse(event)">
In this example the browser evaluates the result of the expression selectmouse(event) and assigns it to the onmousedown property of the body, event is undefined and the selectmouse doesn't return anything so it's result is undefined.
It is equivalent of the following if it was inside a script tag
<script>
function selectmouse(e) {
}
document.body.onmousedown = selectmouse(event);
</script>
<body onmousedown="selectmouse">
When you remove the () you are assigning a function to the onmousedown property. Now the browser fires your callback method whenever the mousedown event is raised and it bubbles up to the body, passing the current event as the parameter you're declaring as "e". If another element also had an onmousedown event handler declared but it cancelled the event ( by calling event.cancelBubble = true ) the body's onmousedown handler will not be invoked.
<script>
function selectmouse(e) {
}
document.body.onmousedown = selectmouse;
</script>