JS selector combined with jquery - javascript

I wonder if there's a way to combine a JS selector with jQuery functions methods like that:
document.getElementsByClassName("example").on("click", function() {
...
});

You can pass your node list to the jQuery constructor:
$(document.getElementsByClassName("example")).on("click", function() {
// ...
});
I don't know for sure how long jQuery has recognized when node lists are passed to the constructor, but it seems to work now.

Related

Difference between creating Jquery plugins with $fn and without it

I'm looking on some Jquery plugins,and I want to build my own. In all tutorials I see syntax like this:
(function($) {
$.fn.myPlugIN = function() {
// Add plugin code here
};
})(jQuery);
But when I look at the code of few popular plugins like iScroll.js, Carousel,js
I see the dont use the $.fn syntax, they write it inside one function
(function(){
function iScroll (el, options) {
var that = this, i;
//some code
}
})();
What are the difference between those function and the use of them?
That's the difference between a jQuery plugin and a basic javascript plugin (or module).
iScroll doesn't use jQuery, it has no reason to be defined as a jQuery plugin. Like most javascript plugins not based on a specific framework, it's based on the very convenient module pattern which lets you define many private variables not cluttering the global namespace. The snippet you show doesn't contain the part where a unique variable is exported in the global namespace.
See source :
if (typeof exports !== 'undefined') exports.iScroll = iScroll;
else window.iScroll = iScroll;
iScroll (and I'm assuming Carousel as well) are not jQuery plugins, so their code-behind syntax will be a bit different.
A jQuery plugin is an extension function that works off jQuery objects. For example, if I create a foo jQuery plugin, I should be able to use that via something like $('#some-element').foo();.
To be able to work this way, jQuery plugins extend the $ prototype by adding functions to the $.fn variable like so:
$.fn.foo = function () {
// foo!
};
iScroll, on the other hand, is not a jQuery plugin. It doesn't work off a jQuery object, so you don't expect it to work like $('#some-element').iScroll();. You use it by invoking iScroll() itself.
var obj = new iScroll('container');
As you'd expect, the difference in means of use will dictate different ways of declaring the plugin in its script file.

Is there a way to trigger an event when inserting html?

It's for a backbone application,
I'm using Jquery html() function to insert my views templates into the layout everywhere, and I would like to be able to trigger an event each time the html() function of jQuery is called to check the html of the page.
Is there a way to do that ?
( Like App.on('html', blablabla...); )
Thank you !
As Marc B suggested DOM MutationEvents is available on some browsers (not many). By default jQuery does not fire any event when using html, but you can define your own behaviour for this, for example:
(function($) {
var html_ref = $.fn.html;
$.fn.extend({
html : function() {
$(document).trigger( 'html_change' );
return html_ref.apply(this, arguments);
}
});
})($);
It should work, didn't test it though. You can use the same with .text method. Now you can simply use:
$(document).bind( 'html_change', function() {
// Hurray! Html changed!
});
That's the idea, use it as you wish.
AFAIK, the jQuery html() method doesn't fire any subscribable events per se, but you could probably roll your own implementation of a simple Observer pattern. I use this across a large number of projects and it provides a great, clean, lightweight way to encapsulate arbitrary event handling across loosely-coupled modules.
However, this is presuming that you have programmatic control over every time the html() method is called - if not, then this would be more difficult, as there is no callback function to hook into.

Initializing jQuery.load'ed elements

I'm loading part of my webpage using AJAX, in particular jQuery.load(). With this the usual jQuery pattern
$('.classname').click(...) // Handler
// or, working with bootstrap
$("a[rel=tooltip]").tooltip() // Function
or similar obviously don't work any more, because they are called only when the page is loaded. I realize there is jQuery.on for the first example, but how would I implement the second?
Is there a simple (builtin) way to also apply these to jQuery.loaded stuff, or do I have to work around it myself? Seems like a problem a lot of people should be having.
You have to work around it yourself; but you can easily to this by calling $("a[rel=tooltip]").tooltip() in the callback for load():
$('#blah').load('/somewhere.html', function () {
$('#blah').find('a[rel="tooltip"]').tooltip();
});
Be sure to restrict the tooltip() call to only newly loaded elements, or you'll end up initializing tooltip multiple times per element (which may result in weird behaviour).
To avoid duplicating code you just need to define a helper function;
function initTooltip(root) {
return $(root || document).find('a[rel="tooltip"]').tooltip();
}
Which allows you to init tooltip. The parameter is optional, and lets you restrict initialization to only descendants of the provided element, e.g.:
jQuery(document).ready(function ($) {
initTooltip(); // equivilant to initTooltip(document);
$('#blah').load('/somewhere.html', function () {
initTooltip('#blah');
});
});

jQuery plugin method that doesn't take an element

I'm authoring a jQuery plugin in which one of the methods that I'd like to write will not take a selector argument and does not need to pass an element. I'd like it to be available by a call like $.myMethod() like the built in $.ajax() method. Up to now I've tried something like
$.fn.myMethod(options) {
console.log("I've been called");
}
This works when I try $('.a_selector').myMethod() but not when I try $.myMethod().
Is this doable with a jQuery plugin or is it only available for interal functions.
The purpose of this method is to perform an action on some data that is stored in jQuery.data. I recognize that they jQuery.data is associated with an element, but in this case I've hard coded it to the body element to make things easier for the end user.
The functions that are members of $.fn apply to jQuery objects, not to the $ object itself. If you want to create such a method, you only have to write:
$.yourMethod = function() {
// Do something.
};
Now you can call it without a jQuery object:
$.yourMethod();
An elaborate way of declaring such a function can be
$.extend({myMethodA:function(){
//Do something
},
myMethodB:function(){
//Do something else
}
});

jQuery plugin class type name

I have searched but have not been able to find any information. I know this isn't typical of jQuery however I need to appease our structure that we have for PHP and make that into the jQuery plugin per my boss.
Is there any way to extend the $.fn to add another name? For example
$.MyTools.useTool('piece of wood','cut');
or
$('#wood').MyTools.useTool('cut');
I guess MyTools would be the class and useTool would be the function. However I have done this in a plugin. We are wanting to have our plugin called MyTools and whenever you use a function in it you need to call MyTools.
Would it be better to do away with the plugin and just create a class?
Yeah, when I want to make a namespace (sort of) like that I do this for all my plugins:
(function( $ ){
if(!$.fn.MyTools) {
$.fn.MyTools = {};
}
$.fn.MyTools.useTool = function() {
// do stuff
};
})( jQuery );
It appears that is no way to do this, so I had to take a different approach and take the official plugin way method by doing $.GLCFormattingCurrency('remove', data);

Categories