Call function defined inside $(document).ready() - javascript

In and external JS file I have
$(document).ready(function() {
var example = function(){ alert("hello") }
});
and I want to call that function from my html, how would I do that?
<img src="..." ondblclick="example()" />
n.b. I'm aware of jquery dblclick() but curious about how to correctly do the above.

$(document).ready(function() {
window.example = function() {
alert("hello")
}
});
Or define it outside, if possible. It doesn't look like it has to be defined inside document ready at all.

The other solutions here will work, but structurally in your project, the best solution is to remove the event handling code from the HTML and hook up the event entirely via javascript (separate the HTML/JS). Since you already have jQuery in your project, this is very easy. To do that, all you need to do is to put some sort of identification on the image:
<img id="example" src="..." />
Then, in you can just hook up the event code in your ready() function like this
$(document).ready(function() {
$("#example").dblclick(function() {
alert("Hello");
});
});
This has the following advantages:
It creates no global variables - reducing the global namespace pollution.
It separates the HTML from the javascript which keeps all code governing the behavior in one compact spot and is usually a good thing
Using event listeners is a bit more scalable than using .ondblclick - allowing multiple different parts of code to use non-conflicting event handlers on the same object

Your function should be global (in fact, property of window object) if you want to access it from HTML. But best practice is to avoid global variables and functions, using namespace instead:
// let's publish our namespace to window object
if (!window.myNamespace){
// creating an empty global object
var myNamespace = {};
}
// and add our function to it
$(document).ready(function() {
myNamespace.example = function(){ alert("hello"); }
});
We can use it in HTML like this:
<img src="..." ondblclick="myNamespace.example()" />

The best option would be to simply define the function outside document.ready(). There is no reason defining the function within the $(document).ready() event is necessary, as if you call the function within the $(document).ready() function, the document is guarenteed to be ready.
However, you can also define the function on the global window object, like so:
$(document).ready(function() {
window.example = function(){ alert("hello") }
});

You can either move the function declaration outside of the DOM-ready handler:
function example(){ alert("hello") }
$(document).ready(function() {
// code
});
But the better solution is to keep JavaScript in your .js files and avoid the inline event handlers. Give your element an id and fetch it:
<img src="..." id="imgid" />
$(document).ready(function() {
document.getElementById("imgid").ondblclick = function(){ alert("hello") }
});

#Esailija has answered it correctly but if you want to keep it as it is then simply remove var and make it global.
var example;
$(document).ready(function() {
example = function() {
alert("hello")
}
});
If you do not put var the variable/function/object becomes global. Using var you were setting its context within document.ready function.

Related

How to call javascript function inside jQuery

