This is a part of a more broad question. It is getting low attention, so let me please ask the only part of it that I can't implement myself. How can I register jquery-like javascript function for a dom object? Say i have a following html page:
<html><body>
<div id = "table"/>
<div id = "chart"/>
</body></html>
and want to be able to call $('#table').update() and $('#chart').update()? I need those update functions to contain different logic and local variables, for example different url to load data from. Sorry for probably being noob.
UPDATE
If I understand correctly, plugin is a function in a global namespace that can process any object. I'd rather want to associate different functions with different elements. That because I thought that it would be easier to associate different update functions with different objects, than write one update function which for every object has to investigate is it applicable, and if yes, how.
What you're after is jQuery's fn.extend():
$.fn.extend({
update: function() {
/* Required code. */
}
});
Then you can simply call .update() on a jQuery object to execute that function:
$('myElement').update();
As an example use, if we wanted to log the id of an element, we could define our update() function as:
$.fn.extend({
update: function() {
console.log("ID = " + this.id);
}
});
Then call:
$('#table').update();
Which would log:
ID = table
You don't need jQuery for this. DOM elements are objects, so you can give them any methods you want:
var table = document.getElementById('table');
table.update = function() {
this.innerHTML += 'table updated ';
}.bind(table);
var chart = document.getElementById('chart');
chart.update = function() {
this.innerHTML += 'chart updated ';
}.bind(chart);
document.getElementById('table').update();
document.querySelector('#chart').update();
Example: http://jsbin.com/uReyIRi/1/edit
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With