What is the difference between function(){func(var)} and func(var) [duplicate] - javascript

This question already has answers here:
What is the difference between a function call and function reference?
(6 answers)
Why does click event handler fire immediately upon page load?
(4 answers)
Closed 1 year ago.
I was transferring all my JavaScript code to external file :
One of the inline codes were like this :
onclick="nextPrev(-1)" ; onclick="nextPrev(1)"
The method I tried was :
document.getElementById("nextPrev").addEventListener("click", nextPrev(1))
document.getElementById("nextPrev").addEventListener("click", function(){nextPrev(1)})
The second line of code works fine, i.e, triggered on the click of button. While the first code is a type of automatic (means value is shown without any click event).
So wanted to know the difference between both method I used in external file. Also if there is any other method to write onclick="nextPrev(1)" in external file please feel free to point out.
Here is a working snippet :
function nextPrev(e){
document.getElementById("demo").innerHTML = e;
}
document.getElementById("nextBtn1").addEventListener("click", nextPrev1(1))
function nextPrev1(e){
document.getElementById("demo1").innerHTML = e;
}
document.getElementById("nextBtn2").addEventListener("click", function() {
nextPrev2(1)
})
function nextPrev2(e){
document.getElementById("demo2").innerHTML = e;
}
<button type="button" id="nextBtn" onclick="nextPrev(1)">onclick="nextPrev(1)"</button>
<div id="demo"></div>
<button type="button" id="nextBtn1">func(var)</button>
<div id="demo1"></div>
<button type="button" id="nextBtn2">function(){func(var)}</button>
<div id="demo2"></div>
Thanks for help in advance

document.getElementById("nextPrev").addEventListener("click", nextPrev(1))
This will call nextPrev(1) immediately (hence giving the impression that the event is executed immediately) and set its returned value as the event listener callback.
document.getElementById("nextPrev").addEventListener("click", function(){nextPrev(1)})
This will set the event listener callback to a function which calls nextPrev(1) whenever the event is executed. Whenever the event is fired, the function is called, and only then is nextPrev(1) called.

The difference is as simple as illustrated below:
function callme(){
console.log("hello");
}
//Does not run until callmeWrapper is executed
function callmeWrapper(){
callme();
}
//Runs automatically
callme();
The second argument of addEventListener has to be the function that is supposed to run.
In this case :
document.getElementById("nextPrev").addEventListener("click", function(){nextPrev(1)})
when you are wrapping in a function definition, the nextPrev function is not run. Here when this line is encountered in the code, the wrapper function is attached as an event handler.
In this case,:
document.getElementById("nextPrev").addEventListener("click", nextPrev(1))
you are not attaching anything.
Here as soon as this line is encountered in the code, the function is run. And the return value(undefined by default) is assigned as an event handler. That will do nothing on click.

Related

Is it discouraged to use "onlclick" with HTML element while using "addEventListener" method?

Before I explain my question, this piece of code is going to be considered:
HTML:
<div>
<button type="button" id="btn" onclick="disAl()">Click</button>
</div>
JS:
function disAl(){
var x = document.getElementById("btn");
if(x.addEventListener){
x.addEventListener("click", altTxt);
}
else if (x.attachEvent){
x.attachEvent("onclick", altTxt);
}
}
function altTxt(){
alert("Hello");
}
Now, if I run the program and click the button first time, nothing happens. However, from the second click the alert pops up. Interestingly enough, when I remove onclick="disAl()" from button element, and also remove the function definition from the script, the problem gets fixed. Like the following:
var x = document.getElementById("btn");
if (x.addEventListener) {
x.addEventListener("click", altTxt);
}
else if (x.attachEvent) {
x.attachEvent("onclick", altTxt);
}
function ...
....
So does it mean onclick="disAl()" method is unnecessary in my case?
Here is what is happening:
First time: Because of this part onclick="disAl()", you are setting up button click handler to a function called disAl(). Due to this, you get inside the function disAl() when you click the button.
When inside, you are again setting up click event handler to altTxt. This causes two handlers to be chained to click event. Then when you click second time, let's see what happens.
Second time: Now when the click happens, first disAl() is called which again unnecessarily sets up altTxt as click event handler. Once this handler is over, altTxt is called and that is when you see the alert.
Second case when you remove the function:
In this case, you are setting up button click event handler when your page is loaded since it is not a function anymore. So when you click the button, you call altTxt and see the alert.
So, yes disAl() is unnecessary in your case. Also, as a good practice, event handlers should not be set in the html but they should be set in the code by addEventListener. This allows you to remove event listener if you so desire by calling removeEventListener().
Hope this helps!
Yes you are right you are selecting document by jquery and writing event listener on it so you can just use like following.
function altTxt(){
alert("Hello");
}
var x = document.getElementById("btn");
if (x.addEventListener)
{
x.addEventListener("click", altTxt);
}
else if (x.attachEvent)
{
x.attachEvent("onclick", altTxt);
}

jQuery onclick call function

