jQuery Impromptu

Take the Tour

About

jQuery Impromptu is an extension to help provide a more pleasant way to spontaneously prompt a user for input. More or less this is a great replacement for an alert, prompt, and confirm. Not only does it replace these but it also allows for creating forms within these controls. This is not intended to be a modal replacement, just a quick tool to prompt user input in a fashionable way.

Get Started

Highly Recommended

Subscribe to my newsletter and follow me @practicalweb.

eBook: Impromptu From I to U

Get the ebook to learn about advanced functionality of Impromptu including states, forms, tours, theming, and more!

buy eBook + Example code

buy eBook

Donation

Has Impromptu been helpful to you?

Download

Version

Version 6.2.3

Last updated on 2016-04-23

jQuery Impromptu is currently available for use in all personal or commercial projects under the MIT License.

Options

Usage

var jqPromptEl = $.prompt( msg , options );

// OR

var api = new Impromptu( msg , options );

Impromptu can be called through $.prompt() or by creating a new instance of the Impromptu object. Whats the difference?

An Impromptu instance is a single prompt. The constructor returns it's api so you can manipulate it.

$.prompt is an object that manages a stack of Impromptu instances. What does this mean? You can continuously call $.prompt without closing the previous prompt, and $.prompt will always manage the newest prompt on the stack by acting as a proxy to the latest Impromptu instance. $.prompt() will return a jQuery object of the latests prompt.

Since $.prompt acts as a simple proxy to Impromptu, they accept the same options.

msg

The message can either be an html string, or an object of "states". Each state has the following properties:

name
A valid variable name to access the state by. Default: State's array index or object key
title
A string to be used as the title of the state
html
A string of html or text for the content
buttons
An object containing the text and values of each button the user may click. Default: { Ok : true }
focus
Index of the button to focus or selector to element to focus. Default: 0
defaultButton
Index of the button to focus. Similar to the focus option, but if focus is a selector this can still style the button as the default. Default: 0
submit
A function to be called when the prompt is submitted. Default: function(event, value, message, formVals){} Return false or event.preventDefault() to keep the prompt open. Event object also has properties event.state and event.stateName.
var temp = {
	state0: {
		html:'test 1...',
		buttons: { Cancel: false, Next: true },
		focus: 1,
		position: { container: '#elId', x: -300, y: -45, width: 250, arrow: 'rm' },
		submit:function(e,v,m,f){ }
	},
	state1: {
		html:'test 2..',
		buttons: { Back: -1, Exit: 0, Next: 1 },
		focus: 2,
		submit:function(e,v,m,f){ }
	}
};

If a string is passed as the message in place of a state, buttons, focus, and submit will be substituted from the options below.

options

