jQuery plugin development preserve element original state - javascript

I'm developing a jQuery plugin to create modal windows, so, now, I want to restore element original state after hide it.
Someone can help me?
Thanks!
---- update ---
Sorry,
I want to store element html in some place when show it, then put the stored data back when hide it.
This is my plugin:
(function ($) { // v2ui_modal
var methods = {
show: function (options) {
var _this = this;
var defaults = {
showOverlay: true,
persistentContent: true
};
var options = $.extend(defaults, options);
if (!_this.attr('id')) {
_this.attr('id', 'v2ui-id_' + Math.random().toString().replace('.', ''));
}
if (options.showOverlay) {
$('<div />', { // overlay
id: 'v2-ui-plugin-modal-overlay-' + this.attr('id'),
css: {
zIndex: ($.topZIndex() + 1),
display: 'none',
position: 'fixed',
width: '100%',
height: '100%',
top: 0,
left: 0
}
}).addClass('v2-ui').addClass('plugin').addClass('overlay').appendTo('body');
};
_this.css({
zIndex: ($.topZIndex() + 2),
position: 'fixed'
});
_this.center();
$('#v2-ui-plugin-modal-overlay-' + _this.attr('id')).fadeIn(function () {
_this.fadeIn();
});
},
hide: function () {
var _this = this;
_this.fadeOut();
$('#v2-ui-plugin-modal-overlay-' + _this.attr('id')).fadeOut(function () {
$('#v2-ui-plugin-modal-overlay-' + _this.attr('id')).remove();
if ((_this.attr('id')).substr(0, 8) == 'v2ui-id_') {
_this.removeAttr('id');
};
});
}
};
jQuery.fn.v2ui_modal = function (methodOrOptions) {
if (methods[methodOrOptions]) {
methods[methodOrOptions].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof methodOrOptions === 'object' || !methodOrOptions) {
methods.show.apply(this, arguments);
};
};
})(jQuery);

You can take a look at jQuery.detach.
The .detach() method is the same as .remove(), except that .detach()
keeps all jQuery data associated with the removed elements. This
method is useful when removed elements are to be reinserted into the
DOM at a later time.
But I am having a hard time understanding your problem fully, so I apologize if my answer does not fit your question.

Related

jQuery plugin: prevent multiply calls of an object

Recently, I'm writing a jQuery plugin which moves html elements.
My plugin is something like this:
$('#div1').moveIt({ top: 100, left: 200 });
The problem is, When I call moveIt more than once for an element. It does all methods together. something like this:
$('#div1').moveIt({ top: 100, left: 200 }); // first call
$('#div1').moveIt({ top: 200, left: 300 }); // second call
// even more calls ....
The questions are:
How can I prevent the the second call inside my plugin?
How can I overwrite the new values of second call into the first call?
A simple sample code will be enough.
edit: here is my problem
UPDATED: What about your problem - check fiddle http://jsfiddle.net/vittore/jHzLN/1/
You have to save timeout and clear it when you set new one.
What you are asking for is called throttle.
Check this article http://benalman.com/projects/jquery-throttle-debounce-plugin/
But as you are really using jquery animations ( your plugin name tells that ), you have to use something else.
Check stop() method
$(selector).stop(true, true).animate(...)
Another interesting thing you can do is queue additional animations. Use queue:true option for that:
$(selector).animate({ left:...} , { queue: true })
Is this what you were going for? http://jsfiddle.net/acbabis/B89Bx/. Let me know:
$(function()
{
var methods =
{
init : function(options) {
$(this).each(function() {
var self = $(this);
var settings = $.extend({
top : 50,
left : 50,
dir : true,
}, options);
var i=0, j=0;
var move = function()
{
settings = self.data('moveItTarget');
if(settings.dir)
{
i++;
j++;
}
else
{
i+=10;
j+=10;
}
self.css({'top':Math.min(i, settings.top),
'left':Math.min(j, settings.left)});
if(j<=settings.top && i<=settings.top)
{
setTimeout(move,1);
} else {
self.data('movingIt', false);
}
};
self.data('moveItTarget', settings);
if(!self.data('movingIt')) {
self.data('movingIt', true);
move();
}
});
}
};
$.fn.moveIt = function(methodOrOptions) {
if (methods[methodOrOptions]) {
return methods[methodOrOptions].apply(this,
Array.prototype.slice.call(arguments, 1));
} else if (typeof methodOrOptions==='object' || !methodOrOptions) {
return methods.init.apply(this, arguments);
} else {
$.error('Method "'+methodOrOptions+'" does not exist!');
}
};
}(jQuery));
$('#div1').moveIt({ top: 100, left: 100, dir: true }); // first call
$('#div1').moveIt({ top: 300, left: 300, dir: false }); // second call

