When making a jQuery plugin, is it possible to accept a text string instead of an element?
For example, instead of
$("#someelement").myPlugin();:
$('Some text string').myPlugin();
Also, is it possible to allow multiple parameters?
For example, $('Text here', 'Another text').myPlugin();
I have been researching, and $() seems to be used only for selecting DOM elements. However, it's not possible to not use it. When I tried my test function using just $.myPlugin(); it didn't work.
Therefore, for this kind of thing should I just use a function? Are jQuery plugins only used when targeting a DOM element (ie. the $("p").greenify(); example). Or is it acceptable to use them like a regular function with params?
jQuery "plugins" are just prototypes on the jQuery object. So when calling the constructor like $('text') it actually "does" something with the argument text (jQuery will treat this as a selector).
If you just want to create a "plugin" for manipulating text, here a simple one for you:
myPlugin('Text here', 'Another text');
Or you can extend the String prototype if you fancy:
String.prototype.myPlugin = function(suffix) {
return this+suffix
};
'mytext'.myPlugin('.com') // -> mytext.com
you can design your plugin to accept a string as parameter...
and then use it on a jquery selection
$('#myid').myPlugin('some text');
or even just as a regular function
myPlugin('some text');
I don't understand your question - what do you want to do exactly?
If you want to call just the plugin without selecting a DOM node, most jquery extensions register themselves to $.fn:
$.fn.my_pluginname
some possibilities to call it on an element:
$('#my-css-id').myPlugin();
$('<div class="justCreatedNow">content</div>').appendTo('body').myPlugin();
Related
Say I have a map on an array of elements. The callback function takes the index and the value at that position in the array.
If I wrap the array element that the callback receives in $(), it behaves as I expect. If I use it without wrapping it in $(), it gives an error.
var nonHiddenElements = $( "form :input" ).not(':hidden');
nonHiddenElements.map(function(index, element){
input_id = $(element).attr('id'); // this works
input_id = element.attr('id') ; // this gives an error
})
Can someone explain how this works.
Is this a jQuery quirk, or a JavScript thing?
What type of objects does my nonHiddenElements array contain exactly?
What is element that gets passed to the callback?
And mainly what is the $() doing?
You need to understand how jQuery actually works. I will try to explain it briefly.
$ is nothing but a normal javascript function. jQuery === $, is just a function with a fancy name. This function does a lot of different things, depending on what you pass in it. For example if you pass a string it will be treated as CSS selector and jQuery internals will try to find corresponding DOM elements. Or if you pass a string starting with < and ending with > jQuery will create a new DOM element by provided HTML string.
Now if you pass a DOM element or NodeCollection of DOM elements, it/they will be wrapped into jQuery instances so that they can have a jQuery prototype methods. There are many prototype methods jQuery offers. For example text, css, append, attr - those are all methods of jQuery prototype. They are defined basically like this (simplified):
jQuery.prototype.text = function() { ... }
Normal DOM elements don't have those convenient methods jQuery provides. And inside of methods like map or each if you check this value or element parameter like you do, you will see that they are actually not jQuery instances:
element instanceof jQuery // => false
and of course you can't use instance methods with not an instance.
So in order to use jQuery prototype methods you need have a jQuery instance, which you can obtain if you call jQuery function with DOM element passed in it:
$(element) instanceof jQuery // true
Javascript is a programming language.
jQuery is a JavaScript Library.
With jQuery:
$("some element")
In native JavaScript you would have to do something like this.
getElementById('elementByID')
Explained in detail here: https://developer.mozilla.org/en-US/docs/Web/API/document.getElementById
MDN is a great resource for beginners. https://developer.mozilla.org/en-US/docs/Web/JavaScript
So I have a set of jQuery plugins, really basic stuff, but I split the code into plugins because I don't like having a huge jQuery(document).ready() function where I store the entire application logic.
Each plugin has a "destructor", which is basically a function that I defined in the plugin prototype object. This function unbinds events used by the plugin, removes DOM elements that were added by the plugin etc.
Plugins are initialized like this:
$('.element').plugin();
Is there any way I can get all the elements that have my plugins attached to them, from another plugin which is supposed to replace the body HTML, so I can call the destructor function?
I was thinking to store each plugin instance inside a global array, then I can access that array from any plugin. But maybe there is a better way that doesn't use the global state?
I don't think there is a ready made method for it... but as a hack you can add a class to the target elements in your plugin and then use that class to get all elements with the widget initialized lke
$.fn.plugin = function(){
this.addClass('my-plugin-class');
}
then to initialize
$(element).plugin()
to get all elements with the plugin
$('.my-plugin-class')....
But if it is a jQuery UI widget then you can use the selector $(':ui-widgetname'), see this answer
Arun P Johny wrote the rigth idea -- just delete 'footprint' of your job by marking the affected DOM elements with some specific class name.
I want just add an idea. Plugins are the methods of the library and nothing more. If you need the destroyer for constructor -- just make another plugin for it:
$.fn.overture = function (){...};// construct
$.fn.crescendo = function (){...};// more construct
$.fn.quietFarewell = function (){...};// destructor for everything above
$(...).overture().crescendo().quietFarewell();
function eegetdropdownvalue_str(ctl){return ctl.selectedIndex>=0&&ctl[ctl.selectedIndex]?ctl[ctl.selectedIndex].value:''}
The above function is called with
co.p1A10=eegetdropdownvalue_str(document.formc.p1A10);
I want to switch the call over to jQuery to drop the document.form reference however doing this
co.p1A10=eegetdropdownvalue_str($('p1A10'));
Does not reference the control correctly - How should I do this?
There's two things wrong with your code.
First, $('p1A10') references nothing.
jQuery selectors work almost identically (if not completely identically) to the way css works.
So, just ask yourself how you would reference the object(s) in question in CSS and you're half way there.
I'm assuming that p1A10 is the name or id of an object. Since we're using CSS/jQuery syntax, this should be an id, although you can select by other attributes such as $("select[name='p1A10']") .
To reference an object by ID we use the # character (again, just like in CSS). So we can select your node via $('#p1A10').
The second problem is that your function is expecting a DOM object not a jQuery object. To keep your code intact, we need to say $('#p1A10')[0] where 0 is the first element within the collection of jQuery elements.
I've provided two examples to explain this a little better. One uses your existing infrastructure and one replaces it.
http://jsfiddle.net/TD6Uu/5/
Hope it helps.
Given a form with id formc and a select with name p1A10 you could e.g. use:
o.p1A10 = eegetdropdownvalue_str($('#formc select[name="p1A10"]').get(0));
If this doesn't do it, please provide use with the exact HTML structure
I'm struggling to find out when to use #,$ in jquery.
i.e. if I have an object
var elem{
}
How to access this?
Whether $('#elem') or $('elem')?
May be its too silly. But I cant find out a solution by googling it.
It looks to me like how to you've used .appendTo(). You need to pass an ID in your case, I believe; something like:
$("<table>").attr("id","waiterBlock").appendTo("testDiv");
Changed to:
$("<table>").attr("id","waiterBlock").appendTo("#testDiv");
The documentation for jQuery's .appendTo() says one needs to pass:
A selector, element, HTML string, or jQuery object; the matched set of elements will be inserted at the end of the element(s) specified by this parameter.
In my javascript, I have a function which will return an element present in the HTML page .i have this stored in a variable and now want to do some kind of traversal in that using jquery methods like parent/fadeIn/fadeOut etc.
How can i do that.? My current code which returns the object is
var currentObject= GetThatObject();
Now i really want to play with this object like what we do with a typical jQuery object which we get like
var curObj=$("#tatElement")
You just do this:
var curObj = $(currentObject);
jQuery can take not only selector strings but HTML elements as arguments as well. It will just take that element, wrap it in its jQuery object and you can then use it the same way as if you had used a selector string. (It is actually a little more efficient because jQuery doesn't have to parse the selector and find the element).