Archive for the ‘jQuery’ Category

After some prompting by those actually using it, I paid more attention to my flexcal date picker plugin, adding features like buttons, drop-down menus and formatted dates. The documentation is on my github pages at github.bililite.com/flexcal, and the code is on github at github.com/dwachss/flexcal. All other posts about it are obsolete.

The current stable version is 3.4.

jQuery's animate is useful for animating CSS properties, but there are times that you want to take advantage of the bookkeeping that jQuery provides to animate, with easing functions etc., but not to change an animatable property. The flip plugin for Mike Alsup's cycle2 has a clever hack to animate some otherwise unused property instead:


<input type=button value="Click Me" id=rotatebutton />
<div id=rotatetest style="height: 100px; width: 100px; background: #abcdef" >Whee!</div>

$('#rotatebutton').click(function(){
  $('<div>'). // create an unused element (could use a preexisting one to save some time and memory)
    animate({lineHeight: 360}, // we aren't really using lineHeight; we just want something numeric.
      // We want it to go from 0 (the default for anything that has a value of 'auto') to 360
    {
      duration: 2000,
      easing: 'easeOutElastic', // use jQuery and jQuery UI to manage the animation timing
      step: function (now){
        $('#rotatetest').css('transform', 'rotate('+now+'deg)'); // use the number that animate gives us
      }
    });
});

I finally updated my jQuery widget subclassing code to use the newest version of jQuery UI, which incorporated a lot of the original ideas I outlined back in 2010. The new documentation is now on my github pages, and I've updated the flexcal posts to reflect it.

It is a breaking change; instead of $.namespace.widgetname.subclass('namespace.newwidgetname', {methods...}) you use the real jQuery UI way: $.widget('namespace.newwidgetname', $.namespace.widgetname, {methods...}).

I've also changed all my flexcal-related widgets to the bililite namespace, per jQuery UI guidelines. It's now $.bililite.flexcal instead of $.ui.flexcal, and so on for all the fields in that (like $.bililite.flexcal.tol10n).

Hope not too many people are inconvenienced.

See the code.

jQuery plugin to allow using cdn.rawgit.com to get the latest commit of a github repo

github won't let you hotlink to their site directly; raw.githubusercontent.com sends its content with a X-Content-Type-Options:nosniff header, so modern browsers won't accept it as javascript.

http://rawgit.com gets around that by pulling the raw file and re-serving it with more lenient headers, but the rate is throttled so you can't use it on public sites. http://cdn.rawgit.com isn't throttled but is cached, permanently. Once a given URL is fetched, it stays in the cache and if the file is updated on github, it won't be on cdn.rawgit.com . So having a script tag <script src="http://cdn.rawgit.com/user/repo/master/file.js"> lets you get the script from github, but even when the master branch is updated, the script retrieved will remain the same.

The answer is to use a specific tag or commit in the script tag: <script src="http://cdn.rawgit.com/user/repo/abc1234/file.js"> and change that when the underlying repo is updated. But that is terribly inconvenient.

For stable libraries, that's not a problem, since they should be tagged with version numbers: http://cdn.rawgit.com/user/repo/v1.0/file.js and that's probably what you want. However, if you always want the latest version, that won't work.

$.repo uses the github API to get the SHA for the latest commit to the master, and returns a $.Deferred that resolved to the appropriate URL (with no trailing slash):

$.repo('user/repo').then(function (repo){
	$.getScript(repo+'/file.js');
});

The github api is also rate-limited (to 60 requests an hour from a given IP address), so the repo address is cached for fixed period of time (default 1 hour), with the value saved in localStorage.

$.repo('user/repo', time); // if the cached value is more than time msec old, get a new one
$.repo('user/repo', 0); // force a refresh from github's server

$.getScripts

$.getScript is useful, but it is asynchronous, which means that you can't load scripts that depend on one another with:

$.getScript('first.js');
$.getScript('second.js');
$.getScript('third.js');

You have to do:

$.getScript('first.js').then(function(){
	return $.getScript('second.js');
}).then(function(){
	return $.getScript('third.js');
}).then(function(){
	// use the scripts
});

$.getScripts(Array) abstracts this out, so you can do:

$.getScripts(['first.js', 'second.js', 'third.js']).then(function(){
	// use the scripts
});