We have this tag with a javascript function in our HTML,
<select name="My_Saved_Billing" onchange="Choose_My_Saved_Billing(this.selectedIndex)" >
<option>Select</option>
<option value="1714">Address line 1, QC</option>
</select>
<script type="text/javascript">
function Choose_My_Saved_Billing(arg_index) {
switch(arg_index) {
// some commands here
}
}
</script>
And I also added a jQuery to it which is below so that on windows load, it will automatically select the second option.
<script type="text/javascript">
$(window).load(function(){
$("select").val($("select option:eq(1)").val());
});
</script>
But is it possible to call javascript function using jQuery? If so, how should I call this one?
Should I use Choose_My_Saved_Billing(this.selectedIndex)or Choose_My_Saved_Billing(arg_index)or you might know something. I've tried these two but none are working. Please let me know. Just a beginner here.
The way to call a JavaScript function from a JQuery file is the same as calling a JavaScript function from a JavaScript file :) This is so because JQuery is a library based from JavaScript. Say, you want to call function foo from a JavaScript file, when the window loads.
JQuery:
$(window).on('load', function() {
foo();
});
And JavaScript:
function foo() {
alert('This works!');
}
I hope this helps!
Yes, it's possible to call functions inside a jQuery ready block. Since you've defined the function at global scope (should probably move this into the jQuery ready block or, if you want to go to the trouble, into a module), it can be called from anywhere. So inside your ready block:
$(function () {
// do stuff
Choose_My_Saved_Billing(args);
});
jQuery is JavaScript. It's just a library for JavaScript. The main jQuery global $ is a JavaScript function that takes a valid selector as an argument and provides several methods on the return value of that function.
So calling a JavaScript function inside the callback function to .load is not an issue.
It is not clear what the Choose_My_Saved_Billing function actually does.
Think about what's happening here. In your onchange event you're calling the function with the index of the selected option passed as an argument. Since JQuery is just a library of shortcuts for things you can do in JavaScript, we should easily be able to do the same thing.
So let's get the element for which we want the selected index:
// maybe think about adding an ID here for better selection
var select = $('select[name^="My_Saved_"]');
Then let's get the index with a change event, then call the function:
var index = 0;
select.change(function(){
index = select.selectedIndex || 2; // set the index to default to 2
Choose_My_Saved_billing(index);
});
Instead of using onchange="...", just use jQuery to attach a change listener:
$(window).load(function() {
$('.colors_backgroundneutral select').on('change', function () {
Choose_My_Saved_Billing(this.value);
});
});
$(document).ready(function() {
$("#Submit1").click(function() {
$("#id1").hide();
Raise1();
});
$("#Raise").click(function() {
$("#id1").show();
});
});
function Raise1() {
var value1;
alert("hi");
value1 = document.getElementById("amount").value;
alert(value1);
alert("done");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.0.1/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.1/jquery.min.js"></script>
As jQuery is a more simple and advanced JavaScript solution, my guessing is you can call you JS function like this:
$(window).load(function(){
my_js_function(arg1, arg2);
});
Now, what you want is to call the JS function named Choose_My_Saved_Billing() with argument arg_index
So, your jQuery will look like this:
$(window).load(function(){
Choose_My_Saved_Billing(arg_index);
});
This only works if the function is already declared through raw code, on via the <script type="text/javascript" src="path/to/my_file.js"> head tag.
It should work like a charm, if not, feel free to share the errors returned by your browser.

How do I use a function as a variable in JavaScript?

I want to be able to put the code in one place and call it from several different events.
Currently I have a selector and an event:
$("input[type='checkbox']").on('click', function () {
// code works here //
});
I use the same code elsewhere in the file, however using a different selector.
$(".product_table").on('change', '.edit_quantity', function () {
// code works here //
});
I have tried following the advice given elsewhere on StackOverflow, to simply give my function a name and then call the named function but that is not working for me. The code simply does not run.
$(".product_table").on('change', '.edit_quantity', function () {
calculateTotals() {
// code does not work //
}
});
So, I tried putting the code into it's own function separate from the event and call it inside the event, and that is not working for me as well.
calculateTotals() {
// code does not work //
}
So what am I doing wrong ?
You could pass your function as a variable.
You want to add listeners for events after the DOM has loaded, JQuery helps with $(document).ready(fn); (ref).
To fix your code:
$(document).ready(function() {
$("input[type='checkbox']").on('click', calculateTotalsEvent)
$(".product_table").on('change', '.edit_quantity', calculateTotalsEvent)
});
function calculateTotalsEvent(evt) {
//do something
alert('fired');
}
Update:
Vince asked:
This worked for me - thank you, however one question: you say, "pass your function as a variable" ... I don't see where you are doing this. Can you explain ? tks. – Vince
Response:
In JavaScript you can assign functions to variables.
You probably do this all the time when doing:
function hello() {
//
}
You define window.hello.
You are adding to Global Namespace.
JavaScript window object
This generally leads to ambiguous JavaScript architecture/spaghetti code.
I organise with a Namespace Structure.
A small example of this would be:
app.js
var app = {
controllers: {}
};
You are defining window.app (just a json object) with a key of controllers with a value of an object.
something-ctlr.js
app.controllers.somethingCtlr.eventName = function(evt) {
//evt.preventDefault?
//check origin of evt? switch? throw if no evt? test using instanceof?
alert('hi');
}
You are defining a new key on the previously defined app.controllers.somethingCtlrcalled eventName.
You can invoke the function with ();.
app.controllers.somethingCtlr.eventName();
This will go to the key in the object, and then invoke it.
You can pass the function as a variable like so.
anotherFunction(app.controllers.somethingCtlr.eventName);
You can then invoke it in the function like so
function anotherFunction(someFn) { someFn();}
The javascript files would be structured like so:
+-html
+-stylesheets
+-javascript-+
+-app-+
+-app.js
+-controllers-+
+-something-ctlr.js
Invoke via chrome developer tools with:
app.controllers.somethingCtlr.eventName();
You can pass it as a variable like so:
$(document).ready(function() {
$('button').click(app.controllers.somethingCtlr.eventName);
});
JQuery (ref).
I hope this helps,
Rhys
It looks like you were on the right track but had some incorrect syntax. No need for { } when calling a function. This code should behave properly once you add code inside of the calculateTotals function.
$(".product_table").on('change', '.edit_quantity', function () {
calculateTotals();
});
$("input[type='checkbox']").on('click',function() {
calculateTotals();
});
function calculateTotals() {
//your code...
}
You could just condense it all into a single function. The onchange event works for both the check box and the text input (no need for a click handler). And jQuery allows you to add multiple selectors.
$('input[type=checkbox], .product_table .edit_quantity').on('change', function() {
console.log('do some calculation...');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="product_table">
<input type="checkbox">
<input class="edit_quantity">
</div>

javascript custom listener - when element is loaded

I have anonymous function where I wrapped all javascript code inside (main.js). I pass global variable to one of function inside. But the problem is that variable is created after main.js is loaded. I could use jQuery document ready, but I don't want to wait entire document to be loaded.
main.js
(function(){
function example(){
alert(globalVariable)
}
})();
and phtml file that is loaded after
<script>var globalVariable = 'example'</script>
Is there any way to create custom listener and when this is created example() should be forced? Something like that (just as example to show what I need):
main.js
(function(){
listen(mycustomlistener){
function example(){
alert(globalVariable)
}
}
})();
phtml file
<script>
var globalVariable = 'example'
create listener(mycustomlistener)
</script>
Where is the trigger that you expect from? Is it triggered by you or from an event or from a change?
If it is listener/observer design u are looking for. You could implement your own or use the one available in backbone.wreqr
http://zen-and-art-of-programming.blogspot.in/2013/12/backbonewreqr-jumpstart.html
Also from the above code even though you create a listener your example function wont be called since it is just a functon declaration inside and not the call i.e make it
var eventAggregator = new Backbone.Wreqr.EventAggregator();
//Subscribe for the event!
eventAggregator.on('eventName', function() {
(function example(){
alert(globalVariable)
})(); //observe the call i ve made here which is absent in urs!!!
});
//Raise the event!
eventAggregator.trigger('eventName');
You could also use jquery observer and observable
https://gist.github.com/addyosmani/1321768
This should help you out in what you want.
http://jsbin.com/mugage/1/edit?html,js,output

Scope issue inside a custom object

I think I am having a scope visibility issue I can't figure out exactly: when I log the variable displayatonce I get back the right result, but as I try to use the buttons I get nothing in return. I have also tried to log this.navbuttons but all I get is an empty set... I really don't get what's wrong with this code.
<!-- html code -->
<div id="nav">
Previous
Next
</div>
/* Js Script with jQuery */
(function() {
var NewsNavigator = {
init: function(config) {
this.navbuttons = config.navbuttons;
this.displayatonce = config.displayatonce;
this.counter = 0;
this.showNews();
this.enableNav();
},
showNews: function() {
console.log(this.displayatonce);
},
enableNav: function() {
console.log(this.navbuttons);
this.navbuttons.on('click', function() {
console.log("clicked");
});
}
};
NewsNavigator.init({
displayatonce: 3,
navbuttons: $('div#nav').find('a')
});
})();
That is happening because as you are using (function())(); which executes the function immediately, maybe it's running the code before the dom is ready
everything is working fine in the below demo
DEMO
Put all your code inside document ready or at least call the initialize method inside doc ready block like
$(function(){
NewsNavigator.init({
displayatonce: 3,
navbuttons: $('div#nav').find('a')
});
});
Read more about Javascript self executing Anonymous function here
Javascript self executing function "is not a function"
or
http://markdalgleish.com/2011/03/self-executing-anonymous-functions/
You're using jQuery too soon, specifically before the DOM is ready to be searched.
Here is fiddle demonstrating this: http://jsfiddle.net/w7KaY/ (JavaScript is placed in <head>, so init() is invoked pretty early) while here (http://jsfiddle.net/w7KaY/1/), the call to init() is encapsulated in an event handler for jQuery's DOM-ready event.
Make sure the html elements are there in the DOM. I don't see any issue with the script other than the fact you have to use the bind method for binding to events.
this.navbuttons.bind('click', function() {
console.log("clicked");
});

Javascript namespace init when called from jquery.ready()

Is the following method wrong way of declaring namespace in Javascript? It is from the book I'm reading and doesn't seem to work in my code.
<script type="text/javascript">
var mynamespace = {};
if(Drupal.jsEnabled){
$(document).ready(mynamespace.init);
}
mynamespace.init = function() {
$("#mybutton").bind("click",function(){
alert('hello');
});
}
</script>
It looks like your code is dependent on jQuery. Make sure that is loaded before you run this script. Also, define your function before it gets called. Try this:
var mynamespace = {};
mynamespace.init = function() {
$("#mybutton").bind("click",function(){
alert('hello');
});
}
if(Drupal.jsEnabled){
$(document).ready(mynamespace.init);
}
What seems to be going wrong here is that the mynamespace.init function isn't defined at the time you are hooking it up to $(document).ready.
This should work as expected:
<script type="text/javascript">
var mynamespace = {};
mynamespace.init = function() {
$("#mybutton").bind("click",function(){
alert('hello');
});
}
if(Drupal.jsEnabled){
$(document).ready(mynamespace.init);
}
</script>
You may also consider forming it like this, as it is easier to understand (at least to me anyhow)
<script type="text/javascript">
var mynamespace = {
init : function() {
$("#mybutton").bind("click",function(){
alert('hello');
})
};
if(Drupal.jsEnabled){
$(document).ready(mynamespace.init);
}
</script>
Be careful using $(document).ready(mynamespace.init);. When executed in this way, this is no longer a reference to mynamespace, normally it would be equal to window, but jQuery do some call magic in the background to set it equal to document. It won't hurt you in this instance, but be wary of it in the future.
$(document).ready(function () {
mynamespace.init();
});
Is how I would do it.
In this case, the reason your code isn't working is that the init method of mynamespace isn't defined at the document $(document).ready(mynamespace.init) is called.
What strikes me as odd, at least working mostly in C#, is that a namespace should not directly contain code logic. In C# it can't, that is what classes are for. So for me, having an init function on a namespace is a contradiction.
Yes, you can use object as a namespace. Another way to form a namespace is to use closures:
(function(inner_variable_1, inner_variable_2) {
// define whatever here, they won't pollute namespace outside this closure
})(outer_variable_1, outer_variable_2);
Popular example is jQuery's noconflict-mode, which enables you to use $ variable in your jQuery code without making $ a global variable, thus leaving the global $ for another use.

Categories