I've found a script that converts json file into quiz using jquery.
I am playing with it's code for almost a day now and I can't come with what I wanted to have.
Functions quiz().init(); and quiz().bindSubmit(); are called when page loaded.
What I want is the START button must be clicked first to load the Quiz.
$("#start").click(function(){
currentQuestion = 0;
questionCount = 0;
answerArray = [];
infoMode = false;
gotData = false;
inMemoryData = [];
quiz().init();
quiz().bindSubmit();
});
HTML:
<button type="button" id="start">Start</button>
<div id="quiz-content"></div>
It works at first click of START button also in the next clicks, it successfully reset the quiz and goes back to #1.
But the problem is after the first click of Start Button, the quiz won't work normally when submitting the quiz. The quiz began to stucked in #1.
For better understanding, JSfiddle here.
Edited:
Basically when the user click start button more than once,the quiz gets started from the beginning ,but didn't get to the next question(Gets stuck on the 1st question itself)
When you call bindSubmit function, inside it you are attaching to the submit event of the #quizForm. So when you press Start button twice, there two event handlers attached to the same event and that is because it is not behaving as it should be. So inside the bindSubmit function you need always disconnect all submit handlers ($(document).off('submit');), like this:
var bindSubmit = function () {
$(document).off('submit');
$(document).on('submit', '#quizForm', function (event) {
event.preventDefault();
next(this);
quiz().init();
});
};
Here is your original fiddle with mentioned update
https://jsfiddle.net/t4p8x02b/35/
There are couple of things i observed in your code, which needs to be rectified for better management of code:
There is no need to expose init() outside your quiz library, for first time initialization, you can call init() before your return from the library(end of quiz() module code).
Also exposing init() makes your quiz() module vulnerable since it can be modified by any external program which could spoil your entire quiz() logic.
Inside bindSubmit(), you dont need to re-initialize your quiz instance to call init(), rather just call init()(refer below code snippet), your event handler will call it without any error [This is the magic of Closure].
bindSubmit():
$(document).on('submit', '#quizForm', function (event) {
event.preventDefault();
next(this);
init();
});

Capturing 'enter' key on input not working

I'm going crazy trying to figure out why this isn't working... I have a text field and I want to capture when someone pushes enter so that the 'next' button can be focused.
This is more or less the input with id of 'guess'.
<input type='text' size='30' id='guess' autocomplete='off' value='' onMouseOver='javascript:this.focus();'>
I've added this event listener, but it's not activating...
document.getElementById('guess').addEventListener('keydown', focusnextbutton(event));
function focusnextbutton(e){
alert('you pushed a button');
if(e.keyCode == 13){
// alert('Button was enter');
// document.getElementById('next_btn').focus();
}
}
The 'you pushed a button' alert isn't even coming up and I cannot work out why. Help? I'm using Chrome on Ubuntu if that's relevant.
Not sure why it's not working either but if you change the line to:
document.getElementById('guess').addEventListener('keydown', focusnextbutton,false);
it will work fine
You have to remove the brackets after the focusnextbutton function.
document.getElementById('guess').addEventListener('keydown', focusnextbutton);
This is because the second argument of addEventListener is a function to call. When the code is run for the first time, addEventListener runs the second argument immediately and expects a function to be returned for the argument. For example, you could also do:
document.getElementById('guess').addEventListener('keydown', function(){
focusnextbutton(event);
});
The anonymous function as the second argument is a function definition and therefore is not run when the code is first evaluated, but IS run on keydown.
You will notice that the alert 'you pushed a button' is run immediately when the page loads. This is because the function is called while the event listener is being added and was key for debugging this error.
Try this
document.getElementById('guess').addEventListener('keydown',function(event){
focusnextbutton(event);
});
Pass the event argument to the callback function too. That's what's missing from the previous answers.
Fiddle Link

Input type=file onchange event won't fire when calling a user-defined function

I can't seem to make onchange fire for an input type of file. If I directly call an alert (like onchange="alert('a')"), it fires but if I call a user-defined function with only an alert inside, it doesn't. see below:
the html:
<input type='file' value='C:\fakepath' onchange="previewFile()"/>
the script:
function previewFile() {
alert("a");
}
http://jsfiddle.net/vDQxj/276/
The reason that's not working is kind of an artifact of using JSFiddle. In the left panel, you specified to execute the JavaScript onLoad. You need to use the option No wrap - in < head > which is normally where you would place JS in a real HTML file. Change that option / check out this version of your fiddle with the option changed.
http://jsfiddle.net/pxsjjgx5/
Here is the answer for your question. Use jQuery for this and write your code in place of alert in my code.
$("input[type=file]").bind("change", function() {
alert();
});

JavaScript/jQuery - textchange

I have a html- input type="text", and I want to add this tag an event handler that will work when the text is changes. The problem is that this input is getting his value from antoher javascript function and then the event handler isn't working.
For example
This is the event:
$("#inputid").change(function(){
alert('bla bla')
}
And this what need to raise the event
function inputvalue(){
$("#inputid").val="bla"
}
Unfortunately when the value of the input is changing (from the function inputvalue),it doesn't raise the event. If I put the value of the input manually the event is working
Any idea why the javascript doesn't reconize the text change from a script?
You can trigger the change event yourself in the inputvalue function:
function inputvalue(){
$("#inputid").val("bla").change();
}
Also notice the correction of your syntax... in jQuery, val is a function that takes a string as a parameter. You can't assign to it as you are doing.
Here is an example fiddle showing the above in action.
Your function has an error. Try this:
function inputvalue(){
$("#inputid").val()="bla"
}
EDIT
My function is also wrong as pointed in comments.
The correct is:
Using pure javascript
function inputvalue(){
document.getElementById("inputid").value ="bla";
}
Using jQuery
function inputvalue(){
$("#inputid").val("bla");
}

Categories