It's basically a very simple script loader.

Two new additions to flexcal, which is now at version 2.2. See the code and a demo, that uses my new github pages.

Mouse Wheel

The calendar now responds to wheel events, changing the month with scroll up/down and changing the calendar tab with scroll left/right. I initially tried to throttle it since my trackpad was too sensitive, but that made it too slow. I'm not sure waht to do about that. It works well with an actual mouse wheel, thoug.

Keith Wood's Calendars

Keith Wood is maintaining the jQuery plugin that eventually became the official jQuery UI datepicker. His version, however, handles multiple calendar systems, much like flexcal (though I like my plugin, of course). His code is on github, and the documentation is on his personal site. He has support for many calendar systems, and I wanted to let flexcal use that. I don't use his datepicker code, just the calendar systems.

I'm using a naming convention of language-calendar, like he-jewish for a calendar localized to hebrew, using a Jewish lunar calendar. It's the opposite of Woods, who uses calendar-language, like islamic-ar for a calendar localized to arabic, using the Islamic lunar calendar. For my names, the default language is en and the default calendar system in gregorian. Thus, islamic would be an English language Islamic calendar, and zh-TW would be a Taiwanese Chinese Gregorian calendar (my parser is smart enough to not be confused by the extra hyphen). The language codes are ISO 639 two-letter codes.

There is a new function, $.ui.flexcal.tol10n(name) that creates a localization object with appropriate language and calendar system. It is designed to be transparent; doing

$('input').flexcal({
  calendars: ['ar-islamic']
});

will look in the existing $.ui.flexcal.l10n object for 'ar-islamic', then try to find it in the jQuery UI datepicker localizations (if those are loaded) (note that jQuery UI only uses Gregorian calendars), then Woods's calendars if they exist.

You can use the bridge directly if you want; $.ui.flexcal.tol10n(name) returns a localization object that you can modify as desired and then pass to flexcal.

To use this, you need to include the necessary script files: jquery.calendars.js for the basic code, jquery.calendars.name.js (like jquery.calendars.islamic.js) for the calendar-system-specific routines (these are all in English), and jquery.calendars.name-language.js (like jquery.calendars.islamic-ar.js)for the language-specific localization, or jquery.calendars.language.js for language-specific localization using the Gregorian calendar.

Of note, the text that is used for the "Next Month" and "Previous Month" is localized for the datepicker, not the underlying calendar system, so if you want that included automatically, also include the jquery.calendars.picker-name.js. I have a little hack in flexcal so you do not have to include the entire jquery.calendars.picker.js package; just include the jquery.calendars.picker-mock.js before including the localization code.
It should be clear which files to include if you look at the list.

TODO

His calendar code also has some nice formatting options, which flexcal does not have out of the box, though it is possible with some work. I'd like to get a bridge to work with my code as well.
Some other options that would be nice include: setting the first day of the week (now is fixed at Sunday) and having the option of showing or selecting days from other months.

I've added the ability to use the console with my status plugin, so you can do

$(console).status({
  run: $.post(url, {data: data}).then(
    function() { return 'Data Saved' },
    function() { return new Error('Data Not saved') }
  )
});


And the output will go to the console rather than to an element on the page.
For simple output to the console, this is far more complicated than console.log, but it works with the rest of the status options. Input is with window.prompt, since I don't know how to get input from the console.

See the demo.
See the source code, which depends on bililiteRange.

Modern browsers won't let synthetic events (triggered with dispatchEvent) execute their default actions (meaning the action that would occur if the event was triggered by a user action). The Event object has a read-only field called isTrusted that is false for anything but unmodified user-initiated events. These are called "trusted events", and I understand the justification, but they go too far. It makes it impossible to implement a virtual keyboard, since triggering keydown or keypress events aren't trusted and won't insert the character (the default action).

Fortunately, bililiteRange and especially bililiteRange.sendkeys can insert characters and do other manipulations on the page. So I created a jQuery plugin that uses bililiteRange.sendkeys to catch keydown events and implement them as well as possible.
Just include the source code and keydown events get a new default handler (so it can be cancelled by preventDefault) that looks at the key field. If it is a single character, that character is inserted at the selection. If it is more than one character long, it is assumed to be a sendkeys command like ArrowLeft and is sent as sendkeys('{'+key+'}').
I used the modern Event.key rather than Event.which, so I don't have to translate keyCodes. If you need to use the old way, see my keymap plugin.