jquery .hover() with else if statement

I want to put a little delay for onmouseout event for a group of sub items in a drop down menu. But I don't want to use css transitions.
I set it with .hover() and setTimeout method but I wanted to put it only for a specific elements in menu - in this case just for sub items so I used if else statement for them. I have no idea why this if else statement does't work.
Here is my javascript code:
var selectors =
{
element: '.main-menu li:has(ul)'
}
var opacityWorkaround = function ($element, value) {
$element.css('opacity', value);
};
var getAnimationValues = function (visible) {
var result = {
visibility: visible
};
result.opacity = visible === 'visible' ? 1 : 0;
};
var mouseActionHandler = function ($element, visible, opacityValue) {
$element
.stop()
.css("visibility", 'visible')
.animate(getAnimationValues(visible),
3000,
function () {
$(this).css("visibility", visible);
opacityWorkaround($(this), opacityValue);
});
};
var onMouseIn = function () {
var $submenu = $(this).children("ul:first");
if ($submenu) {
mouseActionHandler($submenu, 'visible', 1);
}
};
var onMouseOut = function () {
var $submenu = $(this).children("ul:first");
var $global = $('.global').children('ul');
if ($submenu) {
mouseActionHandler($submenu, 'hidden', 0);
} else if ($global) {
setTimeout(function() {
mouseActionHandler($global, 'hidden', 0);
},1500);
}
};
$(selectors.element).hover(onMouseIn, onMouseOut);
I put 1500ms delay and the $global variable is referring to sub items in menu that I want to make disapear with that delay. I wanted to achieve this when user move mouse cursor out of 'some items >' tab.
Here is my fiddle example.
http://jsfiddle.net/PNz9F/1/
Thanks in advance for any help!
In the example you have in your question $submenu always has a value so the else if statement is never run. You can check for a class instead.
var timeout;
var $submenu = $(this).children("ul:first");
var $global = $('.global').children('ul');
if ($(this).hasClass('menu-item')) {
mouseActionHandler($submenu, 'hidden', 0);
mouseActionHandler($global, 'hidden', 0);
clearTimeout(timeout);
} else if ($(this).hasClass('global')) {
timeout = setTimeout(function() {
mouseActionHandler($global, 'hidden', 0);
},1500);
}
you should be able to just use the :hover selector in your code to check whether the user is hovering over the element or not and run code accordingly

Hide all instances of element except one currently being written / displayed

