JQuery plugin - callback breaks other features - javascript

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

Related

How to run 2 js functions

I have 2 function that I am trying to run, one after another. For some reason they both run at the same time, but the second one does not load properly. Is there a way to run the first function wait then run the second function?:
//run this first
$('#abc').click(function() {
$('.test1').show();
return false;
});
//run this second
(function ($) {
"use strict";
// A nice closure for our definitions
function getjQueryObject(string) {
// Make string a vaild jQuery thing
var jqObj = $("");
try {
jqObj = $(string)
.clone();
} catch (e) {
jqObj = $("<span />")
.html(string);
}
return jqObj;
}
function printFrame(frameWindow, content, options) {
// Print the selected window/iframe
var def = $.Deferred();
try {
frameWindow = frameWindow.contentWindow || frameWindow.contentDocument || frameWindow;
var wdoc = frameWindow.document || frameWindow.contentDocument || frameWindow;
if(options.doctype) {
wdoc.write(options.doctype);
}
wdoc.write(content);
wdoc.close();
var printed = false;
var callPrint = function () {
if(printed) {
return;
}
// Fix for IE : Allow it to render the iframe
frameWindow.focus();
try {
// Fix for IE11 - printng the whole page instead of the iframe content
if (!frameWindow.document.execCommand('print', false, null)) {
// document.execCommand returns false if it failed -http://stackoverflow.com/a/21336448/937891
frameWindow.print();
}
// focus body as it is losing focus in iPad and content not getting printed
$('body').focus();
} catch (e) {
frameWindow.print();
}
frameWindow.close();
printed = true;
def.resolve();
}
// Print once the frame window loads - seems to work for the new-window option but unreliable for the iframe
$(frameWindow).on("load", callPrint);
// Fallback to printing directly if the frame doesn't fire the load event for whatever reason
setTimeout(callPrint, options.timeout);
} catch (err) {
def.reject(err);
}
return def;
}
function printContentInIFrame(content, options) {
var $iframe = $(options.iframe + "");
var iframeCount = $iframe.length;
if (iframeCount === 0) {
// Create a new iFrame if none is given
$iframe = $('<iframe height="0" width="0" border="0" wmode="Opaque"/>')
.prependTo('body')
.css({
"position": "absolute",
"top": -999,
"left": -999
});
}
var frameWindow = $iframe.get(0);
return printFrame(frameWindow, content, options)
.done(function () {
// Success
setTimeout(function () {
// Wait for IE
if (iframeCount === 0) {
// Destroy the iframe if created here
$iframe.remove();
}
}, 1000);
})
.fail(function (err) {
// Use the pop-up method if iframe fails for some reason
console.error("Failed to print from iframe", err);
printContentInNewWindow(content, options);
})
.always(function () {
try {
options.deferred.resolve();
} catch (err) {
console.warn('Error notifying deferred', err);
}
});
}
function printContentInNewWindow(content, options) {
// Open a new window and print selected content
var frameWindow = window.open();
return printFrame(frameWindow, content, options)
.always(function () {
try {
options.deferred.resolve();
} catch (err) {
console.warn('Error notifying deferred', err);
}
});
}
function isNode(o) {
/* http://stackoverflow.com/a/384380/937891 */
return !!(typeof Node === "object" ? o instanceof Node : o && typeof o === "object" && typeof o.nodeType === "number" && typeof o.nodeName === "string");
}
$.print = $.fn.print = function () {
// Print a given set of elements
var options, $this, self = this;
// console.log("Printing", this, arguments);
if (self instanceof $) {
// Get the node if it is a jQuery object
self = self.get(0);
}
if (isNode(self)) {
// If `this` is a HTML element, i.e. for
// $(selector).print()
$this = $(self);
if (arguments.length > 0) {
options = arguments[0];
}
} else {
if (arguments.length > 0) {
// $.print(selector,options)
$this = $(arguments[0]);
if (isNode($this[0])) {
if (arguments.length > 1) {
options = arguments[1];
}
} else {
// $.print(options)
options = arguments[0];
$this = $("html");
}
} else {
// $.print()
$this = $("html");
}
}
// Default options
var defaults = {
globalStyles: true,
mediaPrint: false,
stylesheet: null,
noPrintSelector: ".no-print",
iframe: true,
append: null,
prepend: null,
manuallyCopyFormValues: true,
deferred: $.Deferred(),
timeout: 750,
title: null,
doctype: '<!doctype html>'
};
// Merge with user-options
options = $.extend({}, defaults, (options || {}));
var $styles = $("");
if (options.globalStyles) {
// Apply the stlyes from the current sheet to the printed page
$styles = $("style, link, meta, base, title");
} else if (options.mediaPrint) {
// Apply the media-print stylesheet
$styles = $("link[media=print]");
}
if (options.stylesheet) {
// Add a custom stylesheet if given
$styles = $.merge($styles, $('<link rel="stylesheet" href="' + options.stylesheet + '">'));
}
// Create a copy of the element to print
var copy = $this.clone();
// Wrap it in a span to get the HTML markup string
copy = $("<span/>")
.append(copy);
// Remove unwanted elements
copy.find(options.noPrintSelector)
.remove();
// Add in the styles
copy.append($styles.clone());
// Update title
if (options.title) {
var title = $("title", copy);
if (title.length === 0) {
title = $("<title />");
copy.append(title);
}
title.text(options.title);
}
// Appedned content
copy.append(getjQueryObject(options.append));
// Prepended content
copy.prepend(getjQueryObject(options.prepend));
if (options.manuallyCopyFormValues) {
// Manually copy form values into the HTML for printing user-modified input fields
// http://stackoverflow.com/a/26707753
copy.find("input")
.each(function () {
var $field = $(this);
if ($field.is("[type='radio']") || $field.is("[type='checkbox']")) {
if ($field.prop("checked")) {
$field.attr("checked", "checked");
}
} else {
$field.attr("value", $field.val());
}
});
copy.find("select").each(function () {
var $field = $(this);
$field.find(":selected").attr("selected", "selected");
});
copy.find("textarea").each(function () {
// Fix for https://github.com/DoersGuild/jQuery.print/issues/18#issuecomment-96451589
var $field = $(this);
$field.text($field.val());
});
}
// Get the HTML markup string
var content = copy.html();
// Notify with generated markup & cloned elements - useful for logging, etc
try {
options.deferred.notify('generated_markup', content, copy);
} catch (err) {
console.warn('Error notifying deferred', err);
}
// Destroy the copy
copy.remove();
if (options.iframe) {
// Use an iframe for printing
try {
printContentInIFrame(content, options);
} catch (e) {
// Use the pop-up method if iframe fails for some reason
console.error("Failed to print from iframe", e.stack, e.message);
printContentInNewWindow(content, options);
}
} else {
// Use a new window for printing
printContentInNewWindow(content, options);
}
return this;
};
})(jQuery);
How would I run the first one wait 5 or so seconds and then run the jquery print? I'm having a hard time with this. So the id would run first and then the print would run adter the id="abc" Here is an example of the code in use:
<div id="test">
<button id="abc" class="btn" onclick="jQuery.print(#test1)"></button>
</div>
If I understand your problem correctly, you want the jQuery click function to be run first, making a div with id="test1" visible and then, once it's visible, you want to run the onclick code which calls jQuery.print.
The very first thing I will suggest is that you don't have two different places where you are handling the click implementation, that can make your code hard to follow.
I would replace your $('#abc').click with the following:
function printDiv(selector) {
$(selector).show();
window.setTimeout(function () {
jQuery.print(selector);
}, 1);
}
This function, when called, will call jQuery.show on the passed selector, wait 1ms and then call jQuery.print. If you need the timeout to be longer, just change the 1 to whatever you need. To use the function, update your example html to the following:
<div id="test">
<button id="abc" class="btn" onclick="printDiv('#test1')"</button>
</div>
When the button is clicked, it will now call the previously mentioned function and pass it the ID of the object that you want to print.
As far as your second function goes, where you have the comment **//run this second**, you should leave that alone. All it does is extend you jQuery object with the print functionality. You need it to run straight away and it currently does.

