Call JQuery function in JavaScript function - javascript

I got this JQuery code:
file: code.js
jQuery(function(){
function renderSVG(){
//Something
};
});
File: index.html
<script>
function mostrarOdonto() {
renderSVG();
};
</script>
But i got a problem here:
http://i.gyazo.com/9550a64fc16c7570107706fb2162d84f.png in renderSVG() inside mostrarOdonto()
"Uncaught ReferenceError: renderSvg is not defined"
I tried $renderSVG(); but doesnot work. Anyone can help me?
Thanks so much!
PD: Sorry bad english

That is caused by javascript closures. It is local within the jQuery call and not accessible outside. You can read more about it here: MDN Documentation
You can declare objects outside of the jQuery function call to have it available globally. i.e.:
function RenderSVG(){
//Do Stuff
}
jQuery(function(){
RenderSVG();
});
This ensures that it is accessible outside the jquery scope
or if you really need it within jQuery you can go the route of a jQuery Plugin a la: jQuery docs
Example:
(function( $ ) {
$.fn.renderSVG = function( options ) {
//Do Stuff with canvas since it would be referenced in this.
};
}( jQuery ));
Then you can call it like: $('#mycanvas').renderSVG({/*options*/});
Update 1:
You have to ensure when your code is called after loading jQuery and any plugins.
in your <head> tag
you should put <script src=".../jquery.min.js"> or whatever your file for jquery is called
followed by any plugin scripts ...src="jquery.svg.js", then you put your code:
<script>
function RenderSVG(){
}
//And most important is that you call it after it is ready. In this example
//I use jQuery(window).load you can also use jQuery(document).ready
jQuery(window).load(function(){
RenderSVG();
});
</script>
if it still doesn't work you have to ensure the library for the svg methods aren't doing something weird. To be sure we would have to know the library you are using.

The function renderSVG() is a local function,since it is inside jQuery(function(){ }. It is valid only in that scope , So it is not accessible via other scopes. So try it like this.
<script>
jQuery(function(){
function mostrarOdonto() {
renderSVG();
};
};
</script>

You can Do it in this way JSFIDDLE LINK
HTML:
<input type="button" value="go" onclick=" mostrarOdonto();">
Scripts:
$.renderSVG = function() {
alert("I am calling form jquery");
};
$(document).ready(function() {
alert("function is ready to use now");
});
function mostrarOdonto() {
$.renderSVG();
};
This should work as per your requirement. The Jquery part can go into your Code.js file.

I think could help you it's simple and straight forward
$(document).ready(function() {
mostrarOdonto();
});
function renderSVG() {
alert("Testing purpose only");
};
function mostrarOdonto() {
renderSVG();
};

Related

How can I access the function which inside different js file in JQUERY?

There is a script which named Normal.js in the HTML:
$(function () {
function WhiteNav() {
$("#LOGO>img").attr('src', '/images/LOGOWhite.svg');
$("#NavUL a").css("color", "#cecece");
}
});
And here is the struct of the HTML as below:
However, after the browser(Chrome) ran the WhiteNav function in the script, it reported this error and the WhiteNav failed:
Why it turned out to be this? It seems like I ran the code with a different file, is it right? I tried the way as Why jQuery click doesn't work when included in a separate file said but failed again.
What's wrong with this? How can I solve this problem? Would you please help me? Thank you.
You're declaring WhiteNav inside of a function() { ... }, meaning it will only be accessible from within that function.
Simply remove the $(function () { ... }); from around it, and it will be declared globally - accessible from anywhere after it's declaration.
As a side-note, you can remove $(function () { ... }); from your internal <script> snippet as well. $(function () { ... }); and $(document).ready(function() { ... }); are identical and so there is no need for both. The latter is just shorthand.

Imported js function throw a not defined error

I am getting this error validate_allocation is not defined when trying to execute a function from a static file. Any idea why?
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="static/main.js"></script>
<script>
validate_allocation();
</script>
main.js
$(function() {
alert('test'); // I can see this, so the file is imported for sure
function validate_allocation(){
alert('test');
}
});
The purpose of $(function() { ... }); is to run the code inside once the page has finished loading. As others have said, you're defining a function not only after the page has finished loading (and therefore after the call is made in your HTML file), but it is also limited to the scope of that block. It can safely be moved out of the block:
// Declare function at the root of the document and make it accessible to the HTML page
function validate_allocation(){
alert('test');
}
// Actions to perform when the page has completed loading
$(function() {
alert('test'); // I can see this, so the file is imported for sure
});
Remove the Validate_allocation function from jquery onload function. Since you are writing in that function it will be scoped to that function only.
function validate_allocation(){
alert('test');
}
$(function() {
alert('test'); // I can see this, so the file is imported for sure
});
This will make the function globally accessible

Call external js file function in Angular js controller

I have the external js file which has more functions.
I need to call these functions from angular controller.
For example: external.js
...
...
function fun() {
...
...
}
...
...
Controller: acccountController.js
myApp.controller('AddAccountController',function ($scope,AddAccountLoginServices,$location,localStorageService,$compile,toaster){
....
....
$scope.getLoginForm = function(siteId,name) {
...
...
fun(); // This function from external.js file
});
...
...
});
I have imported external.js before the acccountController.js. But it doesnt calling that function. And also i have not get any console error for this.
How to achieve this... Thanks in advance.
EDIT: gave wrong answer, my bad. the following example works.
your external file should like this:
var doSomething = (function () {
"use strict";
return {
test: (function () {
return 'test';
}()),
test2: (function () {
return console.log('test 2');
})
};
}());
and in your controller you call your scripts function:
console.log(doSomething.test);
or
doSomething.test2();
i learned something too, thanks ;)
As mentioned by #nilsK, you define a self invoking function. And then reference to it via window object. For example -
(function functionName(){
Do Something Here...
})();
And then,
window.functionName();
And if your are using AngularJS,
$window.functionName();
I have similar situation and I did not have to make it self invoking function. Including the external js file into the html and it worked fine.
Where is you call $scope.getLoginForm()?. I think you never call it. So fun() is not called, so you not see any thing. You need call $scope.getLoginForm(). Two way to call
In HTML <button ng-click="getLoginForm()"></button>
Or in Javascript $scope.getLoginForm()
Good luck !
You need to create a global instance of the function.
Add a line:
var abc= new funcName();
at the end of the File and you can use this line (var abc= new funcName();) in your controller to invoke any methods from this file by using abc.methodName.

