How to pass argument if event handler is assigned in initialization function? - javascript

It is always good to separate presentation layer and behaviour between HTML and Javascript based on head first book.
They tell me not to do:
<textarea onclick="showAlert()"></textarea>
But instead, do below:
The example below separate the behaviour from HTML code (structure).
<html>
<head>
<script type="text/javascript">
window.onload = init;
function init() {
$('txt_area').onclick = showAlert;
}
function showAlert(say) {
alert(say);
}
</script>
</head>
<body>
<textarea id="txt_area"></textarea>
</body>
</html>
This allows HTML (structure) to look clean and "behaviour" part is initialized in init() function when page loads. I understand that so far.
But then I wonder how am I supposed to pass an argument to showAlert() function???
Below does not work, it will call the showAlert() as soon as the page loads and this is not what I want to because it needs to be fired onclick.
function init() {
$('txt_area').onclick = showAlert("hello");
}
Is it possible to pass arguments to showAlert() function but still separate the behaviour and structure?
UPDATE
Forgot to mention.. I'm using prototype.

Wrap your code in a function.
$('txt_area').onclick = function() {
showAlert("hello");
};

Related

Calling Javascript function from external file when loading html page

I want to load a function named james() from a Javascript file named hello.js which is added as an external file to index.html.
My problem is when the function james is declared inside $(document).ready(function()), it just says that 'james function is undefined' and is not called. How can I call function declared inside document.ready using onload?
<html>
<head>
</head>
<body onload= "james()">
<script src=hello.js>
</body>
</html>
hello.js javascript file
function mountApp{
$(document).ready(function(){
function james(){
alert("how can i get call ,when html page is loaded");
}
});
}
true method is, you create function outside document.ready function and then call
function james()
{
alert("how can i get call ,when html page is loaded");
}
$(document).ready(function(){
james();
)};
Your "james" function does not exist in the correct scope. It is declared inside the "ready" event listener and only exists inside the listener scope. After that, it won't be available anymore.
You cannot do what you are trying to do. Functions cannot be used outside of the scope they were declared in.
Move the function to the global scope instead.
function mountApp{
$(document).ready(function(){
// You can call the function from here
james();
});
}
function james(){
alert("how can i get call ,when html page is loaded");
}
Now, I don't see why you would be adding an event listener "onready" inside a function, because function calls will only be executed after the DOM is ready, so it will never trigger.

Javascript document.ready in multiple files with Gulp [duplicate]

If I have a lot of functions on startup do they all have to be under one single:
$(document).ready(function() {
or can I have multiple such statements?
You can have multiple ones, but it's not always the neatest thing to do. Try not to overuse them, as it will seriously affect readability. Other than that , it's perfectly legal. See the below:
http://www.learningjquery.com/2006/09/multiple-document-ready
Try this out:
$(document).ready(function() {
alert('Hello Tom!');
});
$(document).ready(function() {
alert('Hello Jeff!');
});
$(document).ready(function() {
alert('Hello Dexter!');
});
You'll find that it's equivalent to this, note the order of execution:
$(document).ready(function() {
alert('Hello Tom!');
alert('Hello Jeff!');
alert('Hello Dexter!');
});
It's also worth noting that a function defined within one $(document).ready block cannot be called from another $(document).ready block, I just ran this test:
$(document).ready(function() {
alert('hello1');
function saySomething() {
alert('something');
}
saySomething();
});
$(document).ready(function() {
alert('hello2');
saySomething();
});
output was:
hello1
something
hello2
You can use multiple. But you can also use multiple functions inside one document.ready as well:
$(document).ready(function() {
// Jquery
$('.hide').hide();
$('.test').each(function() {
$(this).fadeIn();
});
// Reqular JS
function test(word) {
alert(word);
}
test('hello!');
});
Yes you can easily have multiple blocks. Just be careful with dependencies between them as the evaluation order might not be what you expect.
Yes it is possible to have multiple $(document).ready() calls. However, I don't think you can know in which way they will be executed. (source)
Yes it is possible but you can better use a div #mydiv and use both
$(document).ready(function(){});
//and
$("#mydiv").ready(function(){});
I think the better way to go is to put switch to named functions (Check this overflow for more on that subject).
That way you can call them from a single event.
Like so:
function firstFunction() {
console.log("first");
}
function secondFunction() {
console.log("second");
}
function thirdFunction() {
console.log("third");
}
That way you can load them in a single ready function.
jQuery(document).on('ready', function(){
firstFunction();
secondFunction();
thirdFunction();
});
This will output the following to your console.log:
first
second
third
This way you can reuse the functions for other events.
jQuery(window).on('resize',function(){
secondFunction();
});
Check this fiddle for working version
Yes you can.
Multiple document ready sections are particularly useful if you have other modules haging off the same page that use it. With the old window.onload=func declaration, every time you specified a function to be called, it replaced the old.
Now all functions specified are queued/stacked (can someone confirm?) regardless of which document ready section they are specified in.
Yes, it's perfectly ok.but avoid doing it without a reason. For example I used it to declare global site rules seperately than indivual pages when my javascript files were generated dynamically but if you just keep doing it over and over it will make it hard to read.
Also you can not access some methods from another
jQuery(function(){}); call
so that's another reason you don't wanna do that.
With the old window.onload though you will replace the old one every time you specified a function.
It's legal, but sometimes it cause undesired behaviour. As an Example I used the MagicSuggest library and added two MagicSuggest inputs in a page of my project and used seperate document ready functions for each initializations of inputs. The very first Input initialization worked, but not the second one and also not giving any error, Second Input didn't show up. So, I always recommend to use one Document Ready Function.
You can even nest document ready functions inside included html files. Here's an example using jquery:
File: test_main.html
<!DOCTYPE html>
<html lang="en">
<head>
<script src="jquery-1.10.2.min.js"></script>
</head>
<body>
<div id="main-container">
<h1>test_main.html</h1>
</div>
<script>
$(document).ready( function()
{
console.log( 'test_main.html READY' );
$("#main-container").load("test_embed.html");
} );
</script>
</body>
</html>
File: test_embed.html
<h1>test_embed.html</h1>
<script>
$(document).ready( function()
{
console.log( 'test_embed.html READY' );
} );
</script>
Console output:
test_main.html READY test_main.html:15
test_embed.html READY (program):4
Browser shows:
test_embed.html
You can also do it the following way:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#hide").click(function(){
$("#test").hide();
});
$("#show").click(function(){
$("#test").show();
});
});
</script>
</head>
<body>
<h2>This is a test of jQuery!</h2>
<p id="test">This is a hidden paragraph.</p>
<button id="hide">Click me to hide</button>
<button id="show">Click me to show</button>
</body>
the previous answers showed using multiple named functions inside a single .ready block, or a single unnamed function in the .ready block, with another named function outside the .ready block. I found this question while researching if there was a way to have multiple unnamed functions inside the .ready block - I could not get the syntax correct. I finally figured it out, and hoped that by posting my test code I would help others looking for the answer to the same question I had