Access originally clicked element in jQuery plugin

I have the following plugin, and while I wish it to be able to be applied to multiple elements, I do not wish to create a new dialog for each element.
But in the dialog.open callback or when the button is clicked, I wish to be able to access the element which was clicked and opened the dialog.
If I wanted to create multiple dialogs, I suppose I could put this.each(function () {...} in the init method and then this would be the individually clicked element, but as stated earlier, I only one one dialog.
EDIT. I revised the code so that it does what I need it to do. It just seems like a bit of a hack using data as I did. Is there a more proper way to do so?
How is this accomplished?
(function($){
var defaults = {};
var methods = {
init : function (options) {
var settings = $.extend({}, defaults, options);
var dialog = $('<div/>').dialog({
open: function( event, ui ) {
console.log(dialog.data('elementThatWasClicked'));
},
buttons: [
{
text: 'click',
click: function() {console.log(dialog.data('elementThatWasClicked'));}
}
]
});
return this.each(function () {
var $this=$(this);
$this.click(function(){dialog.data('elementThatWasClicked',$this).dialog('open')});
});
}
};
$.fn.test = function(method) {
if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === 'object' || ! method) {
return methods.init.apply(this, arguments);
} else {
$.error('Method ' + method + ' does not exist on jQuery.test');
}
};
}(jQuery));
$(function(){
$('.bla').test();
});

