How to use an external function in event handler in JQuery - javascript

I want to do something like this:
$(div).bind('click', myFunctionWithManyManyLinesOfCode(param) );
.....
function myFunctionWithManyManyLinesOfCode(args){
//50 lines of Code
}
If I do this the function is executed when the code reaches the point and doesn't execute on clicks.
If I include the code from the function myFunctionWithManyManyLinesOfCode in the bind method it will be a mess of code.
Also, I've tried this, but I cannot reference variables, they are undefined
$(div).bind('click', function() {myFunctionWithManyManyLinesOfCode(param)} );

You can pass whatever data you want to in the following way.
This should do the trick for you. If something is unclear please write a comment.
Edit: As stated in the comments you should use on and not bind.
function myFunction(e){
console.log(e.data.id);
}
$('#example').on('click',{id: "WHATEVER"}, myFunction);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="example">Test</button>

First of all, 50 lines of code are too much for one function and should be divided into smaller methods, but you can use this method:
var hello = () => {
alert(123)
}
$("p").click(hello);

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>

Retrieving the value of an attribute of a div in jQuery via click()

Sorry for the vague title. I am using jQuery. I have a small scenario in my app and I am stuck.
Problem: I have two functions in my script named as func1 and func2. I want to execute both of these functions when ever an user clicks on the div element and also to access the value of the code attribute in these two functions.
<div id="testId" code="102">Click ME</div> .
Code:
<html>
<body>
<div id="testId" code="102">Click ME</div>
<script type='text/javascript' src='jquery.js'></script>
<script type='text/javascript' src='script.js'></script>
</body>
</html>
script.js:
var code1 = "";
var code2 = "";
func1 = function(){
code1 = $(this).attr('code');
alert("code1 is "+code1);
}
func2 = function(){
code2 = $(this).attr('code');
alert("code2 is "+code2+'2');
}
$('#testId').click(func1, func2);
/*$('#testId').click(function(){
func1();
func2();
});*/
I want to access the value of code="102"in my two functions. I tried two ways.
First I tried the following snippet:
$('#testId').click(func1, func2);
This only executes the func2. The value of the code attribute is also being accessed by func2. But the func1 is not executing! How to do this?
Then I tried a second way. I am able to execute the both functions when ever an user clicks on the div, by using the following snippet
$('#testId').click(function(){
func1();
func2();
});
but now I am unable to access the value of code attribute and it is undefined! How can I access the value of the code attribute in func1 and func2?
I know I can pass the parameters to func1 and func2 like below and later access the values,
$('#testId').click(function(){
func1('value of code');
func2('value of code');
});
But I am looking for a different solution if possible.
Finally I am looking for a way by which I can execute both of the functions and also have access to the value of the code attribute. Any suggestion will be appreciated!
First for all you are ussing the .Click() method so, if you use .click(func1, func2) it hopes that .click( [eventData ], handler ). becouse that only execute the function2 so It's a handlers.
Well you will need execute like:
$('#testId').click(function(){
func1();
func2();
});
If you need get the code, it's much better create a data attribute like:
<div id="testId" data-code="102">Click ME</div>
$('#testId').click(function(){
func1.call(this);
func2.call(this);
});
func1 = function(){ console.log($(this).data('code'));
code1 = $(this).data('code');
alert("code1 is "+code1);
}
With .call() you send who is calling the function.
Advantage:
Well the .data() attr is better becuse all data that you read you will know that it's aditional paramert, instead only code you maybe don't know where it comes from. unsing the .call keep the method clean of parameters.
Disadvantage
You need to know, What does the call do. and Maybe mixing Vanilla with jQuery. :)
LIVE DEMO
This is an issue of scope really. A proper solution can be seen at http://jsfiddle.net/dboots/dhd0dem7/.
In your code, you are referencing $(this) inside func1 and func2. These refer to the actual func1 and func2 scopes and they have no idea what "code" is.
The $(this) inside the click handler, actually refers to the div element you are clicking on so it's fitting to use it there.
In the jsfiddle, we declare code at the global level and set it in the click handler.
var code;
$('#testId').click(function() {
code = $(this).attr('code');
func1();
func2();
});
Then the func1 and func2 functions are able to access it as they see fit.
function func1() {
alert('func1 code: ' + code);
}
function func2() {
alert('func2 code: ' + code);
}
Alternate Solution
Pass the code to the individual functions as seen in http://jsfiddle.net/dboots/dhd0dem7/1/.
function func1(code) {
alert('func1 code: ' + code);
}
function func2(code) {
alert('func2 code: ' + code);
}
$('#testId').click(function() {
code = $(this).attr('code');
func1(code);
func2(code);
});
you can bind your function to the value of this
func1.bind(this)();
func2.bind(this)();
this way when your function tries to access $(this) it will point to the same object as in the click event

multiple functions onClick() not working

