Hi I'm pretty new to javascript looking for some help on creating an argument and adding it to a click event in jquery
Heres a demo: http://jsfiddle.net/zidski/8VwAy/1/
Can someone help example what I have to do?
Thanks
First: Do not use arguments as a variable name, since every function already defines the arguments object.
Your code does not work, because you have injected the JavaScript through the onload setting in JSFiddle. This runs code after the document has loaded.
In the body section, you're calling a function which is not defined yet.
What happens?
Definition:
window.onload = function () {
// Defines window.demo.Alert...
}; ...
window.demo.Alert();
Calling order:
window.demo.Alert(); // Error: 'demo' is not defined.
window.onload = ...
Change onload to nowrap (head) to get your code to work: http://jsfiddle.net/8VwAy/7/
You can actually pass data to the event handler as the first parameter
$(".js-link").click("myne", function(e) {
alert(e.data);
alert("Hello world");
});
fiddle here http://jsfiddle.net/8VwAy/8/
Related
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>
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
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
I dinamically add divs with onlick event, but clicking got an error (Mozilla Firefox): "ReferenceError: myfoo is not defined". If I change onclick event to alert, it works fine, but non with mysefl written functions.
Here is jsfiddle
http://jsfiddle.net/UJ85S/5/
function myfoo(x)
{
alert(x);
}
$("#some").html('<div id="cool_div" onclick="myfoo('+"'xwe'"+');"></div>');
Can you, please, explain what is wrong?
(I understant that can assign.click event, but is it possible through onclick?).
What you really need to do is not let jsFiddle wrap it inside the onload event as this uses a function which creates new scope. Your function is then not accessible outside this new scope. Learn what's happening not learn how to get around it (i.e. not just hack your code to the window Object):
http://jsfiddle.net/UJ85S/12/
No wrap - in <body>
This is happening because you define myfoo inside of $(window).load(function () {...}) function (JSFIDDLE does this):
You need to declare a global function. You can do window.myfoo to declare your function instead.
window.myfoo = function (x)
{
alert(x);
}
JSFIDDLE
But yeah, it's not a good practice to polute the global scope, that's why it's better to use $(...).on("click", function () { alert(...) }) handlers.
I discourage using on... attributes in HTML because it's also another bad practice.
Your code becomes:
function myfoo (x)
{
alert(x);
}
var $divToAppend = $("<div id='cool_div'>")
$divToAppend.on("click", function () {
myfoo("hello");
});
$("#some").html($divToAppend);
And here a DEMO.
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");
});