jQuery retrieve parameter from function call - javascript

$(document).ready(function(){
$('#cumulative-returns').graph({
width: 400,
height: 180,
graphtype: 'bar'
});
});
I have a binded a function on click to #cumulative-returns and I want to be able to get the graphtype value like..
$('#cumulative-returns').click(function() {
alert(this.graphtype)
});
Is this possible or how else would you go about it? Maybe have some code in the graph function that stores the parameters in some global array (messy but feasable)?
*edit: here is the graph function:
(function($) {
$.fn.graph = function(options) {
return this.each(function() {
var defaults = {
name: $(this).attr('id')
};
var opts = $.extend(defaults, options);
var img = this;
$.post('../generate_graph.php', opts);
});
};
})(jQuery);

(function($) {
$.fn.graph = function(options) {
return this.each(function() {
var defaults = {
name: $(this).attr('id')
};
var opts = $.extend(defaults, options);
var img = this;
$(this).data('graphtype', opts.graphtype); // Addition!
$.post('../generate_graph.php', opts);
});
};
})(jQuery);
Then just do:
$('#cumulative-returns').click(function() {
alert($(this).data('graphtype'));
});

You do get the dom element that has been clicked stored in this. Then I don't know if it has the graphtype method linked to it, it all depends on how .graph() behaves.

Related

jQuery plugins functions overwrite

I have implemented several jQuery plugins for my current project.
Since some plugins have functions with the same name, the one called in the last one defined.
Here is the definition of my first plugin:
$(function($)
{
$.fn.initPlugin1 = function(parameters)
{
var defaultParameters = {};
$(this).data('parameters', $.extend(defaultParameters, parameters));
return $(this);
};
$.fn.function1 = function(){ console.log('Function 1.'); };
$.fn.callFunction = function(){ $(this).function1(); };
});
And here is the definition of my second plugin:
$(function($)
{
$.fn.initPlugin2 = function(parameters)
{
var defaultParameters = {};
$(this).data('parameters', $.extend(defaultParameters, parameters));
return $(this);
};
$.fn.function2 = function(){ console.log('Function 2.'); };
$.fn.callFunction = function(){ $(this).function2(); };
});
I have also this scenario :
$("#div1").initPlugin1().callFunction();
$("#div2").initPlugin2().callFunction();
For this specific scenario the consoles shows: Function 2. Function 2.
In fact, since the callFunction() is also defined in the second plugin, this is the one used.
I would like some advise on what is the best way to solve this problem.
Is it possible to create a thing similiar to a namespace ?
Thank to #syms answer, I have created the following example.
Plugin1:
$(function($) {
$.fn.initPlugin1 = function() {
console.log('Initialized Plugin1');
return $(this);
};
$.fn.initPlugin1.testFunction = function() {
$(this).append('Function 1.');
};
});
Plugin2:
$(function($) {
$.fn.initPlugin2 = function() {
console.log('Initialized Plugin2');
return $(this);
};
$.fn.initPlugin2.testFunction = function() {
$(this).append('Function 2.');
};
});
Main:
(function($)
{
$(document).ready(
function()
{
$("#div1").initPlugin1(); //Run correctly
$("#div2").initPlugin2(); //Run correctly
$("#div1").initPlugin1.testFunction(); //Fail
$("#div2").initPlugin2.testFunction(); //Fail
});
})(jQuery);
When I run my code, I got the following error: Cannot read property 'createDocumentFragment' of null.
Apparently, the this object is corrupted.
you can try this,
$(function($) {
$.fn.initPlugin1 = function() {
console.log('Initialized Plugin1');
return $(this);
};
});
$(function($) {
$.fn.initPlugin2 = function() {
console.log('Initialized Plugin2');
return $(this);
};
$.fn.callFunction = function(param) {
$(this).append(param);
};
});
(function($) {
$(document).ready(
function() {
$("#div1").initPlugin1(); //Run correctly
$("#div2").initPlugin2(); //Run correctly
$("#div1").initPlugin1().callFunction('function1');
$("#div2").initPlugin2().callFunction('function2');
});
})(jQuery);

get variable from a jQuery Plugin