Below is the code that I used for multiple java scripts on a single button. But only any one is working when I disable the second one. Please let me know: how do I change my code to make it to work fine?
function invoke(but)
{
if(but==0)
{
function move(){
document.getElementById('tgt1').value =
document.getElementById('Allocation').value;
document.getElementById('Allocation').value="";
document.getElementById("Send").disabled=true;
}document.myform.action="Alloc_Insert.do";
}
else if(but==1)
{
document.myform.action="";
}
else if(but==2){ document.myform.action="WL_Verif.do";}
else if(but==3){ document.myform.action="Add_Query.do";}
document.myform.submit();
}
And the html is as below:
<input type="Submit" value="Allocate" id="Send" name="submit" onClick="invoke(0);move();"/><br/>
change the name of the button to something else than "submit"
To explain what happens:
When you assign the name-attribute "submit" to the button(or any other form-element), this element will be accessible via
document.myform.submit
but there is also the build-in method of a form: submit(), you also may access it by using
document.myform.submit
What happens now when you call document.myform.submit()
I'll write the code a little bit different, and you will see trouble:
document.myform['submit']()
Instead of accessing the built-in method, the code points first to the form-element, and then tries to execute the method. But a form-element is not a method, it all ends up in an error and the rest of the script(including the call of move() ) will not get executed.
It's the same with "reset", you never should use the name of a built-in property/method of the form-element as name for form-elements.
notice the 'move' function is not declared outside the 'invoke' function.
Then;
either wrap them in a self invoking function:
onclick="(function(){ invoke(0);move(); })();"
or attach event handlers (preferred usually)
div.attachEventListener('click', function () { ... }); // DOM 3
div.attachEvent('click', function () { ... }); // IE
Your functions are declared in a weird way. You're defining move inside of invoke, which I don't think you want. If you want to have two functions, put move outside of invoke, like this:
function move(){
document.getElementById('tgt1').value =
document.getElementById('Allocation').value;
document.getElementById('Allocation').value="";
document.getElementById("Send").disabled=true;
}
function invoke(but)
{
if(but==0)
{
move();
document.myform.action="Alloc_Insert.do";
}
else if(but==1)
{
document.myform.action="";
}
else if(but==2){ document.myform.action="WL_Verif.do";}
else if(but==3){ document.myform.action="Add_Query.do";}
document.myform.submit();
}
A note: it's generally not a good idea to use onClick in your HTML -- it's better to put that in your JavaScript.
I think the problem is the scope of the move() function. Try defining move outside of invoke.
function invoke (but) {
if(but==0) {
document.myform.action="Alloc_Insert.do";
// I don't know if you meant to call move() here or not
}
else if (but==2) { document.myform.action="WL_Verif.do"; }
else if (but==3) { document.myform.action="Add_Query.do"; }
document.myform.submit();
}
function move(){
document.getElementById('tgt1').value =
document.getElementById('Allocation').value;
document.getElementById('Allocation').value="";
document.getElementById("Send").disabled=true;
}
Also, properly formatting your code will do wonders to the legibility of it.
NOTE: Firefox seems to be quite happy to execute the onClick="invoke(0);move();" even if move is defined inside invoke. Chrome however won't execute move because it can't find it. So be sure to test your script in multiple browsers as well.

What is the best practice for grouping many jquery functions?

I have a js file containing my all jquery code all, I followed 2 practices but I don't know which one is better:
First:
jQuery(document).ready(function(){
var $ = jQuery;
//some code here
//another code not related to the first one
//also another independent code
//... and so on
});
Second:
jQuery(document).ready(function(){
//call the functions here
my_func_1();
my_func_2();
my_func_3();
my_func_4();
});
//list of functions
function my_func_1() {
//function code
}
function my_func_2() {
//function code
}
function my_func_3() {
//function code
}
function my_func_4() {
//function code
}
the second method seems better and more organized, but sometime let's say that my_func_2() didn't find what it's looking for on the page for example $('#my-id'), the functions that follow my_func_2() never run.
I also tried another method, define all my jquery functions in one js file, and then adding the function using script tags in the html where they should be:
<script>my_func_2();</script>
so what is the best way to group jquery code ?
and should we use :
jQuery(document).ready(function(){
});
for each bunch of code ?
and thanks in advance.
If your code in func_2() potentially causes an error then you really should be wrapping the contents of your functions in try / catch blocks to ensure that there are no issues with the next function running.
Also, the following is also an option for multiple start-up functions whilst keeping their error scopes separate:
$(document).ready(function(e) { ... My function code 1 .... });
$(document).ready(function(e) { ... My function code 2 .... });
$(document).ready(function(e) { ... My function code 3 .... });
$(document).ready(function(e) { ... My function code 4 .... });
var myFunc1 = function() {};
var myFunc2 = function() {};
var myFunc3 = function() {};
var myFunc4 = function() {};
Declare your functions first. And see this shortener for jQuery.ready
jQuery(function($) {
// in here $ === jQuery.
myFunc1();
myFunc2();
myFunc3();
myFunc4();
});
In general, it's good practice to keep your functions short and concise.
Also, consider that splitting your code in small units helps you reusing it somewhere else.
Furthermore, you should keep in mind the aspect of testing your code.
It is much easier to test small separate units of code than large chunks.
The point of putting function definitions inside $.ready(), is that those functions become enclosed into that context and not accessible from outside. This can be an advantage (to access enclosed variables or to prevent function misuse), but make it harder to debug.
For my experience, start declaring you functions outside (so you can easily test your code), than move these functions to $.ready().

Categories