Reputation: 113
Hello I am facing this strange JQuery problem. My Js:
$("#flip-counter").centerH();
function centerH() {
var marginL = ( $(window).width() - $(this).width() ) / 2;
$(this).css("marginLeft",marginL+"px");
alert(marginL);
}
Getting this error:
Uncaught TypeError: Object [object Object] has no method 'centerH'
(anonymous function)
k jquery.js:2
l.fireWith jquery.js:2
p.extend.ready jquery.js:2
D jquery.js:2
jquery.js:2 is empty.
I would understand if none of the code would work but now everything works except that and I can't add any other function. I just keep getting the same error. All files are included properly and when I delete this piece of JS code, my code works like a charm.
Any suggestions?
Upvotes: 3
Views: 3105
Reputation: 2247
You need to extend the jquery,if you want to use the function with jquery objects.
$.fn.centerH = function() {
var marginL = ( $(window).width() - $(this).width() ) / 2;
$(this).css("marginLeft",marginL+"px");
alert(marginL);
}
Upvotes: 6
Reputation: 2321
The centerH() function is in the global scope. But you're calling it from the $("#flip-counter") jQuery object.
If you want to make your own custom functions available to jQuery objects you would create it like this:
jQuery.fn.yourFunction = function() {
// do stuff
}
Upvotes: 1
Reputation: 310
You cannot add functions to JQuery like that. You will need to add it as a plugin using jQuery.fn.centerH
More info on:
http://docs.jquery.com/Plugins/Authoring
Upvotes: 0
Reputation: 1074038
This code:
$("#flip-counter").centerH()
...tries to get a property called centerH
from the jQuery object returned by $("#flip-counter")
and then call it as a function. So there has to be a centerH
function on the object.
This code:
function centerH() {
var marginL = ( $(window).width() - $(this).width() ) / 2;
$(this).css("marginLeft",marginL+"px");
alert(marginL);
}
...creates a centerH
function but does nothing whatsoever to add it to jQuery.
If you're trying to make a jQuery plug-in, you assign the function to $.fn
:
$.fn.centerH = centerH;
Once you've done that, the $("#flip-counter").centerH()
line will work. But note that in a jQuery plug-in function, this
is not a DOM element (your $(this).css(...)
code seems to be treating it as one). Within a jQuery plug-in function, this
is the jQuery object on which the function was called (so this.css(...)
instead).
Upvotes: 3