How to define a jQuery function properly - javascript

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

Related

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>

Passing a function with parameter to event handler

Let's say I have the following code:
$('#from').focus(listExpand(1));
$('#to').focus(listExpand(3));
It's not working as I expected. I think that it works wrong due to the fact that I'm passing a function result but not the function itself.
So the right syntax would be:
$('#from').focus(listExpand); // no brackets and no parameters
But in this case I can not pass any parameters to a function :(
How can I implement the subject?
Wrap the call to listExpand in a separate function definition:
$('#from').focus(function(){ listExpand(1); });
$('#to').focus(function(){ listExpand(3); })
below will work. use this.
$('#from').focus(function() {listExpand(1) });
$('#to').focus(function(){listExpand(3);})
I found other cool way also that #sudher mentioned. You can check it working in http://jsfiddle.net/kvHDA/
Sample Code
$('#from').focus({x: 1},myfunc);
function myfunc( e){
alert(e.data.x);
}
If a data argument is provided to .on() and is not null or undefined,
it is passed to the handler in the event.data property each time
an event is triggered.
$('#from').on("focus" , {id:1} , listExpand);
$('#to').on("focus" , {id:3} , listExpand);
function listExpand(event){
console.log(event.data.id);
}

JS: call methods of an object inside jquery "click"

I have a fundamental misunderstanding of one of my numerous errors. I use jquery.
I have an object defined as:
var terms = {};
terms.clear_history = function(a, b)
{ /* DO SOMETHING */ }
I can call the terms.clear_history(1,2) function in my main js file, no problem. But when I try to call it from the "click" of a <a/> element:
$(document).on('click', '#clearterms', function(){
terms.clear_history(1, 2);
});
it gives me the following error:
Uncaught TypeError: Object # has no method 'clear_history'
I understand that I don't understand something fundamental here...
Thank you!
It sounds like a scope issue. Maybe the terms in the global scope the same as the one assigned clear_history given the method.
also, you don't want to name your param as this which is a reserved keyword in JS.
try this:
window.terms = {};
window.terms.clear_history = function(foo,bar){console.log(foo,bar);};
//then later:
$(document).on('click', '#clearterms', function(){
window.terms.clear_history(1, 2);
});

TypeError: $(...) is null - how to use noconflict()

i get error TypeError: $(...) is null.
<script>
$('w_pages').observe('change', function(){
parent.preview.location = 'W/preview/<?=$page['parent_id'] ?>/?p='+$('w_pages').value;
});
$('w_layout').observe('click', function(){
parent.preview.Tiny.showURL('S/layout/'+$('w_pages').value+'?ajax=true',true)
});
</script>
i read that it is because of a conflict. how do i wrap this in noConflict()
There is no conflict here.
You are using the dollar function of Prototype, which returns a reference to the element with id equal to its argument. If no such element exists in the page it returns null, which in turn causes the TypeError.
I don't know why no such element exists in your page or how to make the JS work like it should, but you can avoid the immediate error by checking the return value before calling methods on it:
var wPages = $('w_pages');
if (wPages) {
wPages.observe('change', function(){
parent.preview.location =
'W/preview/<?=$page['parent_id'] ?>/?p='+wPages.value;
});
}
// The same for w_layout
i fixed it. i was indeed missing the element. thanx for putting me in the right direction.

Using javascript functions in a Jquery script

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");

Categories