diff options
author | Trent Richardson <trentdrichardson@gmail.com> | 2014-10-13 13:06:36 -0400 |
---|---|---|
committer | Trent Richardson <trentdrichardson@gmail.com> | 2014-10-13 13:06:36 -0400 |
commit | 6dbe11def320866a8ed5cf7b3f56191483e6b337 (patch) | |
tree | e92f0e54e0829029fd41bad12eb71f054336fe12 | |
parent | 170e1cccf782bd20b1db64f9cf8588bfaa004d1f (diff) | |
download | jQuery-Impromptu-6dbe11def320866a8ed5cf7b3f56191483e6b337.zip jQuery-Impromptu-6dbe11def320866a8ed5cf7b3f56191483e6b337.tar.gz jQuery-Impromptu-6dbe11def320866a8ed5cf7b3f56191483e6b337.tar.bz2 |
Clean up source
-rw-r--r-- | dist/jquery-impromptu.js | 269 | ||||
-rw-r--r-- | dist/jquery-impromptu.min.js | 2 | ||||
-rw-r--r-- | src/jquery-impromptu.js | 401 | ||||
-rw-r--r-- | test/jquery-impromptu_spec.js | 478 |
4 files changed, 148 insertions, 1002 deletions
diff --git a/dist/jquery-impromptu.js b/dist/jquery-impromptu.js index b81f760..4d9076d 100644 --- a/dist/jquery-impromptu.js +++ b/dist/jquery-impromptu.js @@ -11,32 +11,32 @@ "use strict";
/**
- * setDefaults - Sets the default options
+ * Class constructor
* @param message String/Object - String of html or Object of states
* @param options Object - Options to set the prompt
* @return jQuery - container with overlay and prompt
*/
- $.prompt = function(message, options) {
+ var imp = function(message, options) {
// only for backwards compat, to be removed in future version
if(options !== undefined && options.classes !== undefined && typeof options.classes === 'string'){
options = { box: options.classes };
}
- $.prompt.options = $.extend({},$.prompt.defaults,options);
- $.prompt.currentPrefix = $.prompt.options.prefix;
+ imp.options = $.extend({},imp.defaults,options);
+ imp.currentPrefix = imp.options.prefix;
// Be sure any previous timeouts are destroyed
- if($.prompt.timeout){
- clearTimeout($.prompt.timeout);
+ if(imp.timeout){
+ clearTimeout(imp.timeout);
}
- $.prompt.timeout = false;
+ imp.timeout = false;
- var opts = $.prompt.options,
+ var opts = imp.options,
$body = $(document.body),
$window = $(window);
//build the box and fade
- var msgbox = '<div class="'+ $.prompt.options.prefix +'box '+ opts.classes.box +'">';
+ var msgbox = '<div class="'+ imp.options.prefix +'box '+ opts.classes.box +'">';
if(opts.useiframe && ($('object, applet').length > 0)) {
msgbox += '<iframe src="javascript:false;" style="display:block;position:absolute;z-index:-1;" class="'+ opts.prefix +'fade '+ opts.classes.fade +'"></iframe>';
} else {
@@ -50,9 +50,9 @@ '</div>'+
'</div>';
- $.prompt.jqib = $(msgbox).appendTo($body);
- $.prompt.jqi = $.prompt.jqib.children('.'+ opts.prefix);//.data('jqi',opts);
- $.prompt.jqif = $.prompt.jqib.children('.'+ opts.prefix +'fade');
+ imp.jqib = $(msgbox).appendTo($body);
+ imp.jqi = imp.jqib.children('.'+ opts.prefix);//.data('jqi',opts);
+ imp.jqif = imp.jqib.children('.'+ opts.prefix +'fade');
//if a string was passed, convert to a single state
if(message.constructor === String){
@@ -70,22 +70,22 @@ }
//build the states
- $.prompt.options.states = {};
+ imp.options.states = {};
var k,v;
for(k in message){
- v = $.extend({},$.prompt.defaults.state,{name:k},message[k]);
- $.prompt.addState(v.name, v);
+ v = $.extend({},imp.defaults.state,{name:k},message[k]);
+ imp.addState(v.name, v);
- if($.prompt.currentStateName === ''){
- $.prompt.currentStateName = v.name;
+ if(imp.currentStateName === ''){
+ imp.currentStateName = v.name;
}
}
//Events
- $.prompt.jqi.on('click', '.'+ opts.prefix +'buttons button', function(e){
+ imp.jqi.on('click', '.'+ opts.prefix +'buttons button', function(e){
var $t = $(this),
$state = $t.parents('.'+ opts.prefix +'state'),
- stateobj = $.prompt.options.states[$state.data('jqi-name')],
+ stateobj = imp.options.states[$state.data('jqi-name')],
msg = $state.children('.'+ opts.prefix +'message'),
clicked = stateobj.buttons[$t.text()] || stateobj.buttons[$t.html()],
forminputs = {};
@@ -100,7 +100,7 @@ }
//collect all form element values from all states.
- $.each($.prompt.jqi.children('form').serializeArray(),function(i,obj){
+ $.each(imp.jqi.children('form').serializeArray(),function(i,obj){
if (forminputs[obj.name] === undefined) {
forminputs[obj.name] = obj.value;
} else if (typeof forminputs[obj.name] === Array || typeof forminputs[obj.name] === 'object') {
@@ -117,7 +117,7 @@ $state.trigger(promptsubmite, [clicked, msg, forminputs]);
if(!promptsubmite.isDefaultPrevented()){
- $.prompt.close(true, clicked,msg,forminputs);
+ imp.close(true, clicked,msg,forminputs);
}
});
@@ -125,23 +125,23 @@ var fadeClicked = function(){
if(opts.persistent){
var offset = (opts.top.toString().indexOf('%') >= 0? ($window.height()*(parseInt(opts.top,10)/100)) : parseInt(opts.top,10)),
- top = parseInt($.prompt.jqi.css('top').replace('px',''),10) - offset;
+ top = parseInt(imp.jqi.css('top').replace('px',''),10) - offset;
//$window.scrollTop(top);
$('html,body').animate({ scrollTop: top }, 'fast', function(){
var i = 0;
- $.prompt.jqib.addClass(opts.prefix +'warning');
+ imp.jqib.addClass(opts.prefix +'warning');
var intervalid = setInterval(function(){
- $.prompt.jqib.toggleClass(opts.prefix +'warning');
+ imp.jqib.toggleClass(opts.prefix +'warning');
if(i++ > 1){
clearInterval(intervalid);
- $.prompt.jqib.removeClass(opts.prefix +'warning');
+ imp.jqib.removeClass(opts.prefix +'warning');
}
}, 100);
});
}
else {
- $.prompt.close(true);
+ imp.close(true);
}
};
@@ -156,7 +156,7 @@ //enter key pressed trigger the default button if its not on it, ignore if it is a textarea
if(key === 13){
- var $defBtn = $.prompt.getCurrentState().find('.'+ opts.prefix +'defaultbutton');
+ var $defBtn = imp.getCurrentState().find('.'+ opts.prefix +'defaultbutton');
var $tgt = $(e.target);
if($tgt.is('textarea,.'+opts.prefix+'button') === false && $defBtn.length > 0){
@@ -167,7 +167,7 @@ //constrain tabs, tabs should iterate through the state and not leave
if (key === 9){
- var $inputels = $('input,select,textarea,button',$.prompt.getCurrentState());
+ var $inputels = $('input,select,textarea,button',imp.getCurrentState());
var fwd = !e.shiftKey && e.target === $inputels[$inputels.length-1];
var back = e.shiftKey && e.target === $inputels[0];
if (fwd || back) {
@@ -186,37 +186,37 @@ }
};
- $.prompt.position();
- $.prompt.style();
+ imp.position();
+ imp.style();
- $.prompt.jqif.click(fadeClicked);
- $window.resize({animate:false}, $.prompt.position);
- $.prompt.jqi.find('.'+ opts.prefix +'close').click($.prompt.close);
- $.prompt.jqib.on("keydown",keyDownEventHandler)
+ imp.jqif.click(fadeClicked);
+ $window.resize({animate:false}, imp.position);
+ imp.jqi.find('.'+ opts.prefix +'close').click(imp.close);
+ imp.jqib.on("keydown",keyDownEventHandler)
.on('impromptu:loaded', opts.loaded)
.on('impromptu:close', opts.close)
.on('impromptu:statechanging', opts.statechanging)
.on('impromptu:statechanged', opts.statechanged);
// Show it
- $.prompt.jqif[opts.show](opts.overlayspeed);
- $.prompt.jqi[opts.show](opts.promptspeed, function(){
+ imp.jqif[opts.show](opts.overlayspeed);
+ imp.jqi[opts.show](opts.promptspeed, function(){
- var $firstState = $.prompt.jqi.find('.'+ opts.prefix +'states .'+ opts.prefix +'state').eq(0);
- $.prompt.goToState($firstState.data('jqi-name'));
+ var $firstState = imp.jqi.find('.'+ opts.prefix +'states .'+ opts.prefix +'state').eq(0);
+ imp.goToState($firstState.data('jqi-name'));
- $.prompt.jqib.trigger('impromptu:loaded');
+ imp.jqib.trigger('impromptu:loaded');
});
// Timeout
if(opts.timeout > 0){
- $.prompt.timeout = setTimeout(function(){ $.prompt.close(true); },opts.timeout);
+ imp.timeout = setTimeout(function(){ imp.close(true); },opts.timeout);
}
- return $.prompt.jqib;
+ return imp.jqib;
};
- $.prompt.defaults = {
+ imp.defaults = {
prefix:'jqi',
classes: {
box: '',
@@ -285,21 +285,21 @@ * currentPrefix String - At any time this show be the prefix
* of the current prompt ex: "jqi"
*/
- $.prompt.currentPrefix = $.prompt.defaults.prefix;
+ imp.currentPrefix = imp.defaults.prefix;
/**
* currentStateName String - At any time this is the current state
* of the current prompt ex: "state0"
*/
- $.prompt.currentStateName = "";
+ imp.currentStateName = "";
/**
* setDefaults - Sets the default options
* @param o Object - Options to set as defaults
* @return void
*/
- $.prompt.setDefaults = function(o) {
- $.prompt.defaults = $.extend({}, $.prompt.defaults, o);
+ imp.setDefaults = function(o) {
+ imp.defaults = $.extend({}, imp.defaults, o);
};
/**
@@ -307,33 +307,33 @@ * @param o Object - Options to set as defaults
* @return void
*/
- $.prompt.setStateDefaults = function(o) {
- $.prompt.defaults.state = $.extend({}, $.prompt.defaults.state, o);
+ imp.setStateDefaults = function(o) {
+ imp.defaults.state = $.extend({}, imp.defaults.state, o);
};
/**
* position - Repositions the prompt (Used internally)
* @return void
*/
- $.prompt.position = function(e){
+ imp.position = function(e){
var restoreFx = $.fx.off,
- $state = $.prompt.getCurrentState(),
- stateObj = $.prompt.options.states[$state.data('jqi-name')],
+ $state = imp.getCurrentState(),
+ stateObj = imp.options.states[$state.data('jqi-name')],
pos = stateObj? stateObj.position : undefined,
$window = $(window),
bodyHeight = document.body.scrollHeight, //$(document.body).outerHeight(true),
windowHeight = $(window).height(),
documentHeight = $(document).height(),
height = bodyHeight > windowHeight ? bodyHeight : windowHeight,
- top = parseInt($window.scrollTop(),10) + ($.prompt.options.top.toString().indexOf('%') >= 0?
- (windowHeight*(parseInt($.prompt.options.top,10)/100)) : parseInt($.prompt.options.top,10));
+ top = parseInt($window.scrollTop(),10) + (imp.options.top.toString().indexOf('%') >= 0?
+ (windowHeight*(parseInt(imp.options.top,10)/100)) : parseInt(imp.options.top,10));
// when resizing the window turn off animation
if(e !== undefined && e.data.animate === false){
$.fx.off = true;
}
- $.prompt.jqib.css({
+ imp.jqib.css({
position: "absolute",
height: height,
width: "100%",
@@ -342,7 +342,7 @@ right: 0,
bottom: 0
});
- $.prompt.jqif.css({
+ imp.jqif.css({
position: "fixed",
height: height,
width: "100%",
@@ -357,26 +357,26 @@ var offset = $(pos.container).offset();
if($.isPlainObject(offset) && offset.top !== undefined){
- $.prompt.jqi.css({
+ imp.jqi.css({
position: "absolute"
});
- $.prompt.jqi.animate({
+ imp.jqi.animate({
top: offset.top + pos.y,
left: offset.left + pos.x,
marginLeft: 0,
width: (pos.width !== undefined)? pos.width : null
});
- top = (offset.top + pos.y) - ($.prompt.options.top.toString().indexOf('%') >= 0? (windowHeight*(parseInt($.prompt.options.top,10)/100)) : parseInt($.prompt.options.top,10));
+ top = (offset.top + pos.y) - (imp.options.top.toString().indexOf('%') >= 0? (windowHeight*(parseInt(imp.options.top,10)/100)) : parseInt(imp.options.top,10));
$('html,body').animate({ scrollTop: top }, 'slow', 'swing', function(){});
}
}
// custom state width animation
else if(pos && pos.width){
- $.prompt.jqi.css({
+ imp.jqi.css({
position: "absolute",
left: '50%'
});
- $.prompt.jqi.animate({
+ imp.jqi.animate({
top: pos.y || top,
left: pos.x || '50%',
marginLeft: ((pos.width/2)*-1),
@@ -385,11 +385,11 @@ }
// standard prompt positioning
else{
- $.prompt.jqi.css({
+ imp.jqi.css({
position: "absolute",
top: top,
left: '50%',//$window.width()/2,
- marginLeft: (($.prompt.jqi.outerWidth(false)/2)*-1)
+ marginLeft: ((imp.jqi.outerWidth(false)/2)*-1)
});
}
@@ -403,18 +403,18 @@ * style - Restyles the prompt (Used internally)
* @return void
*/
- $.prompt.style = function(){
- $.prompt.jqif.css({
- zIndex: $.prompt.options.zIndex,
+ imp.style = function(){
+ imp.jqif.css({
+ zIndex: imp.options.zIndex,
display: "none",
- opacity: $.prompt.options.opacity
+ opacity: imp.options.opacity
});
- $.prompt.jqi.css({
- zIndex: $.prompt.options.zIndex+1,
+ imp.jqi.css({
+ zIndex: imp.options.zIndex+1,
display: "none"
});
- $.prompt.jqib.css({
- zIndex: $.prompt.options.zIndex
+ imp.jqib.css({
+ zIndex: imp.options.zIndex
});
};
@@ -422,8 +422,8 @@ * get - Get the prompt
* @return jQuery - the prompt
*/
- $.prompt.get = function(state) {
- return $('.'+ $.prompt.currentPrefix);
+ imp.get = function(state) {
+ return $('.'+ imp.currentPrefix);
};
/**
@@ -433,17 +433,17 @@ * @param afterState String - selector of the state to insert after
* @return jQuery - the newly created state
*/
- $.prompt.addState = function(statename, stateobj, afterState) {
+ imp.addState = function(statename, stateobj, afterState) {
var state = "",
$state = null,
arrow = "",
title = "",
- opts = $.prompt.options,
- $jqistates = $('.'+ $.prompt.currentPrefix +'states'),
+ opts = imp.options,
+ $jqistates = $('.'+ imp.currentPrefix +'states'),
buttons = [],
showHtml,defbtn,k,v,l,i=0;
- stateobj = $.extend({},$.prompt.defaults.state, {name:statename}, stateobj);
+ stateobj = $.extend({},imp.defaults.state, {name:statename}, stateobj);
if(stateobj.position.arrow !== null){
arrow = '<div class="'+ opts.prefix + 'arrow '+ opts.prefix + 'arrow'+ stateobj.position.arrow +'"></div>';
@@ -477,9 +477,9 @@ // iterate over each button and create them
for(i=0, l=buttons.length; i<l; i++){
v = buttons[i],
- defbtn = stateobj.focus === i || (isNaN(stateobj.focus) && stateobj.defaultButton === i) ? ($.prompt.currentPrefix + 'defaultbutton ' + opts.classes.defaultButton) : '';
+ defbtn = stateobj.focus === i || (isNaN(stateobj.focus) && stateobj.defaultButton === i) ? (imp.currentPrefix + 'defaultbutton ' + opts.classes.defaultButton) : '';
- state += '<button class="'+ opts.classes.button +' '+ $.prompt.currentPrefix + 'button '+ defbtn;
+ state += '<button class="'+ opts.classes.button +' '+ imp.currentPrefix + 'button '+ defbtn;
if(typeof v.classes !== "undefined"){
state += ' '+ ($.isArray(v.classes)? v.classes.join(' ') : v.classes) + ' ';
@@ -495,13 +495,13 @@ $state.on('impromptu:submit', stateobj.submit);
if(afterState !== undefined){
- $jqistates.find('#'+ $.prompt.currentPrefix +'state_'+ afterState).after($state);
+ $jqistates.find('#'+ imp.currentPrefix +'state_'+ afterState).after($state);
}
else{
$jqistates.append($state);
}
- $.prompt.options.states[statename] = stateobj;
+ imp.options.states[statename] = stateobj;
return $state;
};
@@ -512,8 +512,8 @@ * @param newState String - Name of the state to transition to
* @return Boolean - returns true on success, false on failure
*/
- $.prompt.removeState = function(state, newState) {
- var $state = $.prompt.getState(state),
+ imp.removeState = function(state, newState) {
+ var $state = imp.getState(state),
rm = function(){ $state.remove(); };
if($state.length === 0){
@@ -522,17 +522,17 @@ // transition away from it before deleting
if($state.css('display') !== 'none'){
- if(newState !== undefined && $.prompt.getState(newState).length > 0){
- $.prompt.goToState(newState, false, rm);
+ if(newState !== undefined && imp.getState(newState).length > 0){
+ imp.goToState(newState, false, rm);
}
else if($state.next().length > 0){
- $.prompt.nextState(rm);
+ imp.nextState(rm);
}
else if($state.prev().length > 0){
- $.prompt.prevState(rm);
+ imp.prevState(rm);
}
else{
- $.prompt.close();
+ imp.close();
}
}
else{
@@ -547,27 +547,27 @@ * @param state String - Name of the state
* @return jQuery - the state
*/
- $.prompt.getState = function(state) {
- return $('#'+ $.prompt.currentPrefix +'state_'+ state);
+ imp.getState = function(state) {
+ return $('#'+ imp.currentPrefix +'state_'+ state);
};
- $.prompt.getStateContent = function(state) {
- return $.prompt.getState(state);
+ imp.getStateContent = function(state) {
+ return imp.getState(state);
};
/**
* getCurrentState - Get the current visible state
* @return jQuery - the current visible state
*/
- $.prompt.getCurrentState = function() {
- return $.prompt.getState($.prompt.getCurrentStateName());
+ imp.getCurrentState = function() {
+ return imp.getState(imp.getCurrentStateName());
};
/**
* getCurrentStateName - Get the name of the current visible state
* @return String - the current visible state's name
*/
- $.prompt.getCurrentStateName = function() {
- return $.prompt.currentStateName;
+ imp.getCurrentStateName = function() {
+ return imp.currentStateName;
};
/**
@@ -577,13 +577,13 @@ * @param callback Function - called when the transition is complete
* @return jQuery - the newly active state
*/
- $.prompt.goToState = function(state, subState, callback) {
- var $jqi = $.prompt.get(),
- jqiopts = $.prompt.options,
- $state = $.prompt.getState(state),
+ imp.goToState = function(state, subState, callback) {
+ var $jqi = imp.get(),
+ jqiopts = imp.options,
+ $state = imp.getState(state),
stateobj = jqiopts.states[$state.data('jqi-name')],
promptstatechanginge = new $.Event('impromptu:statechanging'),
- opts = $.prompt.options;
+ opts = imp.options;
if(stateobj !== undefined){
@@ -599,30 +599,30 @@ subState = false;
}
- $.prompt.jqib.trigger(promptstatechanginge, [$.prompt.getCurrentStateName(), state]);
+ imp.jqib.trigger(promptstatechanginge, [imp.getCurrentStateName(), state]);
if(!promptstatechanginge.isDefaultPrevented() && $state.length > 0){
- $.prompt.jqi.find('.'+ $.prompt.currentPrefix +'parentstate').removeClass($.prompt.currentPrefix +'parentstate');
+ imp.jqi.find('.'+ imp.currentPrefix +'parentstate').removeClass(imp.currentPrefix +'parentstate');
if(subState){ // hide any open substates
// get rid of any substates
- $.prompt.jqi.find('.'+ $.prompt.currentPrefix +'substate').not($state)
+ imp.jqi.find('.'+ imp.currentPrefix +'substate').not($state)
.slideUp(jqiopts.promptspeed)
- .removeClass('.'+ $.prompt.currentPrefix +'substate')
- .find('.'+ $.prompt.currentPrefix +'arrow').hide();
+ .removeClass('.'+ imp.currentPrefix +'substate')
+ .find('.'+ imp.currentPrefix +'arrow').hide();
// add parent state class so it can be visible, but blocked
- $.prompt.jqi.find('.'+ $.prompt.currentPrefix +'state:visible').addClass($.prompt.currentPrefix +'parentstate');
+ imp.jqi.find('.'+ imp.currentPrefix +'state:visible').addClass(imp.currentPrefix +'parentstate');
// add substate class so we know it will be smaller
- $state.addClass($.prompt.currentPrefix +'substate');
+ $state.addClass(imp.currentPrefix +'substate');
}
else{ // hide any open states
- $.prompt.jqi.find('.'+ $.prompt.currentPrefix +'state').not($state)
+ imp.jqi.find('.'+ imp.currentPrefix +'state').not($state)
.slideUp(jqiopts.promptspeed)
- .find('.'+ $.prompt.currentPrefix +'arrow').hide();
+ .find('.'+ imp.currentPrefix +'arrow').hide();
}
- $.prompt.currentStateName = stateobj.name;
+ imp.currentStateName = stateobj.name;
$state.slideDown(jqiopts.promptspeed,function(){
var $t = $(this);
@@ -632,21 +632,21 @@ $t.find(stateobj.focus).eq(0).focus();
}
else{
- $t.find('.'+ $.prompt.currentPrefix +'defaultbutton').focus();
+ $t.find('.'+ imp.currentPrefix +'defaultbutton').focus();
}
- $t.find('.'+ $.prompt.currentPrefix +'arrow').show(jqiopts.promptspeed);
+ $t.find('.'+ imp.currentPrefix +'arrow').show(jqiopts.promptspeed);
if (typeof callback === 'function'){
- $.prompt.jqib.on('impromptu:statechanged', callback);
+ imp.jqib.on('impromptu:statechanged', callback);
}
- $.prompt.jqib.trigger('impromptu:statechanged', [state]);
+ imp.jqib.trigger('impromptu:statechanged', [state]);
if (typeof callback === 'function'){
- $.prompt.jqib.off('impromptu:statechanged', callback);
+ imp.jqib.off('impromptu:statechanged', callback);
}
});
if(!subState){
- $.prompt.position();
+ imp.position();
}
} // end isDefaultPrevented()
}// end stateobj !== undefined
@@ -659,10 +659,10 @@ * @param callback Function - called when the transition is complete
* @return jQuery - the newly active state
*/
- $.prompt.nextState = function(callback) {
- var $next = $('#'+ $.prompt.currentPrefix +'state_'+ $.prompt.getCurrentStateName()).next();
+ imp.nextState = function(callback) {
+ var $next = $('#'+ imp.currentPrefix +'state_'+ imp.getCurrentStateName()).next();
if($next.length > 0){
- $.prompt.goToState( $next.attr('id').replace($.prompt.currentPrefix +'state_',''), callback );
+ imp.goToState( $next.attr('id').replace(imp.currentPrefix +'state_',''), callback );
}
return $next;
};
@@ -672,10 +672,10 @@ * @param callback Function - called when the transition is complete
* @return jQuery - the newly active state
*/
- $.prompt.prevState = function(callback) {
- var $prev = $('#'+ $.prompt.currentPrefix +'state_'+ $.prompt.getCurrentStateName()).prev();
+ imp.prevState = function(callback) {
+ var $prev = $('#'+ imp.currentPrefix +'state_'+ imp.getCurrentStateName()).prev();
if($prev.length > 0){
- $.prompt.goToState( $prev.attr('id').replace($.prompt.currentPrefix +'state_',''), callback );
+ imp.goToState( $prev.attr('id').replace(imp.currentPrefix +'state_',''), callback );
}
return $prev;
};
@@ -688,23 +688,23 @@ * @param forvals Object - key/value pairs of all form field names and values (only used internally)
* @return jQuery - the newly active state
*/
- $.prompt.close = function(callCallback, clicked, msg, formvals){
- if($.prompt.timeout){
- clearTimeout($.prompt.timeout);
- $.prompt.timeout = false;
+ imp.close = function(callCallback, clicked, msg, formvals){
+ if(imp.timeout){
+ clearTimeout(imp.timeout);
+ imp.timeout = false;
}
- if($.prompt.jqib){
- $.prompt.jqib.fadeOut('fast',function(){
+ if(imp.jqib){
+ imp.jqib.fadeOut('fast',function(){
- $.prompt.jqib.trigger('impromptu:close', [clicked,msg,formvals]);
+ imp.jqib.trigger('impromptu:close', [clicked,msg,formvals]);
- $.prompt.jqib.remove();
+ imp.jqib.remove();
- $(window).off('resize',$.prompt.position);
+ $(window).off('resize',imp.position);
});
}
- $.prompt.currentStateName = "";
+ imp.currentStateName = "";
};
/**
@@ -719,7 +719,10 @@ options.withDataAndEvents = false;
}
- $.prompt($(this).clone(options.withDataAndEvents).html(),options);
+ imp($(this).clone(options.withDataAndEvents).html(),options);
};
+ $.prompt = imp;
+ window.Impromptu = imp;
+
}));
diff --git a/dist/jquery-impromptu.min.js b/dist/jquery-impromptu.min.js index 3f2fd6c..37b66a0 100644 --- a/dist/jquery-impromptu.min.js +++ b/dist/jquery-impromptu.min.js @@ -1,4 +1,4 @@ /*! jQuery-Impromptu - v5.2.6 - 2014-09-01 * http://trentrichardson.com/Impromptu * Copyright (c) 2014 Trent Richardson; Licensed MIT */ -(function(t,e){"function"==typeof define&&define.amd?define(["jquery"],e):e(t.jQuery)})(this,function(t){"use strict";t.prompt=function(e,o){void 0!==o&&void 0!==o.classes&&"string"==typeof o.classes&&(o={box:o.classes}),t.prompt.options=t.extend({},t.prompt.defaults,o),t.prompt.currentPrefix=t.prompt.options.prefix,t.prompt.timeout&&clearTimeout(t.prompt.timeout),t.prompt.timeout=!1;var p=t.prompt.options,r=t(document.body),i=t(window),n='<div class="'+t.prompt.options.prefix+"box "+p.classes.box+'">';n+=p.useiframe&&t("object, applet").length>0?'<iframe src="javascript:false;" style="display:block;position:absolute;z-index:-1;" class="'+p.prefix+"fade "+p.classes.fade+'"></iframe>':'<div class="'+p.prefix+"fade "+p.classes.fade+'"></div>',n+='<div class="'+p.prefix+" "+p.classes.prompt+'">'+'<form action="javascript:false;" onsubmit="return false;" class="'+p.prefix+"form "+p.classes.form+'">'+'<div class="'+p.prefix+"close "+p.classes.close+'">'+p.closeText+"</div>"+'<div class="'+p.prefix+'states"></div>'+"</form>"+"</div>"+"</div>",t.prompt.jqib=t(n).appendTo(r),t.prompt.jqi=t.prompt.jqib.children("."+p.prefix),t.prompt.jqif=t.prompt.jqib.children("."+p.prefix+"fade"),e.constructor===String&&(e={state0:{title:p.title,html:e,buttons:p.buttons,position:p.position,focus:p.focus,defaultButton:p.defaultButton,submit:p.submit}}),t.prompt.options.states={};var s,a;for(s in e)a=t.extend({},t.prompt.defaults.state,{name:s},e[s]),t.prompt.addState(a.name,a),""===t.prompt.currentStateName&&(t.prompt.currentStateName=a.name);t.prompt.jqi.on("click","."+p.prefix+"buttons button",function(){var e=t(this),o=e.parents("."+p.prefix+"state"),r=t.prompt.options.states[o.data("jqi-name")],i=o.children("."+p.prefix+"message"),n=r.buttons[e.text()]||r.buttons[e.html()],s={};if(void 0===n)for(var a in r.buttons)(r.buttons[a].title===e.text()||r.buttons[a].title===e.html())&&(n=r.buttons[a].value);t.each(t.prompt.jqi.children("form").serializeArray(),function(t,e){void 0===s[e.name]?s[e.name]=e.value:typeof s[e.name]===Array||"object"==typeof s[e.name]?s[e.name].push(e.value):s[e.name]=[s[e.name],e.value]});var m=new t.Event("impromptu:submit");m.stateName=r.name,m.state=o,o.trigger(m,[n,i,s]),m.isDefaultPrevented()||t.prompt.close(!0,n,i,s)});var m=function(){if(p.persistent){var e=(""+p.top).indexOf("%")>=0?i.height()*(parseInt(p.top,10)/100):parseInt(p.top,10),o=parseInt(t.prompt.jqi.css("top").replace("px",""),10)-e;t("html,body").animate({scrollTop:o},"fast",function(){var e=0;t.prompt.jqib.addClass(p.prefix+"warning");var o=setInterval(function(){t.prompt.jqib.toggleClass(p.prefix+"warning"),e++>1&&(clearInterval(o),t.prompt.jqib.removeClass(p.prefix+"warning"))},100)})}else t.prompt.close(!0)},u=function(e){var o=window.event?event.keyCode:e.keyCode;if(27===o&&m(),13===o){var r=t.prompt.getCurrentState().find("."+p.prefix+"defaultbutton"),i=t(e.target);i.is("textarea,."+p.prefix+"button")===!1&&r.length>0&&(e.preventDefault(),r.click())}if(9===o){var n=t("input,select,textarea,button",t.prompt.getCurrentState()),s=!e.shiftKey&&e.target===n[n.length-1],a=e.shiftKey&&e.target===n[0];if(s||a)return setTimeout(function(){if(n){var t=n[a===!0?n.length-1:0];t&&t.focus()}},10),!1}};return t.prompt.position(),t.prompt.style(),t.prompt.jqif.click(m),i.resize({animate:!1},t.prompt.position),t.prompt.jqi.find("."+p.prefix+"close").click(t.prompt.close),t.prompt.jqib.on("keydown",u).on("impromptu:loaded",p.loaded).on("impromptu:close",p.close).on("impromptu:statechanging",p.statechanging).on("impromptu:statechanged",p.statechanged),t.prompt.jqif[p.show](p.overlayspeed),t.prompt.jqi[p.show](p.promptspeed,function(){var e=t.prompt.jqi.find("."+p.prefix+"states ."+p.prefix+"state").eq(0);t.prompt.goToState(e.data("jqi-name")),t.prompt.jqib.trigger("impromptu:loaded")}),p.timeout>0&&(t.prompt.timeout=setTimeout(function(){t.prompt.close(!0)},p.timeout)),t.prompt.jqib},t.prompt.defaults={prefix:"jqi",classes:{box:"",fade:"",prompt:"",form:"",close:"",title:"",message:"",buttons:"",button:"",defaultButton:""},title:"",closeText:"×",buttons:{Ok:!0},loaded:function(){},submit:function(){},close:function(){},statechanging:function(){},statechanged:function(){},opacity:.6,zIndex:999,overlayspeed:"slow",promptspeed:"fast",show:"fadeIn",focus:0,defaultButton:0,useiframe:!1,top:"15%",position:{container:null,x:null,y:null,arrow:null,width:null},persistent:!0,timeout:0,states:{},state:{name:null,title:"",html:"",buttons:{Ok:!0},focus:0,defaultButton:0,position:{container:null,x:null,y:null,arrow:null,width:null},submit:function(){return!0}}},t.prompt.currentPrefix=t.prompt.defaults.prefix,t.prompt.currentStateName="",t.prompt.setDefaults=function(e){t.prompt.defaults=t.extend({},t.prompt.defaults,e)},t.prompt.setStateDefaults=function(e){t.prompt.defaults.state=t.extend({},t.prompt.defaults.state,e)},t.prompt.position=function(e){var o=t.fx.off,p=t.prompt.getCurrentState(),r=t.prompt.options.states[p.data("jqi-name")],i=r?r.position:void 0,n=t(window),s=document.body.scrollHeight,a=t(window).height(),m=(t(document).height(),s>a?s:a),u=parseInt(n.scrollTop(),10)+((""+t.prompt.options.top).indexOf("%")>=0?a*(parseInt(t.prompt.options.top,10)/100):parseInt(t.prompt.options.top,10));if(void 0!==e&&e.data.animate===!1&&(t.fx.off=!0),t.prompt.jqib.css({position:"absolute",height:m,width:"100%",top:0,left:0,right:0,bottom:0}),t.prompt.jqif.css({position:"fixed",height:m,width:"100%",top:0,left:0,right:0,bottom:0}),i&&i.container){var f=t(i.container).offset();t.isPlainObject(f)&&void 0!==f.top&&(t.prompt.jqi.css({position:"absolute"}),t.prompt.jqi.animate({top:f.top+i.y,left:f.left+i.x,marginLeft:0,width:void 0!==i.width?i.width:null}),u=f.top+i.y-((""+t.prompt.options.top).indexOf("%")>=0?a*(parseInt(t.prompt.options.top,10)/100):parseInt(t.prompt.options.top,10)),t("html,body").animate({scrollTop:u},"slow","swing",function(){}))}else i&&i.width?(t.prompt.jqi.css({position:"absolute",left:"50%"}),t.prompt.jqi.animate({top:i.y||u,left:i.x||"50%",marginLeft:-1*(i.width/2),width:i.width})):t.prompt.jqi.css({position:"absolute",top:u,left:"50%",marginLeft:-1*(t.prompt.jqi.outerWidth(!1)/2)});void 0!==e&&e.data.animate===!1&&(t.fx.off=o)},t.prompt.style=function(){t.prompt.jqif.css({zIndex:t.prompt.options.zIndex,display:"none",opacity:t.prompt.options.opacity}),t.prompt.jqi.css({zIndex:t.prompt.options.zIndex+1,display:"none"}),t.prompt.jqib.css({zIndex:t.prompt.options.zIndex})},t.prompt.get=function(){return t("."+t.prompt.currentPrefix)},t.prompt.addState=function(e,o,p){var r,i,n,s,a,m="",u=null,f="",l="",c=t.prompt.options,d=t("."+t.prompt.currentPrefix+"states"),x=[],v=0;if(o=t.extend({},t.prompt.defaults.state,{name:e},o),null!==o.position.arrow&&(f='<div class="'+c.prefix+"arrow "+c.prefix+"arrow"+o.position.arrow+'"></div>'),o.title&&""!==o.title&&(l='<div class="lead '+c.prefix+"title "+c.classes.title+'">'+o.title+"</div>"),r=o.html,"function"==typeof o.html&&(r="Error: html function must return text"),m+='<div id="'+c.prefix+"state_"+e+'" class="'+c.prefix+'state" data-jqi-name="'+e+'" style="display:none;">'+f+l+'<div class="'+c.prefix+"message "+c.classes.message+'">'+r+"</div>"+'<div class="'+c.prefix+"buttons "+c.classes.buttons+'"'+(t.isEmptyObject(o.buttons)?'style="display:none;"':"")+">",t.isArray(o.buttons))x=o.buttons;else if(t.isPlainObject(o.buttons))for(n in o.buttons)o.buttons.hasOwnProperty(n)&&x.push({title:n,value:o.buttons[n]});for(v=0,a=x.length;a>v;v++)s=x[v],i=o.focus===v||isNaN(o.focus)&&o.defaultButton===v?t.prompt.currentPrefix+"defaultbutton "+c.classes.defaultButton:"",m+='<button class="'+c.classes.button+" "+t.prompt.currentPrefix+"button "+i,s.classes!==void 0&&(m+=" "+(t.isArray(s.classes)?s.classes.join(" "):s.classes)+" "),m+='" name="'+c.prefix+"_"+e+"_button"+s.title.replace(/[^a-z0-9]+/gi,"")+'" id="'+c.prefix+"_"+e+"_button"+s.title.replace(/[^a-z0-9]+/gi,"")+'" value="'+s.value+'">'+s.title+"</button>";return m+="</div></div>",u=t(m),u.on("impromptu:submit",o.submit),void 0!==p?d.find("#"+t.prompt.currentPrefix+"state_"+p).after(u):d.append(u),t.prompt.options.states[e]=o,u},t.prompt.removeState=function(e,o){var p=t.prompt.getState(e),r=function(){p.remove()};return 0===p.length?!1:("none"!==p.css("display")?void 0!==o&&t.prompt.getState(o).length>0?t.prompt.goToState(o,!1,r):p.next().length>0?t.prompt.nextState(r):p.prev().length>0?t.prompt.prevState(r):t.prompt.close():p.slideUp("slow",r),!0)},t.prompt.getState=function(e){return t("#"+t.prompt.currentPrefix+"state_"+e)},t.prompt.getStateContent=function(e){return t.prompt.getState(e)},t.prompt.getCurrentState=function(){return t.prompt.getState(t.prompt.getCurrentStateName())},t.prompt.getCurrentStateName=function(){return t.prompt.currentStateName},t.prompt.goToState=function(e,o,p){var r=(t.prompt.get(),t.prompt.options),i=t.prompt.getState(e),n=r.states[i.data("jqi-name")],s=new t.Event("impromptu:statechanging"),a=t.prompt.options;if(void 0!==n){if("function"==typeof n.html){var m=n.html;i.find("."+a.prefix+"message ").html(m())}"function"==typeof o&&(p=o,o=!1),t.prompt.jqib.trigger(s,[t.prompt.getCurrentStateName(),e]),!s.isDefaultPrevented()&&i.length>0&&(t.prompt.jqi.find("."+t.prompt.currentPrefix+"parentstate").removeClass(t.prompt.currentPrefix+"parentstate"),o?(t.prompt.jqi.find("."+t.prompt.currentPrefix+"substate").not(i).slideUp(r.promptspeed).removeClass("."+t.prompt.currentPrefix+"substate").find("."+t.prompt.currentPrefix+"arrow").hide(),t.prompt.jqi.find("."+t.prompt.currentPrefix+"state:visible").addClass(t.prompt.currentPrefix+"parentstate"),i.addClass(t.prompt.currentPrefix+"substate")):t.prompt.jqi.find("."+t.prompt.currentPrefix+"state").not(i).slideUp(r.promptspeed).find("."+t.prompt.currentPrefix+"arrow").hide(),t.prompt.currentStateName=n.name,i.slideDown(r.promptspeed,function(){var o=t(this);"string"==typeof n.focus?o.find(n.focus).eq(0).focus():o.find("."+t.prompt.currentPrefix+"defaultbutton").focus(),o.find("."+t.prompt.currentPrefix+"arrow").show(r.promptspeed),"function"==typeof p&&t.prompt.jqib.on("impromptu:statechanged",p),t.prompt.jqib.trigger("impromptu:statechanged",[e]),"function"==typeof p&&t.prompt.jqib.off("impromptu:statechanged",p)}),o||t.prompt.position())}return i},t.prompt.nextState=function(e){var o=t("#"+t.prompt.currentPrefix+"state_"+t.prompt.getCurrentStateName()).next();return o.length>0&&t.prompt.goToState(o.attr("id").replace(t.prompt.currentPrefix+"state_",""),e),o},t.prompt.prevState=function(e){var o=t("#"+t.prompt.currentPrefix+"state_"+t.prompt.getCurrentStateName()).prev();return o.length>0&&t.prompt.goToState(o.attr("id").replace(t.prompt.currentPrefix+"state_",""),e),o},t.prompt.close=function(e,o,p,r){t.prompt.timeout&&(clearTimeout(t.prompt.timeout),t.prompt.timeout=!1),t.prompt.jqib&&t.prompt.jqib.fadeOut("fast",function(){t.prompt.jqib.trigger("impromptu:close",[o,p,r]),t.prompt.jqib.remove(),t(window).off("resize",t.prompt.position)}),t.prompt.currentStateName=""},t.fn.prompt=function(e){void 0===e&&(e={}),void 0===e.withDataAndEvents&&(e.withDataAndEvents=!1),t.prompt(t(this).clone(e.withDataAndEvents).html(),e)}});
\ No newline at end of file +(function(t,e){"function"==typeof define&&define.amd?define(["jquery"],e):e(t.jQuery)})(this,function(t){"use strict";var e=function(i,n){void 0!==n&&void 0!==n.classes&&"string"==typeof n.classes&&(n={box:n.classes}),e.options=t.extend({},e.defaults,n),e.currentPrefix=e.options.prefix,e.timeout&&clearTimeout(e.timeout),e.timeout=!1;var o=e.options,s=t(document.body),a=t(window),r='<div class="'+e.options.prefix+"box "+o.classes.box+'">';r+=o.useiframe&&t("object, applet").length>0?'<iframe src="javascript:false;" style="display:block;position:absolute;z-index:-1;" class="'+o.prefix+"fade "+o.classes.fade+'"></iframe>':'<div class="'+o.prefix+"fade "+o.classes.fade+'"></div>',r+='<div class="'+o.prefix+" "+o.classes.prompt+'">'+'<form action="javascript:false;" onsubmit="return false;" class="'+o.prefix+"form "+o.classes.form+'">'+'<div class="'+o.prefix+"close "+o.classes.close+'">'+o.closeText+"</div>"+'<div class="'+o.prefix+'states"></div>'+"</form>"+"</div>"+"</div>",e.jqib=t(r).appendTo(s),e.jqi=e.jqib.children("."+o.prefix),e.jqif=e.jqib.children("."+o.prefix+"fade"),i.constructor===String&&(i={state0:{title:o.title,html:i,buttons:o.buttons,position:o.position,focus:o.focus,defaultButton:o.defaultButton,submit:o.submit}}),e.options.states={};var u,f;for(u in i)f=t.extend({},e.defaults.state,{name:u},i[u]),e.addState(f.name,f),""===e.currentStateName&&(e.currentStateName=f.name);e.jqi.on("click","."+o.prefix+"buttons button",function(){var i=t(this),n=i.parents("."+o.prefix+"state"),s=e.options.states[n.data("jqi-name")],a=n.children("."+o.prefix+"message"),r=s.buttons[i.text()]||s.buttons[i.html()],u={};if(void 0===r)for(var f in s.buttons)(s.buttons[f].title===i.text()||s.buttons[f].title===i.html())&&(r=s.buttons[f].value);t.each(e.jqi.children("form").serializeArray(),function(t,e){void 0===u[e.name]?u[e.name]=e.value:typeof u[e.name]===Array||"object"==typeof u[e.name]?u[e.name].push(e.value):u[e.name]=[u[e.name],e.value]});var l=new t.Event("impromptu:submit");l.stateName=s.name,l.state=n,n.trigger(l,[r,a,u]),l.isDefaultPrevented()||e.close(!0,r,a,u)});var l=function(){if(o.persistent){var i=(""+o.top).indexOf("%")>=0?a.height()*(parseInt(o.top,10)/100):parseInt(o.top,10),n=parseInt(e.jqi.css("top").replace("px",""),10)-i;t("html,body").animate({scrollTop:n},"fast",function(){var t=0;e.jqib.addClass(o.prefix+"warning");var i=setInterval(function(){e.jqib.toggleClass(o.prefix+"warning"),t++>1&&(clearInterval(i),e.jqib.removeClass(o.prefix+"warning"))},100)})}else e.close(!0)},p=function(i){var n=window.event?event.keyCode:i.keyCode;if(27===n&&l(),13===n){var s=e.getCurrentState().find("."+o.prefix+"defaultbutton"),a=t(i.target);a.is("textarea,."+o.prefix+"button")===!1&&s.length>0&&(i.preventDefault(),s.click())}if(9===n){var r=t("input,select,textarea,button",e.getCurrentState()),u=!i.shiftKey&&i.target===r[r.length-1],f=i.shiftKey&&i.target===r[0];if(u||f)return setTimeout(function(){if(r){var t=r[f===!0?r.length-1:0];t&&t.focus()}},10),!1}};return e.position(),e.style(),e.jqif.click(l),a.resize({animate:!1},e.position),e.jqi.find("."+o.prefix+"close").click(e.close),e.jqib.on("keydown",p).on("impromptu:loaded",o.loaded).on("impromptu:close",o.close).on("impromptu:statechanging",o.statechanging).on("impromptu:statechanged",o.statechanged),e.jqif[o.show](o.overlayspeed),e.jqi[o.show](o.promptspeed,function(){var t=e.jqi.find("."+o.prefix+"states ."+o.prefix+"state").eq(0);e.goToState(t.data("jqi-name")),e.jqib.trigger("impromptu:loaded")}),o.timeout>0&&(e.timeout=setTimeout(function(){e.close(!0)},o.timeout)),e.jqib};e.defaults={prefix:"jqi",classes:{box:"",fade:"",prompt:"",form:"",close:"",title:"",message:"",buttons:"",button:"",defaultButton:""},title:"",closeText:"×",buttons:{Ok:!0},loaded:function(){},submit:function(){},close:function(){},statechanging:function(){},statechanged:function(){},opacity:.6,zIndex:999,overlayspeed:"slow",promptspeed:"fast",show:"fadeIn",focus:0,defaultButton:0,useiframe:!1,top:"15%",position:{container:null,x:null,y:null,arrow:null,width:null},persistent:!0,timeout:0,states:{},state:{name:null,title:"",html:"",buttons:{Ok:!0},focus:0,defaultButton:0,position:{container:null,x:null,y:null,arrow:null,width:null},submit:function(){return!0}}},e.currentPrefix=e.defaults.prefix,e.currentStateName="",e.setDefaults=function(i){e.defaults=t.extend({},e.defaults,i)},e.setStateDefaults=function(i){e.defaults.state=t.extend({},e.defaults.state,i)},e.position=function(i){var n=t.fx.off,o=e.getCurrentState(),s=e.options.states[o.data("jqi-name")],a=s?s.position:void 0,r=t(window),u=document.body.scrollHeight,f=t(window).height(),l=(t(document).height(),u>f?u:f),p=parseInt(r.scrollTop(),10)+((""+e.options.top).indexOf("%")>=0?f*(parseInt(e.options.top,10)/100):parseInt(e.options.top,10));if(void 0!==i&&i.data.animate===!1&&(t.fx.off=!0),e.jqib.css({position:"absolute",height:l,width:"100%",top:0,left:0,right:0,bottom:0}),e.jqif.css({position:"fixed",height:l,width:"100%",top:0,left:0,right:0,bottom:0}),a&&a.container){var c=t(a.container).offset();t.isPlainObject(c)&&void 0!==c.top&&(e.jqi.css({position:"absolute"}),e.jqi.animate({top:c.top+a.y,left:c.left+a.x,marginLeft:0,width:void 0!==a.width?a.width:null}),p=c.top+a.y-((""+e.options.top).indexOf("%")>=0?f*(parseInt(e.options.top,10)/100):parseInt(e.options.top,10)),t("html,body").animate({scrollTop:p},"slow","swing",function(){}))}else a&&a.width?(e.jqi.css({position:"absolute",left:"50%"}),e.jqi.animate({top:a.y||p,left:a.x||"50%",marginLeft:-1*(a.width/2),width:a.width})):e.jqi.css({position:"absolute",top:p,left:"50%",marginLeft:-1*(e.jqi.outerWidth(!1)/2)});void 0!==i&&i.data.animate===!1&&(t.fx.off=n)},e.style=function(){e.jqif.css({zIndex:e.options.zIndex,display:"none",opacity:e.options.opacity}),e.jqi.css({zIndex:e.options.zIndex+1,display:"none"}),e.jqib.css({zIndex:e.options.zIndex})},e.get=function(){return t("."+e.currentPrefix)},e.addState=function(i,n,o){var s,a,r,u,f,l="",p=null,c="",d="",m=e.options,x=t("."+e.currentPrefix+"states"),v=[],g=0;if(n=t.extend({},e.defaults.state,{name:i},n),null!==n.position.arrow&&(c='<div class="'+m.prefix+"arrow "+m.prefix+"arrow"+n.position.arrow+'"></div>'),n.title&&""!==n.title&&(d='<div class="lead '+m.prefix+"title "+m.classes.title+'">'+n.title+"</div>"),s=n.html,"function"==typeof n.html&&(s="Error: html function must return text"),l+='<div id="'+m.prefix+"state_"+i+'" class="'+m.prefix+'state" data-jqi-name="'+i+'" style="display:none;">'+c+d+'<div class="'+m.prefix+"message "+m.classes.message+'">'+s+"</div>"+'<div class="'+m.prefix+"buttons "+m.classes.buttons+'"'+(t.isEmptyObject(n.buttons)?'style="display:none;"':"")+">",t.isArray(n.buttons))v=n.buttons;else if(t.isPlainObject(n.buttons))for(r in n.buttons)n.buttons.hasOwnProperty(r)&&v.push({title:r,value:n.buttons[r]});for(g=0,f=v.length;f>g;g++)u=v[g],a=n.focus===g||isNaN(n.focus)&&n.defaultButton===g?e.currentPrefix+"defaultbutton "+m.classes.defaultButton:"",l+='<button class="'+m.classes.button+" "+e.currentPrefix+"button "+a,u.classes!==void 0&&(l+=" "+(t.isArray(u.classes)?u.classes.join(" "):u.classes)+" "),l+='" name="'+m.prefix+"_"+i+"_button"+u.title.replace(/[^a-z0-9]+/gi,"")+'" id="'+m.prefix+"_"+i+"_button"+u.title.replace(/[^a-z0-9]+/gi,"")+'" value="'+u.value+'">'+u.title+"</button>";return l+="</div></div>",p=t(l),p.on("impromptu:submit",n.submit),void 0!==o?x.find("#"+e.currentPrefix+"state_"+o).after(p):x.append(p),e.options.states[i]=n,p},e.removeState=function(t,i){var n=e.getState(t),o=function(){n.remove()};return 0===n.length?!1:("none"!==n.css("display")?void 0!==i&&e.getState(i).length>0?e.goToState(i,!1,o):n.next().length>0?e.nextState(o):n.prev().length>0?e.prevState(o):e.close():n.slideUp("slow",o),!0)},e.getState=function(i){return t("#"+e.currentPrefix+"state_"+i)},e.getStateContent=function(t){return e.getState(t)},e.getCurrentState=function(){return e.getState(e.getCurrentStateName())},e.getCurrentStateName=function(){return e.currentStateName},e.goToState=function(i,n,o){var s=(e.get(),e.options),a=e.getState(i),r=s.states[a.data("jqi-name")],u=new t.Event("impromptu:statechanging"),f=e.options;if(void 0!==r){if("function"==typeof r.html){var l=r.html;a.find("."+f.prefix+"message ").html(l())}"function"==typeof n&&(o=n,n=!1),e.jqib.trigger(u,[e.getCurrentStateName(),i]),!u.isDefaultPrevented()&&a.length>0&&(e.jqi.find("."+e.currentPrefix+"parentstate").removeClass(e.currentPrefix+"parentstate"),n?(e.jqi.find("."+e.currentPrefix+"substate").not(a).slideUp(s.promptspeed).removeClass("."+e.currentPrefix+"substate").find("."+e.currentPrefix+"arrow").hide(),e.jqi.find("."+e.currentPrefix+"state:visible").addClass(e.currentPrefix+"parentstate"),a.addClass(e.currentPrefix+"substate")):e.jqi.find("."+e.currentPrefix+"state").not(a).slideUp(s.promptspeed).find("."+e.currentPrefix+"arrow").hide(),e.currentStateName=r.name,a.slideDown(s.promptspeed,function(){var n=t(this);"string"==typeof r.focus?n.find(r.focus).eq(0).focus():n.find("."+e.currentPrefix+"defaultbutton").focus(),n.find("."+e.currentPrefix+"arrow").show(s.promptspeed),"function"==typeof o&&e.jqib.on("impromptu:statechanged",o),e.jqib.trigger("impromptu:statechanged",[i]),"function"==typeof o&&e.jqib.off("impromptu:statechanged",o)}),n||e.position())}return a},e.nextState=function(i){var n=t("#"+e.currentPrefix+"state_"+e.getCurrentStateName()).next();return n.length>0&&e.goToState(n.attr("id").replace(e.currentPrefix+"state_",""),i),n},e.prevState=function(i){var n=t("#"+e.currentPrefix+"state_"+e.getCurrentStateName()).prev();return n.length>0&&e.goToState(n.attr("id").replace(e.currentPrefix+"state_",""),i),n},e.close=function(i,n,o,s){e.timeout&&(clearTimeout(e.timeout),e.timeout=!1),e.jqib&&e.jqib.fadeOut("fast",function(){e.jqib.trigger("impromptu:close",[n,o,s]),e.jqib.remove(),t(window).off("resize",e.position)}),e.currentStateName=""},t.fn.prompt=function(i){void 0===i&&(i={}),void 0===i.withDataAndEvents&&(i.withDataAndEvents=!1),e(t(this).clone(i.withDataAndEvents).html(),i)},t.prompt=e,window.Impromptu=e});
\ No newline at end of file diff --git a/src/jquery-impromptu.js b/src/jquery-impromptu.js index ad88a67..2f0aaa0 100644 --- a/src/jquery-impromptu.js +++ b/src/jquery-impromptu.js @@ -705,400 +705,21 @@ };
/**
- * @var _ A utility object for internal use only.
+ * Enable using $('.selector').prompt({});
+ * This will grab the html within the prompt as the prompt message
*/
- var _ = {
- /**
- * query - query the document for elements
- * @param selector String - css selector
- * @param scope Element - Dom element to search from
- * @return Class - selector class with properties to manipulate collection of elements
- */
- query: function(selector, scope){
-
- /**
- * Sel - a mini selector object with built in methods to traverse nodes
- * @param selector String, NodeList, Node - css selector, a node list, or a single element
- * @param scope Element - Dom element to search from
- * @return Class - selector class with properties to manipulate collection of elements
- */
- var Sel = function(selector, scope){
- var nl;
- this.scope = scope || document;
- this.nodes=[];
-
- if(typeof selector === 'string'){ // either an html string or css selector
- nl = (selector[0] === '<') ? (function(){
- var dv = document.createElement('div');
- dv.innerHTML = selector;
- return document.createDocumentFragment().appendChild(dv).childNodes;
- })() : this.scope.querySelectorAll(selector);
- }
- else{ // a Node or NodeList was passed in
- nl = selector.length !== undefined ? selector : [selector];
- }
-
- // convert the nodelist to a native array
- for(var i = nl.length; i--; this.nodes.unshift(nl[i])){}
- this.length = this.nodes.length;
- return this;
- };
-
- /**
- * Sel.find - selector functionality for the current collection of nodes
- * @param selector String - css selector
- * @return Class - returns a new Sel class instance of found nodes
- */
- Sel.prototype.find = function(selector){
- return new Sel(selector, this.nodes[0]);
- };
-
- /**
- * Sel.attach - attach the collection of elements to a parent element
- * @param parent Node - an html node element to attach to
- * @param how String - append or prepend
- * @param where Node - Node to insert the new node before
- * @return Class - returns a new Sel class instance of found nodes or null
- */
- Sel.prototype.attach = function(parent, how, where){
- var t = this;
- return this.each(function(i,el){
- var x = how === 'append'? parent.appendChild(el) : parent.insertBefore(el, where || parent.firstChild);
- });
- };
-
- /**
- * Sel.neighbor - get the sibling element, not necessarily in the Sel collection but the overall dom
- * @param where String - previous or next
- * @return Class - returns a new Sel class instance of found nodes or null
- */
- Sel.prototype.neighbor = function(where){
- return new Sel(this.nodes[0][where +'Sibling']);
- };
-
- /**
- * Sel.each - loop over each element in the collection
- * @param fn function - the callback function for each node
- * @return Class - returns this Sel class instance
- */
- Sel.prototype.each = function(fn){
- for(var i=0; i<this.nodes.length; i++){
- fn.apply(this.nodes[i], [i, this.nodes[i]]);
- }
- return this;
- };
-
- /**
- * Sel.data - get/set the data properties on all nodes in collection
- * @param data string, object - string of property name to get, a hash of key/values to set
- * @return Class - returns this Sel class instance or value when using get
- */
- Sel.prototype.data = function(props){
- return (typeof props === 'string' && this.nodes.length > 0) ?
- this.nodes[0].getAttribute('data-'+props) :
- this.each(function(i, el){
- for(var k in props){
- if(props.hasOwnProperty(k)){
- el.setAttribute('data-'+k, props[k]);
- }
- }
- });
- };
-
- /**
- * Sel.offset - get the offset of an element from the overall document x/y
- * @return Object - {x: 123, y: 123} relative to the document, not the parent
- */
- Sel.prototype.offset = function(){
- var el = this.nodes[0],
- ret = { x:0, y:0 };
-
- do {
- ret.x += isNaN(el.offsetLeft) ? 0 : el.offsetLeft;
- ret.y += isNaN(el.offsetTop) ? 0 : el.offsetTop;
- } while(el = el.offsetParent);
-
- return ret;
- };
-
- /**
- * Sel.css - get/set the css properties on all nodes in collection
- * @param data string, object - string of property name to get, a hash of key/values to set
- * @return Class - returns this Sel class instance or value when using get
- */
- Sel.prototype.css = function(props){
- return (typeof props === 'string' && this.nodes.length > 0) ?
- this.nodes[0].style[props] :
- this.each(function(i, el){
- for(var k in props){
- if(props.hasOwnProperty(k)){
- el.style[k] = props[k];
- }
- }
- });
- };
-
- /**
- * Sel.class - work with class names on all nodes in collection
- * @param action string - has, add, delete
- * @param cls string - the class name to add, delete, has
- * @return Class/Bool - returns this Sel class instance, when action="has" will return boolean
- */
- Sel.prototype.cls = function(action, cls){
- var findre = new RegExp("\\b"+ cls +"\\b", 'i');
- return action === 'has' ?
- findre.test(this.nodes[0].className) :
- this.each(function(i, el){
- el.className = el.className.replace(findre, " ");
- if(action === 'add'){
- el.className += ' '+ cls;
- }
- });
- };
-
- /**
- * animate the collection of elements
- * @param props object - key/value pairs of css properties to animate to
- * @param duration int - milliseconds to animate
- * @param fn function - callback when done
- * @return Class - returns this Sel class instance
- */
- Sel.prototype.animate = function(props, duration, fn){
- var raf,
- t = this,
- start,
- progress,
- percent,
- fromprops={},
- animloop = function(time){
- var tmp = {};
- start = start || time;
- progress = time - start;
- percent = duration === 0 ? 1 : (progress / duration);
-
- for(var k in fromprops){
- tmp[k] = (props[k]-fromprops[k]) * percent;
- }
- t.css(tmp);
-
- if(progress < duration){
- window.requestAnimationFrame(animloop);
- }
- else{
- window.cancelAnimationFrame(raf);
- t.css(props);
- if(fn){fn.call(t);}
- }
- };
-
- for(var k in props){
- fromprops[k] = t.css(k) || 0;
- }
-
- // we need to look for an animation flag so this can be turned off
- if(imp.fx || duration > 0){
- raf = window.requestAnimationFrame(animloop);
- }
- else{
- t.css(props);
- if(fn){fn.call(t);}
- }
-
- return this;
- };
-
- /**
- * Sel.serialize - serialize the collection's form fields into an object
- * @return Object - keys are field names, values are field values
- */
- Sel.prototype.serialize = function(){
- var ret = {};
- this.find('input,select,textarea,button').each(function(i,el){
- var n = el.name,
- v = el.value,
- tag = el.tagName.toLowerCase();
-
- // checkboxes are always an array, only append if checked
- if(tag === 'input' && el.type === 'checkbox'){
- ret[n] = ret[n] || [];
- if(el.checked){
- ret[n].push(v);
- }
- }
- // radio is never an array, set only if checked
- else if(tag === 'input' && el.type === 'radio'){
- if(el.checked){
- ret[n] = v;
- }
- }
- // select multiple is always an array, append only selected options
- else if(tag === 'select' && el.multiple){
- ret[n] = [];
- new Sel('option[selected]',el).each(function(i,oel){
- ret[n].push(oel.value);
- });
- }
- // else standard input or select, convert to array if mulple with same name
- else{
- if(typeof ret[n] === 'object'){
- ret[n].push(v);
- }
- else if(ret[n] !== undefined){
- ret[n] = [ret[n], v];
- }
- else{
- ret[n] = v;
- }
- }
- });
- return ret;
- };
-
- /**
- * Sel.on - attach an event to the node collection
- * @param type string - name of the event to attach
- * @param fn function - the event handler function
- * @return Class - returns this Sel class instance
- */
- Sel.prototype.on = function(type, fn){
- return this.each(function(i, el){
- el[ el.addEventListener? 'addEventListener' : 'attachEvent'](type, fn, (type === 'blur' || type === 'focus'));
- });
- };
-
- /**
- * Sel.off - remove an event from the node collection
- * @param type string - name of the event to attach
- * @param fn function - the event handler function
- * @return Class - returns this Sel class instance
- */
- Sel.prototype.off = function(type, fn){
- return this.each(function(i, el){
- el[ el.removeEventListener? 'removeEventListener' : 'detachEvent'](type, fn, (type === 'blur' || type === 'focus'));
- });
- };
-
- /**
- * Sel.trigger - trigger an event to the node collection
- * @param type Event/string - name of the event trigger or an Event object
- * @param isCustom bool - whether this is a custom event or native
- * @return Class - returns this Sel class instance
- */
- Sel.prototype.trigger = function(ev, isCustom){
- ev = (typeof ev === 'string')? _.event(ev) : ev;
- return this.each(function(i, el){
- var j = el.dispatchEvent ? el.dispatchEvent(ev) : el.fireEvent((isCustom ? 'on' : '')+ ev.type, ev);
- });
- };
-
- return new Sel(selector, scope);
- },
-
- /**
- * Build a new event object
- * @param name string - name of the event. Do not include "on" ex: "onclick"
- * @param data object - any data to include into the event
- * @return Event - A native event object
- */
- event: function(name, data){
- var evt = (typeof Event === 'function')? new Event(name) : (function(){
- var mouse=/^(?:click|dblclick|mouse(?:down|up|over|move|out))$/.test(name),
- evt = document.createEvent(mouse ? 'MouseEvents':'HTMLEvents');
- evt[mouse ? 'initMouseEvent':'initEvent'](name, true, true);
- return evt;
- })();
-
- for(var i in data){
- evt[i] = data[i];
- }
- return evt;
- },
-
- /**
- * Extend an object with 1 or more objects
- * @param rec bool - true to do a recursive extend (nested), false for one level
- * @param o1 object - base object to extend, this will be returned
- * param o2.. object - any objects to extend the base object with
- * @return object - o1 object will be returned
- */
- extend: function(rec, o1){
- var i,j,v,t,args = Array.prototype.slice.call(arguments);
-
- for(i=2; i < args.length; i++){
- for(j in args[i]){
- if(args[i].hasOwnProperty(j)){
- v = args[i][j];
- t = Object.prototype.toString.call(v);
- if(rec && t === '[object Object]' && t !== null){
- o1[j] = imp._.extend(rec, o1[j], v);
- }
- else{
- o1[j] = args[i][j];
- }
- }
- }
- }
- return o1;
+ $.fn.prompt = function(options){
+ if(options === undefined){
+ options = {};
+ }
+ if(options.withDataAndEvents === undefined){
+ options.withDataAndEvents = false;
}
- };
-
- // export the utility class so so we can test it
- imp._ = _;
-
- /**
- * @var bool - true to run animations, false to simply set the values
- */
- imp.fx = true;
-
-
- if($){
- /**
- * Enable using $('.selector').prompt({});
- * This will grab the html within the prompt as the prompt message
- */
- $.fn.prompt = function(options){
- if(options === undefined){
- options = {};
- }
- if(options.withDataAndEvents === undefined){
- options.withDataAndEvents = false;
- }
-
- imp($(this).clone(options.withDataAndEvents).html(),options);
- };
- $.prompt = imp;
- }
+ imp($(this).clone(options.withDataAndEvents).html(),options);
+ };
+ $.prompt = imp;
window.Impromptu = imp;
}));
-
-
-// http://paulirish.com/2011/requestanimationframe-for-smart-animating/
-// http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating
-
-// requestAnimationFrame polyfill by Erik Möller
-// fixes from Paul Irish and Tino Zijdel
-
-(function() {
- var lastTime = 0;
- var vendors = ['ms', 'moz', 'webkit', 'o'];
- for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
- window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
- window.cancelAnimationFrame = window[vendors[x]+'CancelAnimationFrame'] || window[vendors[x]+'CancelRequestAnimationFrame'];
- }
-
- if (!window.requestAnimationFrame){
- window.requestAnimationFrame = function(callback, element) {
- var currTime = new Date().getTime();
- var timeToCall = Math.max(0, 16 - (currTime - lastTime));
- var id = window.setTimeout(function() { callback(currTime + timeToCall); }, timeToCall);
- lastTime = currTime + timeToCall;
- return id;
- };
- }
- if (!window.cancelAnimationFrame){
- window.cancelAnimationFrame = function(id) { clearTimeout(id); };
- }
-}());
\ No newline at end of file diff --git a/test/jquery-impromptu_spec.js b/test/jquery-impromptu_spec.js index c784d29..0e3cf25 100644 --- a/test/jquery-impromptu_spec.js +++ b/test/jquery-impromptu_spec.js @@ -2,484 +2,6 @@ describe('jquery-impromptu', function() { // ==================================================================================== // ==================================================================================== - describe('utilities', function(){ - - // ==================================================================================== - describe('extend', function(){ - - it('should extend an object non recursive', function(){ - var o1 = { foo: 'foo', bar: 'bar' }, - o2 = { foo: 'foo2' }, - o3 = { foo: 'foo3', foobar: 'foobar' }, - result = Impromptu._.extend(false, o1,o2,o3), - compare = { foo: 'foo3', bar: 'bar', foobar: 'foobar' }; - - expect(result).toEqual(compare); - - o1 = { foo: { a:1, b:2 }, bar: [1,2,3,4,5] }; - o2 = { foo: { a: -1, c: 3 } }; - o3 = { bar: [9,8,7] }; - result = Impromptu._.extend(false, o1,o2,o3); - compare = { foo: { a: -1, c: 3 }, bar: [9,8,7] }; - - expect(result).toEqual(compare); - }); - - it('should extend an object recursively', function(){ - var o1 = { foo: 'foo', bar: 'bar' }, - o2 = { foo: 'foo2' }, - o3 = { foo: 'foo3', foobar: 'foobar' }, - result = Impromptu._.extend(true, o1,o2,o3), - compare = { foo: 'foo3', bar: 'bar', foobar: 'foobar' }; - - expect(result).toEqual(compare); - - o1 = { foo: { a:1, b:2 }, bar: [1,2,3,4,5] }; - o2 = { foo: { a: -1, c: 3 } }; - o3 = { bar: [9,8,7] }; - result = Impromptu._.extend(true, o1,o2,o3); - compare = { foo: { a: -1, b: 2, c: 3 }, bar: [9,8,7] }; - - expect(result).toEqual(compare); - }); - }); - - // ==================================================================================== - describe('event', function(){ - - it('should create a native event', function(){ - var result = Impromptu._.event('click'), - compare = 'object'; - - expect(result).toBeDefined(); - expect(typeof result).toBe(compare); - expect(result.type).toBe('click'); - }); - - it('should create a custom event', function(){ - var result = Impromptu._.event('impromptu:test'), - compare = 'object'; - - expect(result).toBeDefined(); - expect(typeof result).toBe(compare); - expect(result.type).toBe('impromptu:test'); - }); - - it('should attach data to an event', function(){ - var result = Impromptu._.event('impromptu:test', {test1: 'foobar'}), - compare = 'foobar'; - - expect(result.test1).toBe(compare); - }); - }); - - // ==================================================================================== - describe('query', function(){ - beforeEach(function(){ - $('body').append('<div id="dummyels" style="display:none">'+ - '<form action="" method="post" class="dummyels-form">'+ - '<label class="field"><input type="text" name="test1" value="test val 1"></label>'+ - '<label class="field"><input type="password" name="test2" value="test val 2"></label>'+ - '<label class="field"><input type="file" name="test3"></label>'+ - '<label class="field"><input type="checkbox" name="test4" value="test val 4 - a"></label>'+ - '<label class="field"><input type="checkbox" name="test4" value="test val 4 - b" checked></label>'+ - '<label class="field"><input type="checkbox" name="test4" value="test val 4 - c"></label>'+ - '<label class="field"><input type="checkbox" name="test4" value="test val 4 - d" checked></label>'+ - '<label class="field"><input type="checkbox" name="test4" value="test val 4 - e"></label>'+ - '<label class="field"><input type="radio" name="test5" value="test val 5 - a"></label>'+ - '<label class="field"><input type="radio" name="test5" value="test val 5 - b" checked></label>'+ - '<label class="field"><input type="radio" name="test5" value="test val 5 - c"></label>'+ - '<label class="field"><textarea name="test6">test val 6</textarea></label>'+ - '<label class="field">'+ - '<select name="test7">'+ - '<option value="test val 7 - a">'+ - '<option value="test val 7 - b">'+ - '<option value="test val 7 - c" selected>'+ - '</select>'+ - '</label>'+ - '<label class="field">'+ - '<select name="test8" multiple>'+ - '<option value="test val 8 - a">'+ - '<option value="test val 8 - b" selected>'+ - '<option value="test val 8 - c" selected>'+ - '</select>'+ - '</label>'+ - '</form>'+ - '</div>'); - }); - afterEach(function(){ - $('#dummyels').remove(); - }); - - // ==================================================================================== - describe('constructor', function(){ - - it('should find elements with a css selector', function(){ - var result = Impromptu._.query('#dummyels'), - compare = 1; - - expect(result).toBeDefined(); - expect(result.length).toBe(compare); - }); - - it('should accept a single Node', function(){ - var result = Impromptu._.query(document.getElementById('dummyels')), - compare = 1; - - expect(result.length).toBe(compare); - }); - - it('should accept a NodeList', function(){ - var result = Impromptu._.query(document.getElementById('dummyels').querySelectorAll('label')), - compare = 14; - - expect(result.length).toBe(compare); - }); - - it('should accept an html string and build a document fragment', function(){ - var result = Impromptu._.query('<span>foo</span><span>bar</span><div>foobar</div>'), - compare = 3; - - expect(result.length).toBe(compare); - expect(result.nodes.length).toBe(compare); - }); - }); - - // ==================================================================================== - describe('find', function(){ - - it('should find elements', function(){ - var result = Impromptu._.query('#dummyels').find('label'), - compare = 14; - - expect(result.length).toBe(compare); - }); - }); - - // ==================================================================================== - describe('each', function(){ - - it('should return a result set', function(){ - var result = 0, - compare = 14, - els = Impromptu._.query('#dummyels form label').each(function(){ result++; }); - - expect(els.length).toBe(compare); - }); - - it('should loop every over every found element', function(){ - var result = 0, - compare = 14; - - Impromptu._.query('#dummyels form label').each(function(){ result++; }); - - expect(result).toBe(compare); - }); - }); - - // ==================================================================================== - describe('attach', function(){ - - it('should append elements to a parent', function(){ - var parent = document.getElementById('dummyels'), - result = Impromptu._.query('<span>test append</span>').attach(parent, 'append'), - compare = parent.lastChild; - - expect(result.nodes[0]).toBe(compare); - }); - - it('should append elements to a parent', function(){ - var parent = document.getElementById('dummyels'), - result = Impromptu._.query('<span>test append</span>').attach(parent, 'prepend'), - compare = parent.firstChild; - - expect(result.nodes[0]).toBe(compare); - }); - - }); - - // ==================================================================================== - describe('data', function(){ - - it('should return a result set', function(){ - var compare = 14, - els = Impromptu._.query('#dummyels form label').data({ test: '1234' }); - - expect(els.length).toBe(compare); - }); - - it('should set a data attribute', function(){ - - Impromptu._.query('#dummyels form label').data({ test: 'asdf' }); - - var result = document.querySelector('#dummyels form label').getAttribute('data-test'), - compare = 'asdf'; - - expect(result).toBe(compare); - }); - - it('should get a data attribute', function(){ - - document.querySelector('#dummyels form label').setAttribute('data-test', 'asdf'); - - var compare = 'asdf', - result = Impromptu._.query('#dummyels form label').data('test'); - - - expect(result).toBe(compare); - }); - }); - - // ==================================================================================== - describe('css', function(){ - - it('should return a result set', function(){ - var compare = 14, - els = Impromptu._.query('#dummyels form label').css({ color: 'rgb(255, 0, 0)' }); - - expect(els.length).toBe(compare); - }); - - it('should set a css property', function(){ - - Impromptu._.query('#dummyels form label').css({ color: 'rgb(255, 0, 0)' }); - - var result = document.querySelector('#dummyels form label').style.color, - compare = 'rgb(255, 0, 0)'; - - expect(result).toBe(compare); - }); - - it('should get a css property', function(){ - - document.querySelector('#dummyels form label').style.color = 'rgb(255, 0, 0)'; - - var compare = 'rgb(255, 0, 0)', - result = Impromptu._.query('#dummyels form label').css('color'); - - - expect(result).toBe(compare); - }); - }); - - // ==================================================================================== - describe('cls', function(){ - - it('should find the class name', function(){ - var compare = true, - result = Impromptu._.query('#dummyels form label').cls('has', 'field'); - - expect(result).toBe(compare); - }); - - it('should not find the class name', function(){ - var compare = false, - result = Impromptu._.query('#dummyels form label').cls('has', 'foobar'); - - expect(result).toBe(compare); - }); - - it('should add the class to the elemnts', function(){ - var compare = true, - els = Impromptu._.query('#dummyels form label').cls('add', 'foobar'), - result = els.cls('has', 'foobar'); - - expect(result).toBe(compare); - }); - - it('should remove the class to the elemnts', function(){ - var compare = false, - els = Impromptu._.query('#dummyels form label').cls('remove', 'field'), - result = els.cls('has', 'field'); - - expect(result).toBe(compare); - }); - }); - - // ==================================================================================== - describe('animate', function(){ - describe('with Imprompt.fx false', function(){ - - beforeEach(function(){ - Impromptu.fx = false; - }); - - afterEach(function(){ - Impromptu.fx = true; - }); - - it('should set css properties', function(){ - - Impromptu._.query('#dummyels form label').animate({ width: 200, opacity: 0.5 }, 0); - - var result = document.querySelector('#dummyels form label').style.opacity, - compare = '0.5'; - - expect(result).toBe(compare); - }); - }); - - describe('with Imprompt.fx true', function(){ - - beforeEach(function(done){ - Impromptu._.query('#dummyels form label').animate({ width: 200, opacity: 0.5 }, 100, function(){ done(); }); - }); - - it('should set css properties', function(){ - var result = document.querySelector('#dummyels form label').style.opacity, - compare = '0.5'; - - expect(result).toBe(compare); - }); - }); - }); - - // ==================================================================================== - describe('serialize', function(){ - - it('should return an object with selected values', function(){ - var compare = { - test1: 'test val 1', - test2: 'test val 2', - test3: '', - test4: ['test val 4 - b','test val 4 - d'], - test5: 'test val 5 - b', - test6: 'test val 6', - test7: 'test val 7 - c', - test8: ['test val 8 - b','test val 8 - c'] - }, - result = Impromptu._.query('#dummyels form').serialize(); - - expect(result).toEqual(compare); - }); - - }); - - // ==================================================================================== - describe('on', function(){ - - describe('add native event', function(){ - var spyEventCalled; - - beforeEach(function(done){ - spyEventCalled = false; - - Impromptu._.query('body').on('click', function(){ spyEventCalled = true; done(); }); - - document.body.dispatchEvent(Impromptu._.event('click')); - }); - - it('should fire event', function(){ - expect(spyEventCalled).toBe(true); - }); - }); - - describe('add custom event', function(){ - var spyEventCalled; - - beforeEach(function(done){ - spyEventCalled = false; - - Impromptu._.query('body').on('impromptu:test', function(){ spyEventCalled = true; done(); }); - - document.body.dispatchEvent(Impromptu._.event('impromptu:test')); - }); - - it('should fire event', function(){ - expect(spyEventCalled).toBe(true); - }); - }); - }); - - // ==================================================================================== - describe('off', function(){ - - describe('remove native event', function(){ - var spyEventCalled; - - beforeEach(function(done){ - spyEventCalled = false; - var evtfn = function(){ spyEventCalled = true; done(); }; - - Impromptu._.query('body').on('click', evtfn); - - Impromptu._.query('body').off('click', evtfn); - - document.body.dispatchEvent(Impromptu._.event('click')); - - // since it should haven been called and should happen quickly, end this test - setTimeout(function(){ if(!spyEventCalled){ done(); }}, 10); - }); - - it('should not fire event', function(){ - expect(spyEventCalled).not.toBe(true); - }); - }); - - describe('remove custom event', function(){ - var spyEventCalled; - - beforeEach(function(done){ - spyEventCalled = false; - var evtfn = function(){ spyEventCalled = true; done(); }; - - Impromptu._.query('body').on('impromptu:test', evtfn); - - Impromptu._.query('body').off('impromptu:test', evtfn); - - document.body.dispatchEvent(Impromptu._.event('impromptu:test')); - - // since it should haven been called and should happen quickly, end this test - setTimeout(function(){ if(!spyEventCalled){ done(); }}, 10); - }); - - it('should not fire event', function(){ - expect(spyEventCalled).not.toBe(true); - }); - }); - - }); - - // ==================================================================================== - describe('trigger', function(){ - describe('emit native event', function(){ - var spyEventCalled; - - beforeEach(function(done){ - spyEventCalled = false; - - Impromptu._.query('body').on('click', function(){ spyEventCalled = true; done(); }); - - Impromptu._.query('body').trigger('click'); - }); - - it('should fire event', function(){ - expect(spyEventCalled).toBe(true); - }); - }); - - describe('emit custom event', function(){ - var spyEventCalled; - - beforeEach(function(done){ - spyEventCalled = false; - - Impromptu._.query('body').on('impromptu:test', function(){ spyEventCalled = true; done(); }); - - Impromptu._.query('body').trigger(Impromptu._.event('impromptu:test')); - }); - - it('should fire event', function(){ - expect(spyEventCalled).toBe(true); - }); - }); - }); - }); - - }); - - // ==================================================================================== - // ==================================================================================== describe('base structure', function(){ // ==================================================================================== |