Thus now, $('textarea').trigger({type: 'keydown', key: 'A'}) will work as expected, as will $('textarea').trigger({type: 'keydown', key: 'Backspace'}).

The actual plugin

Under the hood, this uses a very simple jQuery plugin that just calls bililiteRange.sendkeys(). It also turns '\n' in the string into '{Enter}', which I thought would be useful but has actually not turned out that way. Putting the '\n' in braces ('{\n}' prevents the replacement.
The plugin itself is:

$.fn.sendkeys = function (x){
  x = x.replace(/([^{])\n/g, '$1{enter}'); // turn line feeds into explicit break insertions, but not if escaped
  return this.each( function(){
    bililiteRange(this).bounds('selection').sendkeys(x).select();
    this.focus();
  });
};



Demo


$('.selectoutput').click(function(){
	$('.output').removeClass('selected');
	var index = $(this).parents('th').index();
	$('.output').eq(index).addClass('selected').focus();
});
$('div.test input:button').click(function(){
	$('.output.selected').sendkeys($('div.test input:text').val());
});
$('div.wrap input:button').click(function(){
	var tag = $('div.wrap select').val();
	$('.output.selected').sendkeys('<'+tag+'>{selection}{mark}</'+tag+'>');
});
$('.phonepad input').click(function(){
	$('.output.selected').trigger({type: 'keydown', key: this.name || this.value});
});
$('.output').each(function(){
	bililiteRange(this); // initialize the selection tracking
}).on('keydown', function(evt){
	if ($('#overridepad').is(':checked')){
		alert (evt.key);
		evt.preventDefault();
	}
}).on('keypress', function(evt){
	$('#keypress').text($('#keypress').text()+' '+evt.which);
}).on('sendkeys', function(evt){
	$('#sendkeys').text($('#sendkeys').text()+' '+evt.which);
}).on('focus', function(){
	var index = $(this).parents('td').index();
	$('.output').removeClass('selected');
	$('.output').eq(index).addClass('selected')
	$('.selectoutput').eq(index).attr('checked',true);;
});

<div>
	<table style="width: 100%" border="2" id="demo" >
		<thead>
			<tr>
				<th><label>
					<input type="radio" class="selectoutput" name="selectoutput" checked="checked" />
					<code>&lt;input&gt;</code>
				</label></th>
				<th><label>
					<input type="radio" class="selectoutput" name="selectoutput" />
					<code>&lt;textarea&gt;</code>
				</label></th>
				<th><label>
					<input type="radio" class="selectoutput" name="selectoutput" />
					<code>&lt;div contenteditable&gt;</code>
				</label></th>
				<th><label>
					<input type="radio" class="selectoutput" name="selectoutput" />
					<code>&lt;div&gt;</code>
				</label></th>
			</tr>
		</thead>
		<tbody>
			<tr>
				<td><input type="text" class="output selected" /></td>
				<td><textarea class="output"></textarea></td>
				<td><div class="output" contentEditable="true"></div></td>
				<td><div class="output" >This is not editable text</div></td>
			</tr>
		</tbody>
	</table>
<div class="phonepad">
<input type="button" name="ArrowLeft" value="&larr;"/><input type="button" name="ArrowRight" value="&rarr;"/><input type="button" name="Backspace" value="BS"/><input type="button" name="selectall" value="All"/><br/>
<input type="button" value="7" /><input type="button" value="8" /><input type="button" value="9" /><br/>
<input type="button" value="4" /><input type="button" value="5" /><input type="button" value="6" /><br/>
<input type="button" value="1" /><input type="button" value="2" /><input type="button" value="3" /><br/>
<input type="button" value="*" /><input type="button" value="0" /><input type="button" value="#" /><input type="button" name="Enter" value="&crarr;"/>
</div>
<label>Alert on keydown event: <input type=checkbox id=overridepad /></label>
<div class="test"><input type="text" /><input type="button" value="test"/></div>
<div class="wrap"><select><option>em</option><option>strong</option><option>del</option></select><input type="button" value="Wrap Selection"/></div>

<div id="keypress">keypress event.which:</div>
<div id="sendkeys">sendkeys event.which:</div>
</div>
<div style="clear:both" />

The phone pad keys use $().trigger({type: 'keydown', key: key}). The test button does $().sendkeys(textbox.value). The wrap button does $().sendkeys('<tag>{selection}{mark}</tag>'). Note that the trigger code does not affect the non-editable DIV, while sendkeys does.
The "Alert on keydown event" checkbox attaches a handler to the keydown event which calls event.preventDefault, showing that the text entry and keypress events do not occur.

Download the code.

See the demo.

See the hotkeys demo.

Dealing with keydown events is a pain, since the event object has always encoded the key as an arbitrary numeric code, so any program that deals with key-related events has something like:

var charcodes = {
	 32	: ' ',
	  8	: 'Backspace',
	 20	: 'CapsLock',
	 46	: 'Delete',
	 13	: 'Enter',
	 27	: 'Escape',
	 45	: 'Insert',
	144	: 'NumLock',
	  9	: 'Tab'
};

And so on. There is a proposal to add a key field that uses standardized names for the keys, but only Firefox and IE implement that right now. The time is ripe for a polyfill to bring Chrome and Safari into the twenty-first century, and I'd already worked on something similar with my $.keymap plugin.

So I updated that plugin to simply implement the key field in keydown and keyup events. Now just include the plugin and you can do things like:

$('textarea').keydown(function(event){
  if (event.key == 'Escape') { do something useful }
});

Continue reading ‘Rethinking $.keymap’ »

The question came up about using "European" dates (day/month/year) rather than "American" dates (month/day/year) in flexcal. The biggest problem is that the built-in Date.parse() (which is used by new Date(string)) uses the American format, at least with my browsers and settings.

The code in flexcal that does the formatting are in the following methods:

format({Date})
Converts a Date into a String. Used for external formatting: it determines what string is put in the input element after the user selects a date.
_date2string({Date})
Converts a Date into a String. Used for internal formatting: the rel attribute of each day link in the calendar is set with this.
_createDate(d, oldd)
Attempts to coerce d into a Date. If it is a valid Date, just returns that. Otherwise returns new Date(d). If that does not create a valid Date, returns oldd.
this._createDate(this._date2string(d)) must equal d in order for the calendar to work, and this._createDate(this.format(d)) must equal d for the calendar to be able to parse the string in the input element.

So to use European dates, we have to replace each of those methods. I'll use the "dd.mm.yyyy" format.

<input id="eurodate" value="01.02.2014" /> Should start as February first, not January second.

function euroformat (d){
  return d.getDate()+"."+(d.getMonth()+1)+"."+d.getFullYear();
}
$.widget('bililite.euroflexcal', $.bililite.flexcal, {
  format: euroformat,
  _date2string: euroformat,
  _createDate: function (d, oldd){
    // converts d into a valid date
    oldd = oldd || new Date;
    if (!d) return oldd;
    if (typeof d == 'string' && d.match(/(\d+)\.(\d+)\.(\d+)/)){
      d = RegExp.$2 + '/' + RegExp.$1 + '/' + RegExp.$3; // convert to American style
    }
    if (!(d instanceof Date)) d = new Date(d);
    if (isNaN(d.getTime())) return oldd;
    return d;
  }
});
$('#eurodate').euroflexcal();

Someone asked about adding a "today" button/link to flexcal. It's actually pretty simple:

<input id="date1"/>

$('#date1').flexcal({'class': 'multicalendar', calendars: ['en','he-jewish']});
var todaylink = $('<a>Today</a>').attr({
  'class': 'commit',
  rel: $.bililite.flexcal.date2string(new Date),
  title: $('#date1').flexcal('format', new Date),
  style: 'text-decoration: underline; cursor: pointer'
});
$('#date1').flexcal('box').find('.ui-flexcal').append(todaylink);

The key is the todaylink which I append to the calendar (the $('#date1').flexcal('box').find('.ui-flexcal') line). The underlying code uses the rel attribute to determine what day a given <a> in the calendar should go to; use $.bililite.flexcal.date2string(d) to get the right format for a given Date object. The $('#date1').flexcal('format', d) is the displayed format for a given date; you can override that (say to use a European day-month-year format).

The class of the link determines what do to: 'class': 'commit' sets the date in the input box and hides the datepicker; 'class': 'go' would just have the datepicker display that date.