window.myFunction = myFunction vs. onclick="mySecondFunction()" - javascript

Let's say I've got an HTML page that looks somewhat like this
...
<h1>Title</h1>
<button id="myFirstButton">my first button</button>
<button id="mySecondButton" onclick="myClickFunction()">my second button</button>
<script src="myJavascript.js"></script>
...
And the myJavascript.js looks like this
...
window.myClickFunction = myClickFunction;
document.getElementById("myFirstButton").addEventListener("click", () => {
console.log("clicked on first button!");
});
function myClickFunction() {
console.log("clicked on second button!");
}
...
This code works fine. But I've got a couple questions.
What is the difference?
In which cases should I use which approach?
Why does myClickFunction() not work when I don't use the window.myClickFunction = myClickFunction?

When you declare a function myFunction in the global scope, it IS window.myFunction so
window.myClickFunction = myClickFunction; is the same as doing myfunction=myFunction it has no effect whatsoever.
To answer #3, we need to see more code. Perhaps you did NOT declare myClickFunction in global scope but inside an event handler or something
For example
window.addEventListener("load",function() {
function myFunction() { console.log("hello"); }
})
function myFunction1() {
console.log("hello from myFunction1");
myFunction(); // not in window scope
}
myFunction1()

Related

I want to call a function on onclick but that function should be inside another function

Javascript code:
function abc() {
function def() {
//do something
}
}
HTML code:
<button onclick="def()">click me</button>
I get the error def() is not defined.
Try this.
function def(){
//do something
}
function abc(playDef){
if(playDef){
def()
}
}
<button onclick="def(true)">click me</button>
For more functions you can pass arguments and manage if condition
You only need to declare def in global scope:
function abc(){
window.def = function(){
console.log("hello, I'm function def");
}
}
abc();
def();
But remember you need to call abc first to get access to def function.
Hope this helps. Good luck.
I have completed my answer with a code snippet, you can try the working solution:
function abc(){
window.def = function(){
console.log("hello, I'm function def");
}
}
abc();
<button onclick='def();'>Click Me!</button>

Trigger function only on "onclick"

Hello I need a function to run when an a tag is clicked. I am using the onclick="" but it seems that the function runs on page load, instead of waiting to run when the a tag is clicked on. How do I make it so the function only runs when the a tag is clicked?
Here is my code.
HTML:
<a class="req_btn" onclick="conversionOne()">text</a>
<script type='text/javascript'>
(function conversionOne() {
alert("something");
})();
</script>
Thanks!
You are invoking the function when the script loads using an IIFE. Instead of this:
(function conversionOne() {
alert("something");
})();
Do this:
function conversionOne() {
alert("something");
}
You are using a self-executing function.
Declare the function in the global scope without executing it.
function conversionOne() {
alert("something");
}
Doing this
(function(){
/** code **/
})();
Means the code will be executed imediatelly.
in your case you want to create a function so you need this :
function conversionOne() {
/** code **/
}
or
var conversionOne = function () {
/** code **/
}
(function conversionOne() {
alert("something");
})();
calling function like this will work onload
Change this to
function conversionOne() {
alert("something");
};
More info

How to call javascript function from ScriptManager.RegisterStartupScript?

I have the following javascript code:
<script type="text/javascript" language="javascript">
$(document).ready(
function () {
// THIS IS FOR HIDE ALL DETAILS ROW
$(".SUBDIV table tr:not(:first-child)").not("tr tr").hide();
$(".SUBDIV .btncolexp").click(function () {
$(this).closest('tr').next('tr').toggle();
//this is for change img of btncolexp button
if ($(this).attr('class').toString() == "btncolexp collapse") {
$(this).addClass('expand');
$(this).removeClass('collapse');
}
else {
$(this).removeClass('expand');
$(this).addClass('collapse');
}
});
function expand_all() {
$(this).closest('tr').next('tr').toggle();
};
});
</script>
I want to call expand_all function via code-behind .
I know I can use something like this, but it does not work and I don't understand used parameters:
ScriptManager.RegisterStartupScript(Me, GetType(String), "Error", "expand_all();", True)
Can you help me?
Because you have your expand_all function defined within anonymous $.ready event context. Put your code outside and it should work.
function expand_all(){
alert('test B');
}
$(document).ready(
function () {
// this won't work
function expand_all() {
alert('test A');
};
});
// will show test B
expand_all();
check this:
http://jsfiddle.net/jrrymg0g/
Your method expand_all only exists within the scope of the function inside $(document).ready(...), in order for you to call it from ScriptManager.RegisterStartupScript it needs to be at the window level, simply move that function outside the $(document).ready(...)
<script type="text/javascript" language="javascript">
$(document).ready(
function () {
....
});
function expand_all() {
$(this).closest('tr').next('tr').toggle();
};
</script>