JQuery inside function call another function = undefined?

I want to call another function before body, but how?
The system shows me the error undefined function myx
I only can add code after body.
<script type="text/javascript">
jQuery(function($){
function myx() {
alert("omg");
};
});
</script>
</head>
<body>
<script>
jQuery(document).ready(function($){
$("mytest").click(function(){
myx();
});
});
</script>
Check
That function is out of scope. You need to define the function outside the jQuery callback.
<script type="text/javascript">
function myx() {
alert("omg");
};
</script>
</head>
<body>
<script>
jQuery(document).ready(function(){
$("#mytest").click(function(){
myx();
});
});
</script>
Check
Use external JavaScript, so it's cached into the Browser Memory, so when your Client visits again it will load faster. Then look at this:
// wrapper is same as $(document).ready() with no-conflict
jQuery(function($){
// should be defined once everything has loaded
function myx(){
// never use alert except to test
alert('OMG!');
}
// passing a function name like a var is the same as Anonymous function
$('#mytest').click(myx);
});
// Ignoring outer wrapper to save indenting - indent everything further
The important thing is that myx should be defined after everything has loaded.
You don't have to, but it's a best practice to use external JavaScript and put the <script> tags in the <head>, setting both <script type='text/javascript' src='yourUrl.js'></script> to be W3C Compliant. Additionally, technologically the document.body may not be available to some older Browsers if your <script> tags are defined in the <body>, as HTML must be defined before JavaScript is able to get it, which is why you use the Anonymous function inside of jQuery() (same as $(document).ready() or the JavaScript onload Event). Then you get the HTML with JavaScript because those Elements are available onload.

Javascript functions within Dojo script run without being called

I am feeling quite stupid about this, but I have a named function within my main Dojo require script that my intention was to run when called by a click event. However, the function runs on loading the page and does not run on the click event.
<script>
require(["esri/map", "dojo/domReady!"], function(Map){
var map = new Map("map");
testNode = document.getElementById("testNode");
testNode.onclick = test();
function test() {
alert("test");
}
}
</script>
<body>
<div id="testNode">Click Here To Test</div>
<div id="map></div>
</body>
As soon as the page loads the "test" alert pops up and nothing happens on the click event.
When you type
testNode.onclick = test();
You're calling the function test and passing the return value of the function to testNode.onclick. You should instead assign a reference of the function test to testNode.onclick:
testNode.onclick = test;

How to call a function in javascript without HTML?

This is the function
function seeHTML(elem){
var htmlTxt=document.getElementsByTagName('html')[0].innerHTML.toString();
elem.value=htmlTxt;
}
to call i use HTML
<input type="button" value="See HTML" onclick="seeHTML(txt)">
how to call it from another function as document.write
document.write(seeHTML(txt));
-- im a javascript begginer
however i tried document.write but it prints the function data itself, it doesnt use the function, how to ask it to use it then print the return (result)
function foo(element) {
seeHTML(element);
}
function seeHTML(element) {
}
foo(document.getElementsById('element'));
in JavaScript code:
<script type="text/javascript">
document.addEventListener("DOMContentLoaded", call_your_function_here);
</script>
Here we created an event listener it means when the document is fully loaded the function() will be called, using the same way you can add any event listener to any DOM object, ex. you have a button with id="test", var btest = document.getElementById('test'); then
btest.addEventListener('click', function() { //execute code if btest object was clicked });
Bottom line you should call your function when the document is fully loaded hence replace the call_your_function_here() with your function name and if you wanted to reference the same button your function was embedded in use this syntax to reference the button DOM object:
var buttonObj = document.getElementById(buttonID);
then supply buttonObj to your function's argument.

Categories

Resources