Javascript - calling/initialising a function from within a function - javascript

I've had a quick look but cannot find a specific answer for this query so thought I'd ask the experts. I'm still learning HTML and Javascript.
I have some code where I'm using the standard "body onLoad" function to run an "initialise" function located in the HTML doco head section. I have another function called "populateList(){...}" in the head which basically populates an array with data from an external file.
I want to initialise this list by calling the "populateList" function from within the "initialize" function. I've tried using populateList(); and other permutations but this doesn't seem to work. I assume this is a syntax query and should be straightforward so haven't included any code but will if it makes this clearer. Does the "populateList" function need to be specified before the calling function or does it iterate through functions before loading.
Thanks

Like this?
<html>
<head>
<script>
function initialise()
{
alert('initialise');
populateList();
}
function populateList()
{
alert('populate list');
}
</script>
</head>
<body onload="initialise()">
</body>
</html>
Demo: http://plnkr.co/edit/5HgzbiIHDXUijdSGSTzO?p=preview
If thats the case, Javascript works by loading scripts from top to bottom - so you will need to declare them in order.

Related

Function is not found in Jquery, but is found in Javascript

I have an html document in which a function is called like this
<div id="mon" class="topbar" onclick="verd()">
This calls a jquery function inside the body tag that goes like this
<script src="jquery.js">
function verd(){
$("#stillmain").empty();
} </script>
This returns the error:
Uncaught ReferenceError: verd is not defined
at HTMLDivElement.onclick
When I change the script to pure Javascript without Jquery however like this
<script>
function verd(){
$("#stillmain").empty();
} </script>
it does recognize the function verd(), can anyone explain what is going on, and how I could still use Jquery?
I am using the newest version of Jquery(just changed the name, nothing else).
When you give a script tag a src attribute it's going to load that source file in place of the script contents. So any script tags with a src should be kept empty.
You need to load jQuery by calling a script tag with its source on it, and then in a separate tag you can make your own script tag and write your custom JavaScript there.
<script src="jquery.js"></script>
<script>
function verd(){
$("#stillmain").empty();
}
</script>
Make sure that your custom scripts are loaded after jQuery.
If you want to run this as a jQuery function you need to use the proper syntax. Try the link below.
How to Create a jQuery Function
Also, you need to load jQuery in a separate tag or else none of your code will be ran other than the source of that script!

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

Access HTML element later in document through JavaScript

I am just starting out with JavaScript and I have a simple code that sends a value to an element with id p. I am currently declaring this function in a <script> in the <head> element of my document.
function writeP(resultSet) {
document.getElementById('p').innerHTML = resultSet.length;
};
writeP(results);
When I have this listed within the <head> element and run the webpage, firebug throws this error at me: TypeError: document.getElementById(...) is null.
However, if I move the code block into a <script> tag beneath the element and then reload the webpage, no problems and the script works as it should. Is there any reason for this, and a way I could make this work so I wouldn't have to define my functions beneath the element or include a onload on my body element?
Thanks for your help
Reason is that by the time your launch js code, DOM is not yet prepared, and JS can't find such element in DOM.
You can use window.onload (docs on W3schools) trigger to fire your functions after all elements are ready. It's same as having onload property on body element, but is more clear, as you can define it in your js code, not in html.
JS evaluates syncronically. Therefore, it does matter WHEN you declare the function. In this case, you're declaring it before the element actually exists.
Second, when you declare a function with that syntax, it does get eval'd inmediately. If you declared, instead
var writeP=function(resultSet) {
document.getElementById('p').innerHTML = resultSet.length;
};
you could save just the call to the end of the Doc, and leave the declaration at the beggining.
However, I would advise you to read a few jQuery tutorials to learn easier ways to deal with dom manipulation. Nobody runs raw JS for that task anymore.
jQuery includes an useful call to document ready event, which will save you a lot of headaches and is -IMHO- more efficient than the onload event. In this case, you would include the jQuery library somewhere in your code
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
and then add
<script>
jQuery(document).ready(function() {
var writeP=function(resultSet) {
jQuery('#p').html(resultSet.length);
};
writeP(resultSet);
});
</script>
just about anywhere in your document or an external js file, as it suits you.

Execute JavaScript code at the end when the HTML has been loaded

I want to execute a function at the end when the HTML has been loaded. I tried it with onload without success. I also tried it with ready, but it still doesn’t work. Here is my code. This is again placed in the header:
<script type="text/javascript">
$(document).ready(function() {
$('#infowindow_content').html('test');
});
</script>
The div is also set by an external JavaScript file. Content:
window.onload = initialize;
function initialize() {
document.getElementById('infowindow_content').innerHTML = 'testa';
}
It is included the following way before the closing body tag:
<script type="text/javascript" src="../lib/functions.js"></script>
I tried to place the above code before the closing body tag, but currently I have no idea why this doesn't work (the content isn't changed by my JavaScript code). If I execute it on the console afterwards everything works fine.
Solution:
I set a configuration parameter (language) in the HTML file. In the JavaScript file I ask for this value and depending on the value I define another content. Sometimes it could be so simple ...
Try this:
setTimeout(function() {
$(document).ready(function() {
$('#infowindow_content').html('test');
});
}, 20);
I don't know the jQuery equivalent but try the native JS.
Since the <body> has the most HTML & loads after <head>...
document.body.onload=function(){
yourFunction(args)
}
<body onload="yourFunction(args)">...</body>
Or maybe the window object, since it's the root of every webpage DOM...
window.onload=function(){
yourFunction(args)
}
Always place DOM manipulating code directly before your </body> tag. JavaScript in the header should only be called to libraries, such as jQuery.

AS3 navigateToURL(); javascript function not firing when using jQuery

I have a problem I cannot seem to solve. I am using AS3's navigateToURL(); function to call a simple javascript function. At the moment it just alerts the first parameter. The problem is, when this function is placed inside of the $(document).ready(function(){..}) block it does not fire. Example of my code:
<script type="text/javascript">
$(document).ready(function(){
function mapLink(aVar){
alert(aVar);
};
});
</script>
Example of simple AS3 call to function:
navigateToURL(new URLRequest('Javascript: mapLink("'+mapObject.tooltipMoreLink+'");'), '_self');
When the function is placed OUTSIDE of the jquery code, it works fine. Why does it need to be inside of the jquery code you may be asking? I need the jQuery DOM selectors to manipulate certain dom elements based on the value of 'aVar' in my javascript function.
Any guidance is welcomed with an open mind.
eh. this is what the ExternalInterface class was designed for.
You issue has to do with scope. Your function is scoped to the jquery object, and not globally, so it is invisible to your call. If you need jquery selectors, then you could easily set the flash var independently, followed by the jquery routine.
update
maybe I'm missing something, but shouldn't this be as be easy as:
function externalCall(param){
$(domElement).doSomething(param);
}
?
I wouldn't think this need be tied to the jq ready function. I mean, if flash has already loaded, and the user is interacting, then certainly the ready event has long since fired successfully.
Hope that helps. I'm not sure I'm following exactly what you're trying to do ;)
...
btw - I really would look into ExternalInterface, NavToURL may work, but you can call your js directly with the former method.
It won't work because you have created a function inside the DOMReady Event
that is $(document).ready and calling it from outside the scope of the function.
You can access jQuery DOM Selectors from anywhere provided you have referenced jQuery.js in your page.
Example
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js"></script>
<script type="text/javascript">
function mapLink(aVar){
alert(aVar);
}
</script>

Categories

Resources