use 2 jquery functions

I would like to ask on how I can use both functions once the page loads
jQuery(document).ready(function($)
{
$('#list').tableScroll({height:500});
});
and
jQuery(document).ready(function($)
{
$('#list').tableSorter();
});
jQuery(document).ready(function($) {
$('#list').tableSorter().tableScroll({height:500});
});
jQuery supports method chaining.
jQuery(document).ready(function($) {
$('#list')
.tableScroll({height:500})
.tableSorter();
});
jQuery(document).ready(function($)
{
$('#list').tableScroll({height:500});
$('#list').tableSorter();
});
Just put both under one DOM ready handler and use chaining:
$(document).ready(function() {
$("#list").tableScroll({ height: 500 }).tableSorter();
});
$(document).ready(function() {
$("#list").tableScroll({ height: 500 }).tableSorter();
});
I guess its fine to have more than one
jQuery(document).ready(function($) { .... }
both will be called on page on load body :). irrespective of no of call`s made, all will be called on page load only.
Simple, use
jQuery(document).ready(function() {
$('#list').tableScroll({height:500}).tableSorter();
});
There is a shorter version of jQuery(document).ready(function()) that you could use that would have the same result:
$(function() {
// code to execute when the DOM is ready
});
For this situation, using the elegant chaining:
$(function() {
$('#list').tableSorter().tableScroll({height:500});
});
For a discussion of the difference between these two approaches, see this very helpful question.
Here's how I would do it:
// Create an immediately-invoked function expression
(function ($) {
// Enable strict mode
"use strict";
// Cache the selector so the script
// only searches the DOM once
var myList = $('#list');
// Chain the methods together
myList.tableScroll({height:500}).tableSorter();
}(jQuery));
Writing your jQuery in an IIFE like this means you can run the code alongside other libraries that also use $, and you won’t get conflicts.
Be sure to include this JavaScript at the end of your document, just before the closing </body> tag.

Scope of my jQuery function?

I have a file called function.js which has all my jQuery for my aplication which looks like this
$(document).ready(function(){
insert_initial(); //first time to the page, insert into cart and set the subtotal originally
function update_gallery(product_id){
...
}
function update_prices(product_selector){
...
...
}
function insert_initial(){
...
}
$('.trigger').click(function(){
$('.stations').find(".drop-down").slideToggle();
return false;
});
...
...
On the top of the file i have my function call insert_initial(); which gets run on the initial load....and this works great..My problem is that i now need to include this js file on my php pages say 1.php and 2.php and 3.php and 1.php is the only one that needs the insert_initial(); ....so i was thinking of the best way to do this. I assumed taking out the function call out of the functions file and putting it into a separate file
<script src="/someting/js/functions.js" type="text/javascript"></script>
<script src="/someting/js/functions_insert.js" type="text/javascript"></script>
and in my functions_insert.js file i would have only
$(document).ready(function(){
insert_initial(); //first time to the page, insert into cart and set the subtotal originally
});
but that didnt work either...any ideas on how to fix this
This checks to make sure that the location of the current page includes "1.php" before calling insert_initial():
if(window.location.href.indexOf('1.php') != -1)
insert_initial();
I would recommend having your definitions and executions separate in this instance. You don't need to define your functions inside of jQuery's DOM ready event. But it is also good to namespace them as mentioned. A common paradigm I follow is like so:
functions.js
(function($, window, undefined) {
function update_gallery(product_id){
...
}
function update_prices(product_selector){
...
...
}
function insert_initial(){
...
}
window.MyApp = {
update_gallery: update_gallery,
update_prices: update_prices,
insert_initial: insert_initial
};
})(jQuery, window);
1.php
<script src="functions.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
MyApp.insert_initial();
});
</script>
Now you can include your definitions as needed, and call them as necessary.
Try namespacing your functions and attaching them to a nice global object.
window.MyApp = {};
MyApp.insert_initial = function(){
};
Then you can access it from wherever you need, provided it's included earlier in the page.
Edit:
If this doesn't work, you've got an error elsewhere in your code - load order, perhaps? Either method you've described to invoke the function is fine, just make sure it's defined when you invoke it.
Your functions defined in functions.js are only visible in the scope of that document ready function. A simple case where it doesn't work:
(function() {
function square(x) {
return x*x;
}
})();
alert(square(2)); //Fails, since square is not in scope
The easiest way to fix this is to declare your functions in the global namespace:
function square(x) {
return x*x;
};
alert(square(2)); //4

Categories

Resources