CKEditor - get editor data and custom widget

I have following custom ckeditor widget code:
(function()
{
"use strict";
var jQuery = require("jquery"),
Underscore = require("underscore"),
$template = jQuery('<div class="section-wrapper">' +
'<div class="section-label"><span class="section-label-user"></span><span class="cricon cricon-lock"></span><span class="status-icon cricon"></span><span class="section-label-text"></span><span class="section-label-loader"></span></div>' +
'<div class="clearfix"></div>' +
'<div class="section-content">' +
'</div>' +
'</div>'),
bindEvents = function bindEvents(editor, section)
{
if(typeof editor.config.sectionPlugin.handlers !== "undefined")
{
Underscore.each(editor.config.sectionPlugin.handlers, function(callback, eventName)
{
section.on(eventName, callback);
});
}
};
CKEDITOR.plugins.add('section', {
requires: 'widget',
init: function(editor)
{
var self = this;
// Register the section widget.
editor.widgets.add('section', {
inline: false,
allowedContent: 'section[!data-cid]',
draggable: false,
// button is required for UPCAST processing? stupid bug?
button: 'sectionbtn',
init: function()
{
var sectionContent;
this.$element = jQuery(this.element.$);
sectionContent = this.$element.html();
// create html structure
this.$template = $template.clone();
this.$template.find(".section-content").html(sectionContent);
this.$element.html(this.$template);
// set editable content
this.initEditable("content", {
selector: ".section-content"
});
bindEvents(editor, this);
},
bindToContract: function(contract, options)
{
this.section_class = contract.get("sections").get(this.$element.attr("data-cid"));
if(!this.section_class)
{
this.$element.addClass("is-corrupted");
return false;
}
this.section_class.on("change:name", this.update, this);
this.update();
},
update: function()
{
this.$element.find(".section-label-text").text(this.section_class.get("name") + " header" + Math.random());
},
upcast: function(element)
{
return element.name === 'section';
},
downcast: function(widgetElement)
{
return widgetElement;
},
destroy: function(offline)
{
CKEDITOR.plugins.widget.prototype.destroy.call(this, offline);
}
});
}
});
})();
When I am using ckeInstance.getData() method then whole code (widget template) is returned.
Is there any way to define what widget/getData() should return?
I don't want to parse code returned by .getData() method. I think it should be done with ckeditor.
You got to expand your downcast function in the definition of the widget. It should return element or text and this is where you control the the widget's representation in data. Of course, once you define it, make sure the upcast function is able to decode such an representation from data back into DOM (i.e. your template).
For instance, your downcast could be like
function( widgetElement ) {
var el = new CKEDITOR.htmlParser.element( 'div', {
'data-content': this.editables.content.getData()
} );
el.setHtml( 'foo' );
return el;
}
if you were interested in nothing but the content of nested editable in a data attribute. It would convert your widget into
<div data-content="HTML of nested editable">foo</div>
once you call editor.getData(). If you write a corresponding upcast that extracts data-content and re–builds the DOM so it again looks like your widget template, then you have a full state machine that converts the widget between data and DOM.
In short downcast function is a kind of encoder (DOM->data) and upcast – a decoder (data->DOM).

