Calling a function inside a jQuery plugin from outside - javascript

I am trying to work out how to call functions within my jQuery plugin from outside the plugin. The code I have tried is not working. I'm sure I will have to restructure my plugin to allow this, but I'm not sure how to. In this example, I'm trying to access the underline() function.
jsFiddle
jQuery plugin
(function($) {
"use strict";
$.fn.testPlugin = function(options) {
// Settings
var settings = $.extend({
newText : "Yabadabado"
}, options);
return this.each(function(i, el) {
var init = function(callback) {
if( $(el).attr("class") === "red" ) {
$(el).css("color","red");
}
$(el).text(settings.newText);
if( callback && typeof(callback) === "function" ) {
callback();
}
};
var underline = function() {
$(el).addClass("underline");
};
init();
});
};
}(jQuery));
Assign the plugin to selectors
var doTest = $("#testItem").testPlugin({
newText: "Scoobydoo"
});
var doNewTest = $("#newTestItem").testPlugin({
newText: "kapow!"
});
Call a function that is located within the plugin
$("#underline").click(function(e) {
e.preventDefault();
doTest.underline();
});

Take a look at closures.
Here is a basic example of what a closure looks like in a jQuery plugin.
$.fn.plugin = function() {
return {
helloWorld: function() {
console.log('Hello World!');
}
}
};
// init plugin.
var test = $('node').plugin();
// call a method from within the plugin outside of the plugin.
test.helloWorld();
You can see another example at the following jsfiddle.
http://jsfiddle.net/denniswaltermartinez/DwEFz/

First thing first we need to understand each step in building a jQuery plugin, its like build a javascript plugin (class) but we have in addition to it a jQuery class.
//We start with a function and pass a jQuery class to it as a
//parameter $ to avoid the conflict with other javascript
//plugins that uses '$ as a name
(function($){
//We now append our function to the jQuery namespace,
//with an option parameter
$.fn.myplugin = function(options) {
//the settings parameter will be our private parameter to our function
//'myplugin', using jQuery.extend append 'options' to our settings
var settings = jQuery.extend({
param:'value',
}, options);
//Define a reference to our function myplugin which it's
//part of jQuery namespace functions, so we can use later
//within inside functions
var $jquery=this;
//Define an output object that will work as a reference
//for our function
var output={
//Setup our plugin functions as an object elements
'function1':function(param){
//Call jQuery reference that goes through jQuery selector
$jquery.each(function(){
//Define a reference of each element of jQuery
//selector elements
var _this=this;
});
//This steps is required if you want to call nested
//functions like jQuery.
return output;
},
//If we want to make our plugin to do a specific operations
//when called, we define a function for that
'init':function(){
$jquery.each(function(){
var _this=this;
//Note that _this param linked to each jQuery
//functions not element, thus wont behave like
//jQuery function.
//And for that we set a parameter to reference the
//jQuery element
_this.$this=$(this);
//We can define a private function for 'init'
//function
var privatefun=function(){}
privatefun();
//We can now do jQuery stuffs on each element
_this.$this.on('click',function(){
//jQuery related stuffs
});
});
//We can call whatever function we want or parameter
//that belongs to our plugin
output.function1("value");
}
};
//Our output is ready, if we want our plugin to execute a
//function whenever it called we do it now
output.init();
//And the final critical step, return our object output to
//the plugin
return output;
};
//Pass the jQuery class so we can use it inside our plugin 'class'
})(jQuery);
Using our function now is very easy
<div class="plugintest">
<span>1</span>
<span>2</span>
<span>3</span>
<span>4</span>
</div>
<script>
$(function(){
var myplugin=$(".plugintest > span").myplugin({
param:'somevalue'
});
myplugin.function1(1).function1(2).function1(3);
});
</script>
In short, jQuery plugins and any Javascript plugins are simply about parameters scope.
Fiddle version
https://jsfiddle.net/eiadsamman/a59uwmga/

Related

Get plugin object reference back from element on which plugin is applied

