Why does onclick() function run automatically without clicking [duplicate] - javascript

This question already has answers here:
onclick function runs automatically
(4 answers)
Closed 1 year ago.
I am wondering why doStuff() is called without clicking.
function pageReady() {
var buttonBox = document.getElementById("buttonBox");
buttonBox.onclick = doStuff();
function doStuff() {
buttonBox.style.background = "orange";
buttonBox.style.width = "600px";
buttonBox.innerHTML = "<h2>SURPRISE!!</h2>";
}
}

You're invoking the function, you should change
buttonBox.onclick = doStuff()
to
buttonBox.onclick = doStuff;
Now you're passing the function to the handler without invoking it.

Related

Void function return value is used JavaScript [duplicate]

This question already has answers here:
Why does click event handler fire immediately upon page load?
(4 answers)
Closed 1 year ago.
let btn = document.createElement("button");
btn.id = "submitBV"
let firstRow = 12
let lastRow = 59
btn.addEventListener("click", autoInput(firstRow, lastRow))
function autoInput(firstRow, lastRow){
print()
}
It tells me Void function return value is used (screenshot).
After I add a return 1, it doesn't solve as well (screenshot2).
Yes, because you are invoking the autoInput function which does not return something (void) valid. To handle this, to need to pass a function in order to be called when the click event is triggered by the button. In this case, you can add a simple function to do this.
btn.addEventListener("click", function() { autoInput(firstRow, lastRow); })
If you have a function which returns another function (if you are new to javascript, yes, it is possible) it may work fine, which is not your case on the autoInput function.

Why there is some delay caused by a JavaScript function that isn't supposed to run immediately? [duplicate]

This question already has answers here:
Why is the method executed immediately when I use setTimeout?
(8 answers)
Calling functions with setTimeout()
(6 answers)
Closed 3 years ago.
I have two functions, showhide and getSourceCode. I want showhide to execute (hide a dialog box) immediately after submit, but getSourceCode is pretty long so I make it execute later. However, some delay still occurs between I click submit and showhide comes to effect. When I remove getSourceCode, the dialog box can disappear immediately, but it is always delayed as long as there is getSourceCode, even when I setTimeout it.
document.querySelector("[type=submit]").onclick = function (event) {
showhide('dialogBox');
if (options[0].checked) {
setTimeout(getSourceCode(),10000);
}
}
function getSourceCode() {
var htmlastext = ajax("something.aspx");
function HTML(text) {
this.fullCode = (new DOMParser()).parseFromString(text, "text/html");
this.scripts = this.fullCode.querySelectorAll("script[src]");
this.style = this.fullCode.querySelector("link[rel=stylesheet]");
this.images = this.fullCode.querySelectorAll("img");
this.replaceContent = function (content, element, tag) {
var newElement = this.fullCode.createElement(tag);
newElement.innerHTML = content;
element.parentNode.replaceChild(newElement, element);
}
this.modify = function () {
var externalContent;
var serverpath = window.location.origin;
for (var i = 0; i < this.scripts.length; i++) {
externalContent = ajax(this.scripts[i].src.slice(serverpath.length));
this.replaceContent(externalContent, this.scripts[i], "script");
}
externalContent = ajax(this.style.href.slice(serverpath.length));
this.replaceContent(externalContent, this.style, "style");
var removeTagList = [
this.fullCode.getElementById("logout"),
this.fullCode.getElementById("saveHTML"),
this.fullCode.getElementById("dialogOverlay"),
this.fullCode.querySelectorAll("script")[4],
this.fullCode.querySelector("link")
];
for (i=0; i<removeTagList.length; i++) {
removeTagList[i].parentNode.removeChild(removeTagList[i]);
}
}
}
var htmlDoc = new HTML(htmlastext);
var html = htmlDoc.fullCode;
htmlDoc.modify();
htmlastext = (new XMLSerializer()).serializeToString(html);
var txtarea = document.createElement("textarea");
txtarea.innerHTML = htmlastext;
htmlastext = txtarea.value;
document.getElementById("encodedSourceCode").value = btoa(htmlastext);
}
Why does delay occur in showhide? Aren't JavaScript functions synchronous? Isn't setTimeOut able to prevent the parameter function from execution before the timeout? How can I hide the dialog box right after submission, without removing getSourceCode?
The problem is in this line:
setTimeout(getSourceCode(),10000);
because getSourceCode function gets called immediately (because of () after it), and only its return value passed to setTimeout.
Remove the parentheses after your function, then, your function will be passed to setTimeout, and it will internally call it.
setTimeout(getSourceCode,10000);

Javascript this context binding [duplicate]

This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
How does the "this" keyword work, and when should it be used?
(22 answers)
Closed 4 years ago.
I am trying to understand the bind method and I have written the below code :
//
//Window Context
function Hello(d) {
//Always this reffers to calling context
console.log(d);
}
Hello("ABC");
function Student(sname) {
this.name_n = sname;
this.hello = Hello;
this.printAfter2Seconds = printAfter2Seconds.bind(this);
this.print = function() {
console.log(`Student Name: ${this.name_n}`);
}
}
printAfter2Seconds = function() {
console.log(`Before Set TimeOut - ${this.name_n}`);
//let that = this;
setTimeout(function() {
//console.log(this);
console.log(`After Set TimeOut - ${this.name_n}`);
},2000);
}
function Department(dname) {
this.name_n = dname;
this.hello = Hello;
this.printAfter2Seconds = printAfter2Seconds.bind(this);
}
let s = new Student("ABC");
s.hello(s.name_n);
s.printAfter2Seconds();
let d = new Department("IT");
d.hello(d.name);
d.printAfter2Seconds();
//
If I comment the setTimeout line and the line ending setTimeout like below :
//setTimeout(function() {
//console.log(this);
console.log(`After Set TimeOut - ${this.name_n}`);
// },2000);
I am getting the expected output ABC and IT. But If I include setTimeout I am getting undefined both time. So I am guessing some where I need to invoke bind again. This may not be a trivial example that you use everyday just trying to understand bind.
So I need to understand how to bind the this context of the function inside setTimeout or that is even possible.
Thanks in Advance.

How do I run this function on page load? [duplicate]

This question already has answers here:
How do I call a JavaScript function on page load?
(8 answers)
Closed 6 years ago.
I have to wrap my functions in a namespace. How do I run my function on page load in this format?
window.myFunction = { submitButton: function () {
document.getElementById('button').value='My text';
}
window.onload = submitButton;
};
If I write this without the namespace, it works fine
function submitButton() { document.getElementById('button').value='My text'; }
window.onload = submitButton;
myFunction in your example is an object not a function and submitButton is a property of that object, to access it you'll do this:
window.onload = window.myFunction.submitButton;
update
Something like this will run multiple functions.
window.onload = function(){
for(var prop in window.myFunction) {
if(window.myFunction.hasOwnProperty(prop) && typeof window.myFunction[prop] === 'function') {
window.myFunction[prop]();
}
}
};

Preventing default, then applying default in JavaScript [duplicate]

This question already has answers here:
Is there a [universal] way to invoke a default action after calling event.preventDefault()?
(5 answers)
Closed 8 years ago.
Once preventDefault(); is called, how can I invoke that event that was just prevented?
For example:
$("a").click(function(e){
setTimeout(function(){
e.huh? // run original function
},5e3);
});
This will work
$("a").one("click", function (e) {
e.preventDefault();
var elem = this;
setTimeout(function () {
elem.click();
}, 2000);
});
http://jsfiddle.net/XyETg/3/

Categories