I have this notification system that works with the following jQuery / javascript and displays a notification when called.
What I am having some trouble doing and what I am trying to do is once a new notification is create to hide and remove / destroy any existing notifications.
I've tried something like this: $('.notification').not(this).hide().remove();, but that didn't work.
Here is the jQuery behind the notifications:
;(function($) {
$.notificationOptions = {
className: '',
click: function() {},
content: '',
duration: 5000,
fadeIn: 400,
fadeOut: 600,
limit: false,
queue: false,
slideUp: 200,
horizontal: 'right',
vertical: 'top',
afterShow: function(){},
afterClose: function(){}
};
var Notification = function(board, options) {
var that = this;
// build notification template
var htmlElement = $([
'<div class="notification ' + options.className + '" style="display:none">',
'<div class="close"></div>',
options.content,
'</div>'
].join(''));
// getter for template
this.getHtmlElement = function() {
return htmlElement;
};
// custom hide
this.hide = function() {
htmlElement.addClass('hiding');
htmlElement.animate({ opacity: .01 }, options.fadeOut, function() {
var queued = queue.shift();
if (queued) {
$.createNotification(queued);
}
});
htmlElement.slideUp(options.slideUp, function() {
$(this).remove();
options.afterClose();
});
};
// show in board
this.show = function() {
// append to board and show
htmlElement[options.vertical == 'top' ? 'appendTo' : 'prependTo'](board);
htmlElement.fadeIn(options.fadeIn, options.afterShow());
//$('.notification').css('marginLeft', -$('.notification').outerWidth()/2);
$('.notification-board.center').css('marginLeft', -($('.notification-board.center').width()/2));
$(window).on('resize', function(){
$('.notification-board.center').css('marginLeft', -($('.notification-board.center').width()/2));
});
};
// set custom click callback
htmlElement.on('click', function() {
options.click.apply(that);
});
// helper classes to avoid hide when hover
htmlElement.on('mouseenter', function() {
htmlElement.addClass('hover');
if (htmlElement.hasClass('hiding')) {
// recover
htmlElement.stop(true);
// reset slideUp, could not find a better way to achieve this
htmlElement.attr('style', 'opacity: ' + htmlElement.css('opacity'));
htmlElement.animate({ opacity: 1 }, options.fadeIn);
htmlElement.removeClass('hiding');
htmlElement.addClass('pending');
}
});
htmlElement.on('mouseleave', function() {
if (htmlElement.hasClass('pending')) {
// hide was pending
that.hide();
}
htmlElement.removeClass('hover');
});
// close button bind
htmlElement.children('.close').on('click', function() {
that.hide();
});
if (options.duration) {
// hide timer
setTimeout(function() {
if (htmlElement.hasClass('hover')) {
// hovering, do not hide now
htmlElement.addClass('pending');
} else {
that.hide();
}
}, options.duration);
}
return this;
};
var queue = [];
$.createNotification = function(options) {
options = $.extend({}, $.notificationOptions, options || {});
// get notification container (aka board)
var board = $('.notification-board.' + options.horizontal + '.' + options.vertical);
if (!board.length) {
board = $('<div class="notification-board ' + options.horizontal + ' ' + options.vertical + '" />');
board.appendTo('body');
}
if (options.limit && board.children('.notification:not(.hiding)').length >= options.limit) {
// limit reached
if (options.queue) {
queue.push(options);
}
return;
}
// create new notification and show
var notification = new Notification(board, options)
notification.show(board);
return notification;
};
})(jQuery);
and here is how the notifications are called / created:
$.createNotification({
horizontal:'center',
vertical:'top',
content:'No more cards at this time.',
duration:6000,
click:function(){
this.hide();
}
});
The code:
$('.notification').not(this).hide().remove();
will work just fine to remove all .notification DOM elements currently in the DOM except the current one IF this is the current notification DOM element. If that code isn't working, then it's likely because this isn't the desired notification DOM element that you want to keep. If this is an instance of your Notification class, then that's the wrong type of object. For that above code to work, this has to be the notification DOM object.
If you want to just remove all old notification DOM elements BEFORE you insert your new one, then you can just do this before your new one is in the DOM:
$('.notification').remove();
That will clear out the old ones before you insert your new one.
Since you don't have this line of code in your currently posted code, I can't tell where you were trying to use it so can't advise further on what might be wrong. Please describe further where in your code you were trying to use this.

jQGrid Column Chooser Modal Overlay