jquery AMD plugin - each() does not loop?

I tried to make a jquery plugin in AMD pattern and it seems that I can't get the each() to loop. It only return the first item but I have three items.
index.html,
<body>
<div class="element">
1
</div>
<div class="element">
2
</div>
<div class="element">
3
</div>
</body>
in the html head,
$(document).ready(function(){
$(".element").plugin2().data('plugin_plugin2').someMethod();
});
plugin.js,
!function(root, factory) {
if (typeof define === 'function' && define.amd) {
define(['jquery'], factory);
} else {
factory(root.jQuery);
}
}(this, function($) {
var pluginName = 'plugin2',
defaults = {
param1: 'param1',
param2: 'param2'
};
var Plugin = function(element, options) {
this.element = element;
this.options = options;
};
Plugin.prototype = {
constructor: Plugin,
someMethod: function(options) {
var rootScope = this;
return rootScope.element.each(function(e){
console.log(e); // you get 0 only
console.log(this); // the first <div class="element"> only
});
}
};
$.fn[pluginName] = function(options) {
options = $.extend(true, {}, defaults, options);
return this.each(function() {
var $this = $(this);
$this.data('plugin_' + pluginName, new Plugin($this, options));
});
};
$.fn[pluginName].defaults = defaults;
$.fn[pluginName].Plugin = Plugin;
});
any ideas what have I done wrong?
Like all of jQuery's getter/setter methods, data is asymmetrical: When setting, it sets on all elements in a jQuery set, but when getting, it only gets from the first.
So this line:
$(".element").plugin2().data('plugin_plugin2').someMethod();
...will only give you the data from the first element in the set. If you want to see the data for all three, you need to loop there, too:
$(".element").plugin2().each(function() {
$(this).data('plugin_plugin2').someMethod();
});
But fundamentally, what your code is doing is not how you implement methods in plugins (not least for this reason). Instead, the usual way to implement methods in plugins is to have the main plugin method accept a string (the method name), e.g.:
$(".element").plugin2().plugin2("someMethod");
thanks. so how does it look for boilerplate for doing this -$(".element").plugin2().plugin2("someMethod");
Here's a very minimal example:
(function($) {
var methods = {
init: function() {
// If you have to do different things on different
// elements, use this.each(...) or similar
this.css("color", "red");
return this;
},
color: function(color) {
// If you have to do different things on different
// elements, use this.each(...) or similar
this.css("color", color);
return this;
},
increment: function(color) {
// For example, this is effectively a `this.each(...)`:
this.text(function() {
return +$(this).text() + 1;
});
return this;
}
};
var slice = Array.prototype.slice;
$.fn.foo = function(method) {
var f = methods[method || "init"];
if (!f) {
throw "Unknown method for plugin `foo`: '" + method + "'";
}
return f.apply(this, slice.call(arguments, 1));
};
})(jQuery);
setTimeout(function() {
$(".element").foo();
}, 500);
setTimeout(function() {
$(".element").foo("color", "green");
}, 1000);
setTimeout(function() {
$(".element").foo("increment");
}, 1500);
<div class="element">1</div>
<div class="element">2</div>
<div class="element">3</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

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.

Categories