buttons
An object containing the text and values of each button the user may click. Default: { Ok : true }
buttonTimeout
A time frame in milliseconds to disable buttons after a click to prevent double submitting. -1 will disable this feature. Default: 1000
classes
An object of class names for each part of a prompt for greater compatibilty with existing css frameworks. For example if you would like to use twitter bootstrap you would include the base theme (in the themes folder), then pass the following classes:
{
	box: '',
	fade: '',
	prompt: '',
	close: '',
	title: 'lead',
	message: '',
	buttons: '',
	button: 'btn',
	defaultButton: 'btn-primary'
}
Use the base theme in place of the default css file since it has minimal styling, allowing other css frameworks to work their magic. To view a complete demo see the examples section below.
close
A function to be called when the prompt is closed and just before being removed from the DOM. Default: function(event[, value, message, formVals]){} Last three paremeters available only when button was clicked.
focus
Index of the button to focus or selector to element to focus. Default: 0
initialState
The state to be shown first. Pass either a string for state name or numeric index of the state. Default: 0
loaded
A function to be called when the prompt is fully loaded Default: function(event){}
opacity
The prefered opacity of the transparent layer placed over the container. Default: 0.6
overlayspeed
The prefered speed of the fadeIn and fadeOut of the overlay ("slow", "fast", number) Default: "slow"
persistent
If the prompt should close when the fade is clicked (true doesn't close). Default: true
prefix
A prefix to be used for all css classes and html object id's. Use this option when you want to change themes. Default: 'jqi'
promptspeed
The prefered speed of the showing of the prompt ("slow", "fast", number). Default: "fast"
show
Name of the jQuery method to animate the entrance of the prompt ("show","fadeIn","slideDown"). Default: "fadeIn"
hide
Name of the jQuery method to animate the hiding of the prompt ("hide","fadeOut","slideUp"). Default: "fadeOut"
statechanging
A function to be called when a state is about to change. Default: function(event, fromStatename, toStateName){} Return false or event.preventDefault() to prevent the state change.
statechanged
A function to be called when a state has changed. Default: function(event, toStateName){}
submit
See state submit event above.
timeout
The number of milliseconds until the prompt automatically closes. Default: 0
top
Distance from the top of the screen the prompt will be Default: 15%
useiframe
Will use an iframe for the overlay in IE6 to cover up <select>. Default: false
zIndex
zIndex to apply to the prompt. Default: 999

Methods

$.prompt.setDefaults(options)
Sets the defaults for prompts.
$.prompt.setDefaults({
	prefix: 'myPrompt',
	show: 'slideDown'
});
$.prompt.setStateDefaults(options)
Sets the defaults for states.
$.prompt.setStateDefaults({
	buttons: { Ok:true, Cancel:false },
	focus: 1
});
jQuery.prompt.open(states, options)
Returns an instance of Impromptu. Opens the prompt.
jQuery.prompt.getCurrentState()
Returns a jquery object of the current visible state.
jQuery.prompt.getCurrentStateName()
Returns a string current visible state's name.
jQuery.prompt.getState(stateName)
Returns a jquery object of the state, so you can update the content within it.
jQuery.prompt.getPrompt()
Returns a jquery object of the prompt.
jQuery.prompt.getBox()
Returns a jquery object of the box (div) containing the fade and prompt.
jQuery.prompt.getApi()
Returns the instance object exposing the api. Useful when using $.prompt and you want direct access to the Impromptu instance.
jQuery.prompt.addState(stateName, stateOptions, insertAfterState)
Injects a new state after the indicated insertAfterState name. Returns a jQuery object of the new state.
jQuery.prompt.removeState(stateName)
Removes the state. Returns true on success, false on failure.
jQuery.prompt.goToState(stateName, subState, callback)
Transitions to the specified state. subState is a Boolean to use substate functionality. Callback represents a statechanged event.
jQuery.prompt.nextState(callback)
Transitions to the next state. Callback represents a statechanged event.
jQuery.prompt.prevState(callback)
Transitions to the previous state. Callback represents a statechanged event.
jQuery.prompt.enableStateButtons(stateName, buttons)
Enable buttons in a state. stateName defaults to the current state and buttons is an array of button values to enable. Omit the buttons argument to enable all buttons.
jQuery.prompt.disableStateButtons(stateName, buttons)
disable buttons in a state. stateName defaults to the current state and buttons is an array of button values to disable. Omit the buttons argument to disable all buttons.
jQuery.prompt.close()
Closes the prompt.

Events

If you like to bind events manually you can do so with the following:

impromptu:loaded
Same as loaded option. Scope is the entire prompt and fade container.
var myPrompt = jQuery.prompt(/*...*/);
myPrompt.on('impromptu:loaded', function(e){});
impromptu:submit
Same as submit option. Scope is the state element. These events are per state, so you must attach it directly to a state.
var myPrompt = jQuery.prompt(/*...*/);
$.prompt.getState('state2')
	.on('impromptu:submit', function(e,v,m,f){});
impromptu:close
Same as close option. Scope is entire prompt and fade container
impromptu:statechanging
Same as statechangin option. Scope is the entire prompt and fade container. This fires before the state changes, so you may return false or use e.preventDefault() prevent the state change.
impromptu:statechanged
Same as statechanged option. Scope is the entire prompt and fade container. This fires after the state has successfully changed.

Examples

Basics

A prompt in the simplest of fashion.

$.prompt("Hello World!");

Lets add some buttons and a title.

$.prompt("Proceeding may be good for your site..", {
	title: "Are you Ready?",
	buttons: { "Yes, I'm Ready": true, "No, Lets Wait": false }
});

Use the submit function to get the answer.

$.prompt("Open your javascript console to see the answer.", {
	title: "Are you Ready?",
	buttons: { "Yes, I'm Ready": true, "No, Lets Wait": false },
	submit: function(e,v,m,f){
		// use e.preventDefault() to prevent closing when needed or return false.
		// e.preventDefault();

		console.log("Value clicked was: "+ v);
	}
});

You can open multiple prompts at one time. Of course for a better user experience you may want to look at using states when possible, but multiple prompts can be open at once.

$.prompt will always control the most recent prompt. If you ever need direct access to the current instance, you can call $.prompt.getApi();

var multiplePromptsCounter = 1;

function openMultiplePrompts(){

	$.prompt("Do you want to open another?", {
		title: "A Prompt Has Opened: "+ multiplePromptsCounter++,
		buttons: { "Yes, Open Another": true, "No, Close This One": false },
		persistent: false,
		submit: function(e,v,m,f){
			if(v){
				e.preventDefault();
				openMultiplePrompts();
			}
		}
	});
}

openMultiplePrompts();

States

To use states pass in a collection (array or object) of objects with common properties (html, buttons, focus, submit, position..).

var statesdemo = {
	state0: {
		html:'Something really cool will happen when you click Next.  Prepare yourself for amazement!...',
		buttons: { Cancel: false, Next: true },
		focus: 1,
		submit:function(e,v,m,f){
			if(v){
				e.preventDefault();
				$.prompt.goToState('state1');
				return false;
			}
			$.prompt.close();
		}
	},
	state1: {
		html:'Was that awesome or what!?',
		buttons: { Back: -1, Exit: 0 },
		focus: 1,
		submit:function(e,v,m,f){
			e.preventDefault();
			if(v==0)
				$.prompt.close();
			else if(v==-1)
				$.prompt.goToState('state0');
		}
	}
};

$.prompt(statesdemo);

To use a substate create your states as normal, but use the subState option when calling $.prompt.goToState().

var statesdemo = {
	state0: {
		title: 'Terms of Use',
		html:'<p>These are the terms of use.  You should agree to these terms before proceeding.</p><p>(This is just an example)</p>',
		buttons: { Cancel: false, Agree: true },
		focus: 1,
		submit:function(e,v,m,f){
			if(v){
				e.preventDefault();
				$.prompt.goToState('state1', true);
				return false;
			}
			$.prompt.close();
		}
	},
	state1: {
		html:'Are you sure?',
		buttons: { No: -1, Yes: 0 },
		focus: 1,
		submit:function(e,v,m,f){
			e.preventDefault();
			if(v==0)
				$.prompt.goToState('state2');
			else if(v==-1)
				$.prompt.goToState('state0');
		}
	},
	state2: {
		title: "You're Done!",
		html: "Congratulations, you've finished this example!",
		buttons: { Close: 0 },
		focus: 0
	}
};

$.prompt(statesdemo);

To use tour or tooltip like features pass in a collection (array or object) of state objects with the position property.

var tourSubmitFunc = function(e,v,m,f){
			if(v === -1){
				$.prompt.prevState();
				return false;
			}
			else if(v === 1){
				$.prompt.nextState();
				return false;
			}
},
tourStates = [
	{
		title: 'Welcome',
		html: 'Ready to take a quick tour of jQuery Impromptu?',
		buttons: { Next: 1 },
		focus: 0,
		position: { container: 'h1', x: 200, y: 60, width: 200, arrow: 'tc' },
		submit: tourSubmitFunc
	},
	{
		title: 'Download',
		html: 'When you get ready to use Impromptu, you can get it here.',
		buttons: { Prev: -1, Next: 1 },
		focus: 1,
		position: { container: '#Download', x: 170, y: 0, width: 300, arrow: 'lt' },
		submit: tourSubmitFunc
	},
	{
		title: "You've Got Options",
		html: 'A description of the options are can be found here.',
		buttons: { Prev: -1, Next: 1 },
		focus: 1,
		position: { container: '#Options', x: -10, y: -145, width: 200, arrow: 'bl' },
		submit: tourSubmitFunc
	},
	{
		title: 'Examples..',
		html: 'You will find plenty of examples to get you going..',
		buttons: { Prev: -1, Next: 1 },
		focus: 1,
		position: { container: '#Examples', x: 80, y: 10, width: 500, arrow: 'lt' },
		submit: tourSubmitFunc
	},
	{
		title: 'The Tour Code',
		html: 'Including this tour... See, creating a tour is easy!',
		buttons: { Prev: -1, Next: 1 },
		focus: 1,
		position: { container: '#TourCode', x: 180, y: -130, width: 400, arrow: 'br' },
		submit: tourSubmitFunc
	},
	{
		title: 'Learn More',
		html: 'If you would like to learn more please consider purchasing a copy of Impromptu From I to U. If you found Impromptu helpful you can also donate to help fund development.  If not, thanks for stopping by!',
		buttons: { Done: 2 },
		focus: 0,
		position: { container: '.ebook', x: 370, y: 120, width: 275, arrow: 'lt' },
		submit: tourSubmitFunc
	}
];
$.prompt(tourStates);

Forms

The bread and butter of Impromptu is forms. By simply including form fields in the html all form values are gathered and sent via the "f" (aka "form") parameter. The "m" (aka "message") parameter is a jQuery object of the message itself incase you need to modify the dom. Open your javascript console to view the object sent on submit.

var statesdemo = {
	state0: {
		title: 'Name',
		html:'<label>First <input type="text" name="fname" value=""></label><br />'+
			'<label>Last <input type="text" name="lname" value=""></label><br />',
		buttons: { Next: 1 },
		//focus: "input[name='fname']",
		submit:function(e,v,m,f){
			console.log(f);

			e.preventDefault();
			$.prompt.goToState('state1');
		}
	},
	state1: {
		title: 'Gender',
		html:'<label><input type="radio" name="gender" value="Male"> Male</label><br />'+
			'<label><input type="radio" name="gender" value="Female"> Female</label>',
		buttons: { Back: -1, Next: 1 },
		//focus: ":input:first",
		submit:function(e,v,m,f){
			console.log(f);

			if(v==1) $.prompt.goToState('state2')
			if(v==-1) $.prompt.goToState('state0');
			e.preventDefault();
		}
	},
	state2: {
		title: 'Transportation',
		html:'<label>Travels By <select name="travel" multiple>'+
				'<option value="Car" selected>Car</option>'+
				'<option value="Bus">Bus</option>'+
				'<option value="Plane" selected>Plane</option>'+
				'<option value="Train">Train</option>'+
			'</select></label>',
		buttons: { Back: -1, Done: 1 },
		focus: 1,
		submit:function(e,v,m,f){
			console.log(f);

			e.preventDefault();
			if(v==1) $.prompt.close();
			if(v==-1) $.prompt.goToState('state1');
		}
	},
};

$.prompt(statesdemo);

Advanced

The following are example demonstrations of various useful utilities with Impromptu.