I need to know how is possible to get a plugin variable outside the plugin, to test it with some test framework.
So this is my simplified plugin:
(function ($) {
$.fn.extend({
myPlugin: function (argumentOptions) {
var defaults = {
image: 'img/default.png',
};
this.textSend = '';
var options = $.extend(defaults, argumentOptions);
var globalHere = this;
return this.each(function () {
obj.mouseup(function(e) {
globalHere.textSend = 'test';
});
});
}
});
})(jQuery);
I need to the variable this.textSend outside the plugin.
I have tried in this way:
$(document).ready(function(){
var testfield = $('.txt');
testfield.myPlugin({
image:"../img/twitter.png"
});
testfield.focus();
testfield.trigger($.Event( "mouseup"));
console.log($.fn.myPlugin.textSend);
});
but the console.log return me undefined
How can i get that variable outside?
Thanks
You will want to make sure you are returning this like so:
(function($) {
$.fn.extend({
myPlugin: function(argumentOptions) {
var self = this;
self.textSend = 'something';
self.inc = 0;
self.mouseup(function(e) {
self.textSend = 'new thing #' + self.inc;
self.inc++;
});
return self;
}
});
})(jQuery);
var instantiated = $('button').myPlugin({});
$('input').val(instantiated.textSend);
$('button').click(function(e) {
$('input').val(instantiated.textSend);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<label>Current textSend:</label>
<input />
<br/>
<button>Change textSend</button>
Hopefully will get you on the right track.
Update
Try new code.
You can store it inside the closed scope you created around your plugin and expose it through another function. Of course it'll need some refactoring, but this is the general idea:
(function ($) {
var whateverNameYouWant; //here
$.fn.extend({
myPlugin: function (argumentOptions) {
var defaults = {
image: 'img/default.png',
};
this.textSend = '';
whateverNameYouWant = this.textSend; //here
var options = $.extend(defaults, argumentOptions);
var globalHere = this;
return this.each(function () {
obj.mouseup(function(e) {
globalHere.textSend = 'test';
whateverNameYouWant = this.textSend; //here
});
});
}
});
$.extend({
getWhateverNameYouWant: function() {
return whateverNameYouWant;
}
})
})(jQuery);
var value = $.getWhateverNameYouWant();
At line console.log($.fn.myPlugin.textSend);
use testfield.textSend . now it has become proprty of selector via myplugin.

JQuery plugin - callback breaks other features

I'm trying to build a basic color picker plugin (mainly as an exercise to learn about plugin development). I have a callback called "onSelected" that fires when you pick a color, but it breaks another feature of the plugin (the ability to toggle the visibility of the swatch list).
I am new to plugin development so I'm sure it's a simple mistake I'm making...
jsfiddle
Plugin:
(function ($) {
$.colorPicker2 = function (el, options) {
// the wrapper around the colors
var $pickerContainer = $("<div>");
// To avoid scope issues, use 'base' instead of 'this'
// to reference this class from internal events and functions.
var base = this;
// Access to jQuery and DOM versions of element
base.$el = $(el);
base.el = el;
// Add a reverse reference to the DOM object
base.$el.data("colorPicker2", base);
base.init = function () {
console.log("base.init");
base.options = $.extend({}, $.colorPicker2.defaultOptions, options);
// Put your initialization code here
// code goes here
$.each(base.options.colors, function (index, value) {
var $item = $('<div class="colorPicker-colorOption">').css({
"background-color": "#" + value
})
$item.click(function () {
console.log("item.click");
base.selectColor(value);
})
$pickerContainer.append($item);
});
//$pickerContainer.hide();
base.$el.append($pickerContainer);
if (base.options.toggleElement != null) {
base.options.toggleElement.click(function (e) {
base.togglePicker();
e.preventDefault();
});
}
};
base.togglePicker = function()
{
$pickerContainer.toggle();
}
base.selectColor = function (color) {
base.togglePicker();
if (typeof base.options.onSelected == 'function') {
base.options.onSelected.call(this, color);
}
}
// Sample Function, Uncomment to use
// base.functionName = function(paramaters){
//
// };
// Run initializer
base.init();
};
$.colorPicker2.defaultOptions = {
colors: [
'000000', '993300', '333300', '000080', '333399', '333333', '800000', 'FF6600',
'808000', '008000', '008080', '0000FF', '666699', '808080', 'FF0000', 'FF9900',
'99CC00', '339966', '33CCCC', '3366FF', '800080', '999999', 'FF00FF', 'FFCC00',
'FFFF00', '00FF00', '00FFFF', '00CCFF', '993366', 'C0C0C0', 'FF99CC', 'FFCC99',
'FFFF99', 'CCFFFF', '99CCFF', 'FFFFFF'
],
toggleElement: null,
onSelected: function (color) { }
};
$.fn.colorPicker2 = function (options) {
return this.each(function () {
(new $.colorPicker2(this, options));
});
};
})(jQuery);
How I hook into the onSelected event:
$(function () {
$('#primaryColorPicker').colorPicker2({
toggleElement: $('#selectPrimaryColor'),
onSelected: function (color) {
$('#selectedPrimaryColor').html("(#" + color + ")");
}
});
});
The HTML:
<a id="selectPrimaryColor">Toggle Color Picker</a>
<span id="selectedPrimaryColor" />
<div id="primaryColorPicker"></div>
You just have to learn how to write valid HTML
replace
<span id="selectedPrimaryColor" />
with
<span id="selectedPrimaryColor"></span>
FIDDLE

I am trying to attach a hover action, but the hover action is being called immediately

I am writing my first jQuery plugin. I am trying add a hover action, but the hover response is being called immediately. Here is my plugin:
(function($){
var Help = function(element, options) {
this.$element = element;
this.options = $.extend({}, $.fn.help.defaults, options);
};
Help.prototype.hover = function(name){
alert(name);
};
$.fn.help = function(option){
return this.each(function () {
var $this = $(this);
var help = $this.data('help');
var options = "";
var data = $this.data('help-id');
if(!help) {
$this.data('help', (help = new Help(this, options)));
}
$this.on('hover', help.hover(data));
});
};
})(jQuery);
I attach my plugin with $('#one').help(), but this immediately calls the hover function. What am I doing wrong?
You're not passing a function to on but the result of the call of your function.
Replace
$this.on('hover', help.hover(data));
with
$this.on('hover', function(){help.hover(data)});

how can I cause any change to a variable in an internal function to affect main variable value

I know java script doesn't have call by reference. So how can I solve this?
(function($){
$.fn.extend({
something: function(options) {
var Status;
var defaults = {
regex:/^([\u0600-\u06FF]|\s)*$/,
errortxt:"Invalid input",
emptytxt:"It should not be empty"
}
var options = $.extend(defaults, options);
$(this).bind('change', function () {
Status = true;
$(this).each(function() {
/*variables*/
var necessaryElement;
if (options.regex && options.errortxt && options.errorsection)
{
var filter = options.regex;
var $this = $(this);
var wrongMessage = options.errortxt;
var $errordiv = $("[ID$="+options.errorsection+"]");
} else{
console.log("Error : Not enough arguments for invoking something Plugin");
}
if (options.emptytxt)
{
var noMessage = options.emptytxt;
necessaryElement = true;
}
else
{
necessaryElement = false;
}
var elementvalue = $this.val();
/* Methods */
if (elementvalue != "" && necessaryElement) {
if (filter.test(elementvalue)){
$this.removeClass("error").addClass("ok");
$errordiv.fadeOut(300);
} else {
Status = false;
$this.removeClass("ok").addClass("error");
$errordiv.fadeIn(200);
$errordiv.text(wrongMessage);
}
} else if (elementvalue == "" && necessaryElement) {
Status = false;
$this.removeClass("ok").addClass("error");
$errordiv.fadeIn(200);
$errordiv.text(noMessage);
}
});
});
return Status;
}
});
})(jQuery);
and I call it in another js in this way:
var myarray=new Array();
myarray[0] = $('#selector').something({
regex:/^([\u0600-\u06FF]|\s)*$/,
// another options
});
$('#selector').change(function (){
alert (myarray[0]);
});
but it alerts undefined.
If I change var Status to var Status= true Then it always alerts true.
Can anyone help me? How I can change the code to return the desired Status?
Edit : Trying to be clearer.
Something() returns a value which is modified by change.
So when you call something you return the value unmodified.
Then you call change that will change the value, but it's not passed by reference in the array so it won't change anything.
You may want to use the data function available on JQuery objects for keeping data.
Here is a simplified version:
(function($){
$.fn.extend({
something: function(options) {
$(this).bind('change', function () {
$(this).data('status','true');
});
}
});
})(jQuery);
$(document).ready(function() {
var myarray=new Array();
myarray[0] = $('#selector').something({
regex:/^([\u0600-\u06FF]|\s)*$/
});
$('#selector').change(function (){
alert ($(this).data('status'));
});
});

Categories