Looking off this example, notice how clicking on the Search button brings up a modal form with a darkened overlay behind it. Now notice how clicking on the Column Chooser button brings up a modal form but no overlay behind it.
My question is: how do I get the dark overlay to appear behind my Column Chooser popup?
There are currently undocumented option of the columnChooser:
$(this).jqGrid('columnChooser', {modal: true});
The demo demonstrate this. One can set default parameters for the columnChooser with respect of $.jgrid.col too:
$.extend(true, $.jgrid.col, {
modal: true
});
Recently I posted the suggestion to extend a little functionality of the columnChooser, but only a part of the changes are current code of the jqGrid. Nevertheless in the new version will be possible to set much more jQuery UI Dialog options with respect of new dialog_opts option. For example the usage of the following will be possible
$(this).jqGrid('columnChooser', {
dialog_opts: {
modal: true,
minWidth: 470,
show: 'blind',
hide: 'explode'
}
});
To use full features which I suggested you can just overwrite the standard implementation of columnChooser. One can do this by including the following code
$.jgrid.extend({
columnChooser : function(opts) {
var self = this;
if($("#colchooser_"+$.jgrid.jqID(self[0].p.id)).length ) { return; }
var selector = $('<div id="colchooser_'+self[0].p.id+'" style="position:relative;overflow:hidden"><div><select multiple="multiple"></select></div></div>');
var select = $('select', selector);
function insert(perm,i,v) {
if(i>=0){
var a = perm.slice();
var b = a.splice(i,Math.max(perm.length-i,i));
if(i>perm.length) { i = perm.length; }
a[i] = v;
return a.concat(b);
}
}
opts = $.extend({
"width" : 420,
"height" : 240,
"classname" : null,
"done" : function(perm) { if (perm) { self.jqGrid("remapColumns", perm, true); } },
/* msel is either the name of a ui widget class that
extends a multiselect, or a function that supports
creating a multiselect object (with no argument,
or when passed an object), and destroying it (when
passed the string "destroy"). */
"msel" : "multiselect",
/* "msel_opts" : {}, */
/* dlog is either the name of a ui widget class that
behaves in a dialog-like way, or a function, that
supports creating a dialog (when passed dlog_opts)
or destroying a dialog (when passed the string
"destroy")
*/
"dlog" : "dialog",
/* dlog_opts is either an option object to be passed
to "dlog", or (more likely) a function that creates
the options object.
The default produces a suitable options object for
ui.dialog */
"dlog_opts" : function(opts) {
var buttons = {};
buttons[opts.bSubmit] = function() {
opts.apply_perm();
opts.cleanup(false);
};
buttons[opts.bCancel] = function() {
opts.cleanup(true);
};
return $.extend(true, {
"buttons": buttons,
"close": function() {
opts.cleanup(true);
},
"modal" : opts.modal ? opts.modal : false,
"resizable": opts.resizable ? opts.resizable : true,
"width": opts.width+20,
resize: function (e, ui) {
var $container = $(this).find('>div>div.ui-multiselect'),
containerWidth = $container.width(),
containerHeight = $container.height(),
$selectedContainer = $container.find('>div.selected'),
$availableContainer = $container.find('>div.available'),
$selectedActions = $selectedContainer.find('>div.actions'),
$availableActions = $availableContainer.find('>div.actions'),
$selectedList = $selectedContainer.find('>ul.connected-list'),
$availableList = $availableContainer.find('>ul.connected-list'),
dividerLocation = opts.msel_opts.dividerLocation || $.ui.multiselect.defaults.dividerLocation;
$container.width(containerWidth); // to fix width like 398.96px
$availableContainer.width(Math.floor(containerWidth*(1-dividerLocation)));
$selectedContainer.width(containerWidth - $availableContainer.outerWidth() - ($.browser.webkit ? 1: 0));
$availableContainer.height(containerHeight);
$selectedContainer.height(containerHeight);
$selectedList.height(Math.max(containerHeight-$selectedActions.outerHeight()-1,1));
$availableList.height(Math.max(containerHeight-$availableActions.outerHeight()-1,1));
}
}, opts.dialog_opts || {});
},
/* Function to get the permutation array, and pass it to the
"done" function */
"apply_perm" : function() {
$('option',select).each(function(i) {
if (this.selected) {
self.jqGrid("showCol", colModel[this.value].name);
} else {
self.jqGrid("hideCol", colModel[this.value].name);
}
});
var perm = [];
//fixedCols.slice(0);
$('option:selected',select).each(function() { perm.push(parseInt(this.value,10)); });
$.each(perm, function() { delete colMap[colModel[parseInt(this,10)].name]; });
$.each(colMap, function() {
var ti = parseInt(this,10);
perm = insert(perm,ti,ti);
});
if (opts.done) {
opts.done.call(self, perm);
}
},
/* Function to cleanup the dialog, and select. Also calls the
done function with no permutation (to indicate that the
columnChooser was aborted */
"cleanup" : function(calldone) {
call(opts.dlog, selector, 'destroy');
call(opts.msel, select, 'destroy');
selector.remove();
if (calldone && opts.done) {
opts.done.call(self);
}
},
"msel_opts" : {}
}, $.jgrid.col, opts || {});
if($.ui) {
if ($.ui.multiselect ) {
if(opts.msel == "multiselect") {
if(!$.jgrid._multiselect) {
// should be in language file
alert("Multiselect plugin loaded after jqGrid. Please load the plugin before the jqGrid!");
return;
}
opts.msel_opts = $.extend($.ui.multiselect.defaults,opts.msel_opts);
}
}
}
if (opts.caption) {
selector.attr("title", opts.caption);
}
if (opts.classname) {
selector.addClass(opts.classname);
select.addClass(opts.classname);
}
if (opts.width) {
$(">div",selector).css({"width": opts.width,"margin":"0 auto"});
select.css("width", opts.width);
}
if (opts.height) {
$(">div",selector).css("height", opts.height);
select.css("height", opts.height - 10);
}
var colModel = self.jqGrid("getGridParam", "colModel");
var colNames = self.jqGrid("getGridParam", "colNames");
var colMap = {}, fixedCols = [];
select.empty();
$.each(colModel, function(i) {
colMap[this.name] = i;
if (this.hidedlg) {
if (!this.hidden) {
fixedCols.push(i);
}
return;
}
select.append("<option value='"+i+"' "+
(this.hidden?"":"selected='selected'")+">"+colNames[i]+"</option>");
});
function call(fn, obj) {
if (!fn) { return; }
if (typeof fn == 'string') {
if ($.fn[fn]) {
$.fn[fn].apply(obj, $.makeArray(arguments).slice(2));
}
} else if ($.isFunction(fn)) {
fn.apply(obj, $.makeArray(arguments).slice(2));
}
}
var dopts = $.isFunction(opts.dlog_opts) ? opts.dlog_opts.call(self, opts) : opts.dlog_opts;
call(opts.dlog, selector, dopts);
var mopts = $.isFunction(opts.msel_opts) ? opts.msel_opts.call(self, opts) : opts.msel_opts;
call(opts.msel, select, mopts);
// fix height of elements of the multiselect widget
var resizeSel = "#colchooser_"+$.jgrid.jqID(self[0].p.id),
$container = $(resizeSel + '>div>div.ui-multiselect'),
$selectedContainer = $(resizeSel + '>div>div.ui-multiselect>div.selected'),
$availableContainer = $(resizeSel + '>div>div.ui-multiselect>div.available'),
containerHeight,
$selectedActions = $selectedContainer.find('>div.actions'),
$availableActions = $availableContainer.find('>div.actions'),
$selectedList = $selectedContainer.find('>ul.connected-list'),
$availableList = $availableContainer.find('>ul.connected-list');
$container.height($container.parent().height()); // increase the container height
containerHeight = $container.height();
$selectedContainer.height(containerHeight);
$availableContainer.height(containerHeight);
$selectedList.height(Math.max(containerHeight-$selectedActions.outerHeight()-1,1));
$availableList.height(Math.max(containerHeight-$availableActions.outerHeight()-1,1));
// extend the list of components which will be also-resized
selector.data('dialog').uiDialog.resizable("option", "alsoResize",
resizeSel + ',' + resizeSel +'>div' + ',' + resizeSel + '>div>div.ui-multiselect');
}
});
In the case you can continue to use the original minimized version of jquery.jqGrid.min.js and the code which use can be just $(this).jqGrid('columnChooser');. Together with all default settings it will be like
$.extend(true, $.ui.multiselect, {
locale: {
addAll: 'Make all visible',
removeAll: 'Hidde All',
itemsCount: 'Avlialble Columns'
}
});
$.extend(true, $.jgrid.col, {
width: 450,
modal: true,
msel_opts: {dividerLocation: 0.5},
dialog_opts: {
minWidth: 470,
show: 'blind',
hide: 'explode'
}
});
$grid.jqGrid('navButtonAdd', '#pager', {
caption: "",
buttonicon: "ui-icon-calculator",
title: "Choose columns",
onClickButton: function () {
$(this).jqGrid('columnChooser');
}
});
The demo demonstrate the approach. The main advantage of the changes - the really resizable Column Chooser:
UPDATED: Free jqGrid fork of jqGrid, which I develop starting with the end of 2014, contains of cause the modified code of columnChooser.
I get the following error while trying the code on the mobile device.
Result of expression 'selector.data('dialog').uiDialog' [undefined] is not an object.
The error points to the following line of code.
selector.data('dialog').uiDialog.resizable("option", "alsoResize", resizeSel + ',' + resizeSel +'>div' + ',' + resizeSel + '>div>div.ui-multiselect');
When I inspect the code, I find that the data object does not have anything called uiDialog.
just been looking thru the code, try adding this line:
jqModal : true,
to this code:
$grid.jqGrid('navButtonAdd', '#pager', {
caption: "",
buttonicon: "ui-icon-calculator",
title: "Choose columns",
onClickButton: function () {
....
like this:
$grid.jqGrid('navButtonAdd', '#pager', {
caption: "",
buttonicon: "ui-icon-calculator",
title: "Choose columns",
jqModal : true,
onClickButton: function () {
....

jQuery plugin feedback

I'm new to building jQuery plugins.
I have seen and used a lot of tooltip plugins, and today I've decided to build my own.
Can I get some feedback on the code?
What work, what doesn't.
Optimizations.
Caching.
What can I do to make it faster and better?
This would be really helpful for my learning and hopefully for others too.
Heres my plugin:
;(function($) {
$.fn.jTooltip = function(options) {
opts = $.extend({}, $.fn.jTooltip.defaults, options);
return this.each(function() {
var $this = $(this);
var content;
var showTimeout;
$tip = $('#jTooltip');
if($tip.size() == 0){
$('body').append('<div id="jTooltip" style="display:none;position:absolute;"><div></div></div>');
$tipContent = $('#jTooltip div');
}
$this.mouseover(function(event) {
content = $this.attr('title');
$this.attr('title', '');
$tipContent.html(content);
$body.bind('mousemove', function(event){
$tip.css({
top: $(document).scrollTop() + (event.pageY + opts.yOffset),
left: $(document).scrollLeft() + (event.pageX + opts.xOffset)
});
});
showTimeout = setTimeout('$tip.fadeIn(' + opts.fadeTime + ')', opts.delay);
});
$this.mouseout(function(event) {
clearTimeout(showTimeout);
$this.attr('title', content);
$('body').unbind('mousemove');
$tip.hide();
});
});
};
$.fn.jTooltip.defaults = {
delay: 0,
fadeTime: 300,
yOffset: 10,
xOffset: 10
};
})(jQuery);
Updated code
;(function($) {
$.fn.jTooltip = function(options) {
opts = $.extend({}, $.fn.jTooltip.defaults, options);
return this.each(function() {
var $this = $(this);
var showTimeout;
$this.data('title',$this.attr('title'));
$this.removeAttr('title');
$document = $(document);
$body = $('body');
$tip = $('#jTooltip');
$tipContent = $('#jTooltip div');
if($tip.length == 0){
$body.append('<div id="jTooltip" style="display:none;position:absolute;"><div></div></div>');
}
$this.hover(function(event){
$tipContent.html($this.data('title'));
$body.bind('mousemove', function(event){
$tip.css({
top: $document.scrollTop() + (event.pageY + opts.yOffset),
left: $document.scrollLeft() + (event.pageX + opts.xOffset)
});
});
showTimeout = setTimeout(function(){
$tip.fadeIn(opts.fadeTime);
}, opts.delay);
}, function(){
clearTimeout(showTimeout);
$body.unbind('mousemove');
$tip.hide();
});
});
};
$.fn.jTooltip.defaults = {
delay: 0,
fadeTime: 300,
yOffset: 10,
xOffset: 10
};
})(jQuery);
Let me know if you have some more feedback ;)
Use .length rather than .size(). Internally size() calls length so just saves the extra call.
Consider removing the title attribute when you create the tip and storing the tip on the element using .data('tip', title). This will avoid the need for you to constantly blank the title and then add it back again.
Create a function for the work you do inside the setTimeout. Implied eval is considered bad which is what happends when you pass a string to setTimeout/Interval.
window.setTimeout( yourFadeTipFunc , opts.fadeTime);
Cache the $(document) in a var rather than calling it twice.
You could chain the mouseout to the mouseover.
Other than that it is a really good, clean first effort.
Can't say there's anything horribly wrong (others correct me if I'm wrong) but if I were to nitpick I would say use this:
$this.removeAttr('title'); //slightly more readable
instead of this:
$this.attr('title', '');
I just think it's prettier to call removeAttr instead of setting the attribute to the empty string - also, it allows other code to conditionally check for the existence of that attribute, rather than testing it's currently set value against the empty string.

Categories