Please consider following code. Here I have a jquery plugin myPlugin by using which I changed the ui of #targetElement
var myPluginVar = $('#targetElement').myPlugin();
I created a button and added a click event listener on it
$('#myButton').click(function(){
// HERE I want reference of myPlugin back.
}
Now on a button trigger I want to get back myPlugin object.
I don't want to use myPluginVar. Is there any way to get reference of myPlugin using element on which plugin is applied.
$.fn.myPlugin = function(){} will create a plugin that can be called on an element like this: $("#example").myPlugin();, as you know.
$.myPlugin = function(){} will create a plugin that can be called statically like this: $.myPlugin();.
So all you have to do is set $.myPlugin every time you call $.fn.myPlugin so it will refer to the last element used.
$.fn.myPlugin = function(){
this.text("Hello, world!");
var t = this;
$.myPlugin = function() {
return t;
}
};
$("#test").myPlugin();
$("#button").click(function(){
$.myPlugin().text("something else");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test">
</div>
<button id="button">Click Me</button>
thats depend on how you write your plugins.
following this example of basic plugin:
(function($){
$.fn.myPlugin = function(){
return this.text('Iam is myPlugin');
};
}(jQuery));
thats plugin (yet) cannot be referenced, because it didn't passed their self to anything.
but if change plugin code abbove to this:
(function($){
$.myPlugin = function(el){
$(el).data('myPlugin', this);
return $(el).text('Iam is myPlugin');
};
$.fn.myPlugin = function(){
return new $.myPlugin(this);
};
}(jQuery));
you can call plugin self referenced with:
$('#targetElement').data('myPlugin');
offcourse if plugin never initialized on #targetElement, it will returned as undefined
but if you have initialize #targetElement, with:
$('#targetElement').myPlugin();
it will return with $.myPlugin object

using $(this) inside jquery plugin

Here is my plugin code below.
$.fn.myplugin = function(options) {
var defaults = {
my_data_title11:"",
my_div:".getslow",
}
var settings = $.extend({}, defaults, options);
return this.each(function(){
console.log(options.my_data_title);
});
}
I am calling this plugin from an external page like this...
$('#o_vari,#0_var2').myplugin({
my_data_title11:$(this).attr("id"),my_div:'.getfast'
});
but it is displaying undefined. I am aware my_data_title11:$(this).attr("id") is not recognizing $(this) the calling statement, I even tried putting this exteral variable , but still the same problem.
From the way you have written the code, I'm assuming you wants to print o_vari and 0_var2... but that is not the case because in the context in which you have used $(this).att('id'), this does not refer to the o_varx element.
So if you want the desired output try
$('#o_vari,#0_var2').each(function () {
$(this).myplugin({
my_data_title: this.id,
my_div: '.getfast'
});
})
Demo: Fiddle

durandaljs - how to query a DOM element from a widget after ready

I want to query a element in a durandaljs widget, when it's ready.
If i use the selector directly in the data-binding, the element will not be found:
html (no attached view):
<button id="myButton"></button>
<div data-bind="widget: { kind: 'myWidget', options: { btn: $('#myButton') } }"></div>
controller.js:
define(function (require) {
var ctor = function (element, settings) {
var btn = settings.options.btn;
// btn = $('#myButton'); // this will work, but i'm not sure if the DOM is
// currently ready in the constructor
btn.on("click", function () {
console.log("I want to be fired");
});
};
return ctor;
});
Whats the best way to query a DOM element from a durandal widget at start?
I'm not sure where the html fragment belongs to so there are two slightly different answers.
First I'd suggest that you don't pass in the btnas jQuery object ({btn: $('myButton')}) , when you're not sure that it already exists. It's probably better to pass in a selector {btn: '#myButton'} and let the widget figure out how to deal with it.
Does your widget have its own view.html and the button is defined inside? If that's the case than you should take a look at the viewAttached callback.
var ctor = function (element, settings) {
this.btn = settings.options.btn;
};
ctor.prototype.viewAttached = function (view){
var btn = $(this.btn, view);
if ( btn.length > 0 ) {
btn.on("click", function () {
console.log("I want to be fired");
});
}
}
If your widget doesn't have its own view.html than you should let the widget know by adding a view property to the settings object with a value of false.
Here's the paragraph from http://durandaljs.com/documentation/Creating-A-Widget/ that explains that.
Note: In some cases, your widget may not actually need a view. Perhaps it's just adding some jQuery behavior or applying an existing jQuery plugin to a dom element. To tell Durandal that there is no view to load and bind, add a view property to the settings object with a value of false inside your widget's constructor.
In that instance however you can only access elements that are already in the DOM when the widget is instantiated e.g.
var ctor = function (element, settings) {
settings.view = false;
this.btn = $(settings.options.btn);
if ( this.btn.length > 0 ) {
this.btn.on("click", function () {
console.log("I want to be fired");
});
}
};

How to have multiple instances of jQuery plugin on single page?

I'm writing a simple jQuery plugin, but I'm having trouble being able to use multiple instances on a page.
For instance, here is a sample plugin to illustrate my point:
(function($) {
$.fn.samplePlugin = function(options) {
if (typeof foo != 'undefined')
{
alert('Already defined!');
} else {
var foo = 'bar';
}
};
})(jQuery);
And then if I do this:
$(document).ready(function(){
$('#myDiv').samplePlugin({}); // does nothing
$('#myDiv2').samplePlugion({}); // alerts "Already defined!"
});
This is obviously an over-simplified example to get across the point. So my question is, how do I have two separate instances of the plugin? I'd like to be able to use it across multiple instances on the same page.
I'm guessing that part of the problem might be with defining the variables in a global scope. How can I define them unique to that instance of the plugin then?
Thank you for your guidance!
I have the very same problem but i find a very handy solution i´ll post it for someone who may have this problem
when you define your variables insinde the plugin you could use the .data() to store all the variables you define
like this
(function($) {
$.fn.samplePlugin = function(options) {
var base = this;
this.foo // define foo
// do stuff with foo and other variables
// Add a reverse reference to the DOM object
this.data("pluginname", base);
};})(jQuery);
And when you want to use the same foo variable you should retrive the reference with this:
base = this.data("pluginname");
base.foo
Hope it helps
Logan
html:
<code class="resize1">resize1</code>
<code class="resize2">resize2</code>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
<script src="js/plugins.js"></script>
<script src="js/main.js"></script>
<script type="text/javascript">
jQuery(document).ready(function($) {
$('.resize1').ratiofix({message:'resize1'});
$('.resize2').ratiofix({message:'resize2'});
});
</script>
I have found 2 solutions - the first one is jquery widget factory
http://jqueryui.com/widget/
js code:
$.widget("custom.ratiofix",{
options:{
message:"nothing"
},
_create:function (){
var self=this;
this.setListeners();
},
setListeners:function (){
var self=this;
$(window).on('resize',$.proxy(self.printMsg,self));
},
printMsg:function (){
console.log(this.options.message);
}
});
And the second (without widget factory):
(function ($){
var Ratiofix = {
init: function(options, elem) {
this.options = $.extend({},this.options,options);
this.elem = elem;
this.$elem = $(elem);
this.setListeners();
return this;
},
options: {
message: "No message"
},
printMsg: function(){
console.log(this.options.message);
},
setListeners:function (){
var self=this;
this.$elem.on('click',function (){
console.log(self.options.message);
});
$(window).on('resize',$.proxy(self.printMsg, self));
}
};
$.fn.ratiofix=function (options){
this.init= function(options, elem) {
this.options = $.extend({},this.options,options);
this.elem = elem;
this.$elem = $(elem);
return this;
};
if ( this.length ) {
return this.each(function(){
var ratiofix = Object.create(Ratiofix);
ratiofix.init(options, this);
$.data(this, 'ratiofix', ratiofix);
});
}
};
})(jQuery);
In both cases plugins work separately and have own settings. In my case - 2 widgets listen to window resize and print to console own options.message
I'm not sure what you mean by having more than one instance of a plugin. A plugin would be available to use on any element.
This comment doesn't clarify much for me:
So say that it was a plugin that took
a "color" parameter and turned the
object into that color. Well, in that
case you'd need multiple instances, as
you're dealing with more than one page
element turning more than one color.
In this case, you would pass in different colors are arguments as needed:
$('div#foo').makeColor('red');
$('div#bar').makeColor('blue');
Each time you call the plugin, it will use whatever arguments you give it. The plugin isn't a class that needs instances.
Just throwing my solution in here:
(function ($){
$.fn.plugin = function (options){
var settings = $.extend({}, $.fn.plugin.defaults, options);
settings.that = $(this);
$.fn.plugin.init (settings);
};
$.fn.plugin.defaults = { objval: 'default' };
$.fn.plugin.init = function (settings){
settings.that.val (settings.objval);
};
}( jQuery ));
$('#target1').plugin ({objval: 'not default'});
$('#target2').plugin ();
DEMO
The settings variable is isolated every time you initialize the object.
To answer your question directly, you can use jQuery.noconflict() to avoid namespace collisions and thus potentially have multiple instantiations on a page..
var $j = jQuery.noConflict();
// Use jQuery via $j(...)
$j(document).ready(function() {
// etc
check here
But I question your design. Why are you writing a plugin that appears to not operate on a jQuery wrapped set ? .. Plugins should be written to assume they are operating on a jQuery array held in 'this'. In which case any state can be stored in each of the items being acted upon... But maybe you are building something different?
Please review this page
instead of writing this
$("#divid1").samplePlugin();
$("#divid2").samplePlugin();
you can do this way
$.plugin('samplePlugin1', samplePlugin);
$("#divid1").samplePlugin1();
$.plugin('samplePlugin2', samplePlugin);
$("#divid2").samplePlugin2();
You can have much details from here
http://alexsexton.com/?p=51
You need to use this.foo instead of var foo, so that the variable is only related to the current object.
This worked a treat for me! I had specific parameters for which pages/places I wanted to run a plugin and was able to achieve success by using a simple if statement. Hope this helps someone!
<!-- Begin JQuery Plugin Foo -->
<script src="js/foo_fun.js"></script>
<?php
if(substr_count(strtolower($currentUrl),"member")>0)
{
?>
<script>
$(document).ready(function(){
$('#vscroller').vscroller({newsfeed:'news_employee.xml', speed:1000,stay:2000,cache:false});
});
</script>
<?php
}
else
{
?>
<script>
$(document).ready(function(){
$('#vscroller').vscroller({newsfeed:'news_company.xml', speed:1000,stay:2000,cache:false});
});
</script>
<?php
}
?>
<!-- End JQuery Foo-->
I had the same problem : how to use many instances of a plugin on only one form ?
The usual way fails because in fact, the instance is not an instance of the plugin : it is an instance of jQuery.
So, if more than one element is defined to be managed by a plugin, each definition overrides the previous parameters.
It was necessary to have a look on the problem from another side.
A plugin is usually made to react on a specific event for a specific element. e.g.. onclick on a button, or when the mouse is over the element.
In my case, I had to use an autocomplete plugin for a city field, but my form has 5 tabs and in total 4 fields for the cities for 4 different parts of the information to be collected.
For each fields, parameters are specifics.
By the way, I've realised iI don't need to have the plugin active everytime : just on the appropriate event on the field is enough.
So I had an idea : an event manager for each element. When the event appends, so I define the plugin action.
Some code will be more efficient to explain : imagine you have 3 div blocks and your plugin must change the colours, but with specifics colours depending on which div is affected.
$(document).ready(function(){
// Wich elements are affected by the plugin
var ids = ['myDiv1','myDiv2','myDiv3'];
// foe each one :
for (v in ids)
{
//define from an event :
$('#'+ ids[v]).focus(function()
{
// depending which id is active :
var aParams, idDiv = $(this).attr('id');
// Choosing the right params
switch(idDiv)
{
case 'myDiv1':
aParams = {'color': '#660000', 'background-color': '#0000ff'};
break;
case 'myDiv2':
aParams = {'color': '#006600', 'background-color': '#ff00ff'};
break;
case 'myDiv3':
aParams = {'color': '#000066', 'background-color': '#ff0000'};
break;
default:
aParams = {'color': '#000000', 'background-color': '#ffffff'};
};
// Defining the plugin on the right element with the right params
$(this).myPlugin(
{
colors: aParams
});
});
}
});
And this works fine.
Sorry if my English is not perfect - I hope you understand well.

calling Jquery function from javascript

How can i call a jQuery function from javascript?
//jquery
$(function() {
function my_fun(){
/.. some operations ../
}
});
//just js
function js_fun () {
my_fun(); //== call jquery function
}
Yes you can (this is how I understand the original question).
Here is how I did it. Just tie it into outside context.
For example:
//javascript
my_function = null;
//jquery
$(function() {
function my_fun(){
/.. some operations ../
}
my_function = my_fun;
})
//just js
function js_fun () {
my_function(); //== call jquery function - just Reference is globally defined not function itself
}
I encountered this same problem when trying to access methods of the object, that was instantiated
on DOM object ready only. Works. My example:
MyControl.prototype = {
init: function {
// init something
}
update: function () {
// something useful, like updating the list items of control or etc.
}
}
MyCtrl = null;
// create jquery plug-in
$.fn.aControl = function () {
var control = new MyControl(this);
control.init();
MyCtrl = control; // here is the trick
return control;
}
now you can use something simple like:
function() = {
MyCtrl.update(); // yes!
}
You can't.
function(){
function my_fun(){
/.. some operations ../
}
}
That is a closure. my_fun() is defined only inside of that anonymous function. You can only call my_fun() if you declare it at the correct level of scope, i.e., globally.
$(function () {/* something */}) is an IIFE, meaning it executes immediately when the DOM is ready. By declaring my_fun() inside of that anonymous function, you prevent the rest of the script from "seeing" it.
Of course, if you want to run this function when the DOM has fully loaded, you should do the following:
function my_fun(){
/* some operations */
}
$(function(){
my_fun(); //run my_fun() ondomready
});
// just js
function js_fun(){
my_fun(); //== call my_fun() again
}
var jqueryFunction;
$().ready(function(){
//jQuery function
jqueryFunction = function( _msg )
{
alert( _msg );
}
})
//javascript function
function jsFunction()
{
//Invoke jQuery Function
jqueryFunction("Call from js to jQuery");
}
http://www.designscripting.com/2012/08/call-jquery-function-from-javascript/
<script>
// Instantiate your javascript function
niceJavascriptRoutine = null;
// Begin jQuery
$(document).ready(function() {
// Your jQuery function
function niceJqueryRoutine() {
// some code
}
// Point the javascript function to the jQuery function
niceJavaScriptRoutine = niceJueryRoutine;
});
</script>
jQuery functions are called just like JavaScript functions.
For example, to dynamically add the class "red" to the document element with the id "orderedlist" using the jQuery addClass function:
$("#orderedlist").addClass("red");
As opposed to a regular line of JavaScript calling a regular function:
var x = document.getElementById("orderedlist");
addClass() is a jQuery function, getElementById() is a JavaScript function.
The dollar sign function makes the jQuery addClass function available.
The only difference is the jQuery example is calling the addclass function of the jQuery object $("#orderedlist") and the regular example is calling a function of the document object.
In your code
$(function() {
// code to execute when the DOM is ready
});
Is used to specify code to run when the DOM is ready.
It does not differentiate (as you may think) what is "jQuery code" from regular JavaScript code.
So, to answer your question, just call functions you defined as you normally would.
//create a function
function my_fun(){
// call a jQuery function:
$("#orderedlist").addClass("red");
}
//call the function you defined:
myfun();
I made it...
I just write
jQuery('#container').append(html)
instead
document.getElementById('container').innerHTML += html;
//javascript function calling an jquery function
//In javascript part
function js_show_score()
{
//we use so many javascript library, So please use 'jQuery' avoid '$'
jQuery(function(){
//Call any jquery function
show_score(); //jquery function
});(jQuery);
}
//In Jquery part
jQuery(function(){
//Jq Score function
function show_score()
{
$('#score').val("10");
}
});(jQuery);
My problem was that I was looking at it from the long angle:
function new_line() {
var html= '<div><br><input type="text" value="" id="dateP_'+ i +'"></div>';
document.getElementById("container").innerHTML += html;
$('#dateP_'+i).datepicker({
showOn: 'button',
buttonImage: 'calendar.gif',
buttonImageOnly: true
});
i++;
}
<script>
$.myjQuery = function() {
alert("jQuery");
};
$(document).ready(function() {
alert("Welcome!");
});
function display() {
$.myjQuery();
};
</script>
<input type="button" value="submit" onclick=" display();">
Hope this will work for you!

Categories