Reference error: myFunc is not a function

I'm having a problem with my function that is showing type error. In summary I've the code like below:
function myFunc(){
alert('test');
}
//if I run myFunc() here then it runs
myFunc();//alerts test
$('.selector').click(function(){
myFunc();//type error:: how to call the function?
});
Sorry, if this is a stupid question.
Update
I've just reproduced my key problem:
demo
window.onload = function(){
function myFunc(){
alert('test');
}
}
$('.test').click(function(){
myFunc();//doesn't alert test
});
myFunc is scoped to the function it is declared inside.
Move it outside or move the event handler assignment inside.
// Define this in a script element after the element you are trying to select
function myFunc(){
alert('test');
}
$('.test').click(function(){
myFunc();
});
// or use this anywhere
window.onload = function(){
function myFunc(){
alert('test');
}
$('.test').click(function(){
myFunc();
});
}
// but if you are going to use jQuery, you might as well go the whole hog
// and also just wait for the DOM to be ready instead of allowing time for images
// and other external resources to load too.
$(function(){
function myFunc(){
alert('test');
}
$('.test').click(function(){
myFunc();
});
});
Your function is defined in the scope of another function and is unreachable. You should put it in the scope of the calling function, e.g.:
function myFunc() {
alert('test');
}
$(function() {
$('.test').click(function() {
myFunc();
});
});

Pass function to a jquery key event?

I have a function foo(peram) which I want to call from multiple jquery .keyup() events.
How can I define/pass function foo so that I can call it from inside the event?
I tried something like this:
function foo(peram) {
alert(peram);
}
$("#someElement").keyup(function(alert) {
foo("You pressed a key!");
});
However I get TypeError: foo is not a function.
Update:
I have removed everything from my script and html, and it still does not work.
html:
<html>
<head>
<script src="../jquery-1.10.2.js" type="text/javascript"></script>
<script src="test.js" type="text/javascript"></script>
</head>
<body onload="asdf()">
<input type="text" name="name">
</body>
</html>
test.js:
function asdf() {
function hqxftg(stuff) {
alert(stuff);
}
$(document).ready(function() {
$('[name="name"]').keyup(function(hqxftg) {
alert(typeof hqxftg)
hqxftg("asdf");
})
})
}
It does seem to work in jsfiddle for some reason.
It is because you have named the event parameter same as the function
function asdf() {
function hqxftg(stuff) {
alert(stuff);
}
$(document).ready(function () {
$('[name="name"]').keyup(function (event) {
alert(typeof hqxftg)
hqxftg("asdf");
})
})
}
The event callback keyup receives the event object as the first parameter, you are naming it as hqxftg which overrides the external scoped function name.
Also there is no need to use the onload="", you can just use the dom ready callback
jQuery(function ($) {
function hqxftg(stuff) {
alert(stuff);
}
$('[name="name"]').keyup(function (event) {
alert(typeof hqxftg)
hqxftg("asdf");
})
})
You are missing a couple of things...
1) You miss the ; at the end of calling foo()
2) You are missing tags to close the jQuery selector
When you try this it will work:
function foo(peram) {
alert(peram);
}
$("#someElement").keyup(function(alert) {
foo("You pressed a key!");
});
JSFiddle here...
Update: Post has been updated and original comment of mine becomes obsolete.
I would go with the comment of Derek.
I am able to reproduce the problem: JSFiddle
Is it correct you have also foo declared as a var?
Try this code.
HTML
<input id="someElement" />
Java script:
function foo(peram) {
alert(peram);
}
$( document ).ready(function() {
$("#someElement").keyup(function() {
foo("You pressed a key!");
});
});
Demo

Categories