Getting value from this JQuery plugin - javascript

I've been experimenting with writing JQuery plugins lately, and I'm sure this is a very simple question. But, I seem to not be able to get a value inside of my plugin.
For example, I have the following code:
plugin.js
$(function($) {
$.fn.myPlugin = function() {
// alert the id from main.js
}
});
main.js
$(document).ready(function() {
$('#someDIV').attr('id').myPlugin();
});

You cannot define plugin on string. Use selector to call the plugin.
Have a look at this.
Use it like this:
(function ($) {
$.fn.myPlugin = function () {
this.each(function () {
// Allow multiple element selectors
alert(this.attr('id'));
});
return this; // Allow Chaining
}
} (jQuery));
$('.myClass').myPlugin();
DEMO
Tutorial

Try this:
(function($) {
$.fn.myPlugin = function() {
alert($(this).attr('id'));
}
}(jQuery));
See here: http://jsfiddle.net/1cgub37y/1/

You should pass only the object into your jQuery-extension function (not the object's ID), as below or in this fiddle (will alert "someDIV" onload):
// jQuery extension
// The object passed into jQuery extension will occupy keyword "this"
$(function($) {
$.fn.myPlugin = function() {
// Get the ID (or some other attr) of the object.
var id = $(this).attr("id");
// Now do something with it :)
alert(id);
}
});
$(document).ready(function() {
$('#someDIV').myPlugin();
});

Related

jQuery - Plugins and namespace issues with method chaining

I'm trying to create a simple plugin that I can call by both: $.myPlugin() and $('something').myPlugin()
Heres the code:
(function($) {
$.fn.myPlugin = function(item) {
return this;
};
$.myPlugin = function(item) {
return $.fn.myPlugin(item);
};
}(jQuery));
This works when called either way mentioned above.
However, calling $.myPlugin().hide() does not work. Any chained methods are failing.
Heres a simple JSBin I made showing the issue
Why?
You should return $(this), not jquery this:
(function($) {
$.fn.myMethod = function() {
this.append('<p>MY METHOD</p>');
return $(this);
};
$.myMethod = function() {
return $.fn.myMethod();
};
}(jQuery));
$(function () {
// Moment of truth
$('.output').myMethod().hide('slow');
$('h1').click(function(){
$('.output').myMethod().hide();
});
});

A good method for passing 2 selectors into my jquery plugin for use with .on()

Many jQuery plugins do something like this:
$('#selector').myPlugin({option:"value"});
However, inside myPlugin I want to use jQuery .on(), so I need another selector:
// my-plugin.js
(function($){
$.fn.myPlugin = function(options) {
// Help!! I need a container here!
$(?????).on("click", this.selector, function(){
alert('success!');
});
};
})(jQuery);
How do I pass another selector for use in the .on statement inside my plugin? (I realize that a selector is only text and I could pass it with my options I'm passing, but is that the standard approach?)
EDIT:
Found this later and it also provides good clarification on dealing with this issue: jQuery plugin to apply also on dynamically created elements
You obviously have no need for the selected element, therefore i suggest instead creating your plugin on $ directly rather than $.fn so that you don't waste time selecting elements that you'll never use. Pass in the context and selector through the options object parameter as an object.
$.myPlugin = function (options) {
$(options.context).on("click", options.selector, function(){
alert("Hello World!");
});
}
$.myPlugin({
context: "#container",
selector: ".targetel"
});
An alternative would be:
$.fn.myPlugin = function (selector) {
return this.on("click", selector, function(){
alert("Hello World!");
});
}
$("#container").myPlugin(".targetel");
Try this (edit)
(function($){
$.fn.myPlugin = function(options) {
settings = {
container : null
};
var options = $.extend({}, settings, options);
// Help!! I need another selector here!
return $(options.container).on("click", function(){
alert('success!');
});
};
})(jQuery);
$('html').myPlugin({container:"body"})
jsfiddle http://jsfiddle.net/guest271314/vpu33/
hi see this fiddle:
http://jsfiddle.net/jFIT/4cNRC/
$.fn.myPlugin = function(options) {
$("#container").on("click", '#'+$(this).attr('id'), function(){
alert('success!');
});
//OR if container is dynamic..
$(this).parent().on("click", '#'+$(this).attr('id'), function(){
alert('Dynamic success!');
});
};
$('#someDiv').myPlugin({option:"value"});

How can I retrieve the target element that a jquery plugin is attached to?

I am new to writing JQuery Plugins...and have a question regarding returning the selector used to bind the plugin to.
Lets say we attach a jQuery plugin to an element like this...
$(".someClass").viEdit();
And this is the Plugin ...
(function ($) {
$.fn.viEdit = function () {
var myTarget = "????"; // See Below
};
}(jQuery));
Now...How can I retrieve the target that was used to bind the jQuery?
I don't mean $(this), I'm looking for .someClass in this case.
As a second example, if it was set like this...
$("#myElement").viEdit();
I would be looking for...
#myElement
Any help would be greatly appreciated!
You can use this.selector:
http://jsfiddle.net/3NAwD/
(function ($) {
$.fn.viEdit = function () {
console.log(this.selector);
};
}(jQuery));
Note that something like $(document.getElementById('someId')).viEdit(); will give you a blank selector.
There were a .selector property, which is deprecated in newer versions.
The advised method now is to pass it as a option like
(function ($) {
$.fn.viEdit = function (options) {
var myTarget = options.target;
};
}(jQuery));
$("#myElement").viEdit({
target: '#myElement'
});

jQuery and object literal function not working together

i was trying to organize my jquery code so i created an object literal, but now the focusTextArea is not working and my textarea value is not updating.
Thanks for your help.
html
<textarea id="test"></textarea>​
javascript
(function($,window,document,undefined){
var TEX = {
inputField: $("textarea#test"),
/* Init all functions */
init: function()
{
this.focusTextArea();
},
/* Function update textarea */
focusTextArea: function()
{
this.inputField.text('test');
},
}
$(document).ready(function(){
TEX.init();
});
})(jQuery,window,document);​
jsfiddle
http://jsfiddle.net/vBvZ8/1/
First of all, you haven't included jQuery correctly in the fiddle. Also, I think you mean to place the code in the head of the document (because of the document.ready handler).
More importantly perhaps the selector $("textarea#test") is run before the document is ready and therefore won't actually find the element correctly. I would recommend assigning inputField in TEX.init:
(function($,window,document,undefined){
var TEX = {
/* Init all functions */
init: function()
{
this.inputField = $("#test");
this.focusTextArea();
},
/* Function update textarea */
focusTextArea: function()
{
this.inputField.text('test');
},
}
$(document).ready(function(){
TEX.init();
});
})(jQuery,window,document);​
Updated example: http://jsfiddle.net/xntA2/1/
As a side note, textarea#test should be changed to just #test. The textarea bit is superfluous since there should be only one element on the page with id=test.
Alternative syntax to avoid looking for an element before it exists is to return the element from a function:
(function($,window,document,undefined){
var TEX = {
/* function won't look for element until called*/
inputField:function(){
return $("textarea#test")
},
init: function()
{
this.focusTextArea();
},
focusTextArea: function()
{
this.inputField().text('test');
},
}
$(document).ready(function(){
TEX.init();
});
})(jQuery,window,document);
DEMO: http://jsfiddle.net/vBvZ8/5/
I realize this is a simplified example...but you are also very close to creating a jQuery plugin and that may also be of benefit. Following provides same functionality as example:
(function($, window, document, undefined) {
$.fn.focusTextArea = function() {
return this.each(function(){
$(this).text('test');
})
};
})(jQuery, window, document);
$(function() {
$('textarea').focusTextArea()
});
DEMO: http://jsfiddle.net/vBvZ8/8/

jquery plugin Uncaught TypeError: object is not a function

I just created my first jQuery plugin , it is very simple it slideToggle two Divs , the code works fine and it do what i want , the problem is that i get an ERROR message at the console saying :
Uncaught TypeError: object is not a function
it refer to this line of code
})(jQuery);
CODE
$(function($) {
$.fn.toggleDiv = function(opt) {
var options = $.extend({}, $.fn.toggleDiv.objectOptions, opt);
return this.each(function() {
if (options.animation == true) {
$(this).slideToggle();
} else {
$(this).toggle();
}
});
};
$.fn.toggleDiv.objectOptions = {
animation: false
};
$("button").click(function() { $("#Div1, #Div2")
.toggleDiv({animation : fa}); return false; });
})(jQuery);
Does any one know what is that error and how can i fix it thanks
You either want to do
(function ($) { ... })(jQuery);
if you want your code to be run immediatly,
or
jQuery(function ($) { .... });
for your code to be run on document-ready.
You are referring to $("button"), and therefore need the document tree to be available. So use the second version. A even nicer solution would be to use the jQuery function "delegate", this would look something like this:
jQuery(function ($) {
$(document).delegate("button", "click", function (ev) { ... });
});

Categories

Resources