According to this post Click here to see the referred post
I tried to get access to a function which is defined in another .js file following the post instruction. However, I still have a problem. See my code below:
sildemenu.js
$(document).ready(function() {
var window.slideMenu=function(){
//do something here
}();
});
control.js
$(document).ready(function() {
$('#foo').on('click', function() {
window.slideMenu();
});
});
I got the error "Object [object Window] has no method 'sildeMenu' ".
I am very new in programming. Please give me a mercy.
You try to define a complex variable, (which is impossible this way) instead of assign a value to the global object- window.
var window.slideMenu=function(){
//^^^ Get rid of this
//do something here
}();
//^^ and remove this
And get rid of the var
Fixed code:
window.slideMenu=function(){
//do something here
};
There is no need of window object just write:
sildemenu.js
$(document).ready(function() {
slideMenu=function(){
//Do your stuff here!
};
});
control.js
$(document).ready(function() {
$('#foo').on('click', function() {
slideMenu();
});
});
Related
I want to write an jquery function because otherwise I have to write some code over and over.
Here is wat the function was first:
$(".checkbox-car").click(function(){
$(this).toggleClass('checked-car')
});
$(".checkbox-bus").click(function(){
$(this).toggleClass('checked-bus')
});
And this is what I tried to do with my own function:
$.fn.checkedFunction = function(Clicked, Checked){
$(this).click(function(){
console.log('check');
$(Clicked).toggleClass(Checked);
});
}
$('.checkbox-car').checkedFunction('.checkbox-car','.checked-car');
But I get the error that the checkedFunction is not defined.
What am I doing wrong here can someone help me out?
You're getting an error that checkedFunction isn't defined because it isn't. checkedFunction is a property defined in$.fn object.
To use the function you created, you should do
$(".some-element").checkedFunction(...args).
More over, you should read the jQuery docs.
Just had to do this:
$.fn.checkedFunction = function(Clicked, Checked){
$(this).click(function(){
$(Clicked).toggleClass(Checked);
});
}
$('.checkbox-car').checkedFunction('.checkbox-car','checked-car');
$('.checkbox-bus').checkedFunction('.checkbox-bus','checked-bus');
remove the dot before the second checked- class
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 if this sounds weird but i have tried to create a function that checks a variable before executing the remaining jQuery code, it looks something like this:
$(document).ready(function(){
var myVar = true;
var myFunction = function(){
if (myVar) {
// do something
};
};
$("div").click(function(){
myFunction();
$("div).fadeOut("fast");
});
});
I guess this is not how you implement a function in jQuery so i am a bit lost.
You are missing a double quote in your click handler:
$("div").fadeOut("fast");
$("div).fadeOut("fast");
Syntax error
replace it
$("div").fadeOut("fast");
in my javascript application I am getting the following error upon page load.
Uncaught TypeError : Object #<Object> has no method 'showHideCleanupButton'
this appears (inside Chrome's debugger) to be blowing up inside the method 'getAllItemsForDisplay'where it calls 'this.showHideCleanupButton'
here is a link to it on jsFiddle:
http://jsfiddle.net/cpeele00/4fVys/
Any help would be greatly appreciated :-)
Thanks,
Chris
It appears that this is the relevant piece of code:
getAllItemsForDisplay: function() {
$.getJSON('services/act_getAllItems/', function(data) {
$('#items-list').empty();
$('#items-listTmpl').tmpl(data).appendTo('#items-list');
this.showHideCleanupButton();
BeefyUtils.noSelect();
});
},
What are you expecting this to be set to inside the getJSON callback? Have you set a breakpoint on the relevant statement and looked at what the value of this is?
If I understand the jQuery doc correct, by default this inside a getJSON call will be a reference to the ajax options that were originally passed in. I think it's possible to change what this will be with ajaxSetup, but I don't see that you've done that.
If you want to refer to the this at the beginning of getAllItemsForDisplay, then you need to save that into another variable that you can use like this:
getAllItemsForDisplay: function() {
var obj = this;
$.getJSON('services/act_getAllItems/', function(data) {
$('#items-list').empty();
$('#items-listTmpl').tmpl(data).appendTo('#items-list');
obj.showHideCleanupButton();
BeefyUtils.noSelect();
});
},
To piggy-back on jfriend00's answer, change this:
getAllItemsForDisplay: function() {
$.getJSON('services/act_getAllItems/', function(data) {
$('#items-list').empty();
$('#items-listTmpl').tmpl(data).appendTo('#items-list');
this.showHideCleanupButton();
BeefyUtils.noSelect();
});
},
to this:
getAllItemsForDisplay: function() {
var self = this;
$.getJSON('services/act_getAllItems/', function(data) {
$('#items-list').empty();
$('#items-listTmpl').tmpl(data).appendTo('#items-list');
self.showHideCleanupButton();
BeefyUtils.noSelect();
});
},
This will give you the context that called getAllItemsForDisplay, which I assume is what you want.
I have some inherited JS code that uses this format:
function main(param) {
var myVar;
function doSomething() {
...
}
....
doSomething();
....
}
It works, but now I have to control some click events. Something like this:
function main(param) {
var myVar;
function manageEvent(item) {
...
myVar = item.value;
...
}
....
item.onclick = function() { manageEvent(this) }
....
}
The problem is that manageEvent() has no access to myVar and I don't know how to solve the problem without rewriting all the code (really hard work). How can I manage the event in order to give "manageEvent" access to myVar?
It works: http://jsfiddle.net/kgmYM/
Your problem is somewhere else, it certainly is not in this code; it's perfectly fine. Try and see if what you're clicking actually has the same value; try and play with its value and see the result. But anyway, your posted code works, and without any further information, we can't find what's really wrong in your situation.