see whatever…

jump to menu

October 3, 2012

Touch handling in Windows 8 JS app

Filed under: CSS,HTML5,Javascript,Win8 — see @ 9:12 pm

Documentation for handling touch in Windows 8 style (Metro ;) apps with Javascript is not really sparse but nevertheless or maybe because of that a total mess. Lots of decriptions of classes (random links…),  some blog posts, a few samples which all seem very complicated and a few (better) pointers can even be found at StackOverflow (where else ;) .

Guess as until now I only used wrapper libs like Zepto or a few jQuery plugins for mobile touch handling (mostly iOS) which abstract the hard parts away I expected the code to handle a simple swipe left/right to be simpler.

After playing around a few hours, being lost in the depths of the Microsoft docs I came up with this:

 // define GestureRecognizer
 var recognizer = new Windows.UI.Input.GestureRecognizer();
 recognizer.gestureSettings = Windows.UI.Input.GestureSettings.manipulationTranslateX
 recognizer.addEventListener('manipulationcompleted', function (e) {
   var dx = e.cumulative.translation.x
   // **actually do something, left or right defined by dx > 0 or < 0**
 });

 // actual element which feeds the GestureRecognizer
 var processUp = function (args) {
   try {
     recognizer.processUpEvent(args.currentPoint);
   }
     catch (e) { } // translateYfails ?!
   }
 var swiper = document.querySelector('.swipearea')
 swiper.addEventListener('MSPointerDown', function (args) {
   try {
     recognizer.processDownEvent(args.currentPoint);
   }
     catch (e) { } // translateYfails ?!
   }, false);
 swiper.addEventListener('MSPointerMove', function (args) {
   try {
     recognizer.processMoveEvents(args.intermediatePoints);
   }
     catch (e) { } // translateYfails ?!
   }, false);
 swiper.addEventListener('MSPointerUp', processUp, false);
 swiper.addEventListener('MSPointerCancel', processUp, false);

All in all and in the end almost logical. You preprare a GestureRecognizer and feed it with events from a DOM element. This actually seems capable of doing lots of much more advanced stuff but for a simple swipe left/right gesture seems almost overkill. I wonder if there is something simpler?

In addition I do not understand why the recognizer feeding methods like recognizer.processUpEvent do actually raise an exception if in the above case a up/down swipe is used. One reason is that the element actually has a normal overflow, so the normal scrolling works there. This is the reason the recognizer is set up to only actually handle manipulationTranslateX gestures. But why the additional exceptions?

Anyway, the above seems to work (at least on my desktop and the simulator with both Mouse and BasicTouch mode). Not the simple stuff I have hoped for but maybe I did it all too complicated? Any hints are very much appreciated :)

August 7, 2010

HTML5 canvas API chainable (jQuery like)

Filed under: HTML5,Javascript — see @ 7:01 pm

While playing around with HTML5 canvas (with jQuery on the page) I noticed the rather tedious writing of

canvas = $('canvas')
ctx canvas.get(0).getContext('2d')
ctx.dothis...
ctx.dothat...

So I thought a jQuery like chaining syntax would be nice. Only first try but it seems actually quite simple. Code I came up with:

function jqContext(canvas) {
	function jqContext(canvas) {
	/* Canvas 2D Context wrapper allowing jQuery like chaining */
	var self = this
	self.context = canvas.get(0).getContext('2d')
	
	// wrap properties of context chainable, without argument
    // returning current value, with argument setting value
	$(['fillStyle'
	   ,'font'
	   ,'strokeStyle'
	   ,'textAlign' ,'textBaseline'
	   ,'mozImageSmoothingEnabled'
	]).each(function() {
		 var property = this
		 self[property] = function(a) {
		  	 if (a != undefined) {
		 		 self.context[property] = a
				 return self 
			 } else {
				 return self.context[property]
			 }
		 }
	})
	// wrap methods of context
	$(['arc',
	   'beginPath', 'closePath'
	   ,'drawImage' //?
	   ,'fillText', 'strokeText'
	   ,'lineTo'
	   ,'moveTo',
	   ,'fillRect', 'strokeRect', 'clearRect'
	   ,'stroke'
	]).each(function() {
	    var method = this
	    self[method] = function() {
		    self.context[method].apply(self.context, arguments)
		    return self			
	    }
    })
	// wrap methods of context NOT chainable
	$(['createLinearGradient'
	]).each(function() {
	    var method = this
	    self[method] = function() {
		    return self.context[method].apply(self.context, arguments)
	    }
    })
}

So now I can write:

c = $('<canvas></canvas>').appendTo('body')
c.css({
	width: 800,
	height: 400,
	border: '1px solid #ccc'
})

x = new jqContext(c)
x
.strokeStyle('#f00')
.strokeRect(0,0, 100, 100)
.fillRect(40,50, 100, 100)
.clearRect(70,50, 80, 100)

Don’t know if worth the effort and only a test (not complete at all obviously) but fun ;)

UPDATE: Improved the class a bit, calling a property wrapper with no value returns the current value now, also added a few more methods…

November 10, 2007

@media ajax

Filed under: Javascript,Programming — see @ 1:07 pm

I will be at @media ajax from 19-20 November in London. Really looking forward to it :)
@media ajax

Javascript is besides Python one of my favourite languages. Especially with libs like jQuery which (only partly of course) seem to be influenced by Python. Despite having Java in its name Javascript feels much nearer to Python then to Java.

September 27, 2007

closures in Python

Filed under: Javascript,Python — see @ 9:58 pm

Written quite a while ago but but still a very good post about how closures in Python work. Basically they are read-only so if you need to mutate a value you need to use a mutable variable like a list or object.

Closures in e.g. Javascript are easier – ah wait, actually I am not quite sure if I actually did change a value the last time I just a closure…

- just checked, it does work as expected (thanks to Firebug, I guess that’s why I like both Javascript and Python, both with a great console ;) ):

>>> a = 1
>>> function b() { alert(a); a = 2}
>>> b() // alerts 1
>>> b() // alerts 2
>>> a
>>> 2

I do quite like to work with closures, working with Ajax callbacks is almost only possible by using them. I did try to use the same technique in cssutils and of course failed miserably until I found the above post and workaround. So all in all better than nothing. I wonder though if it would be very difficult to add “proper” closure support to Python, guess a simple syntax is the most difficult…

July 9, 2007

What is allowed in a URL parameter name?

Filed under: Javascript,Web — see @ 9:50 pm

I am wondering what actually is allowed in a URL parameter name? Skimming RFC 3368 does not really gave me a proper answer (probably I am not reading properly enough though). But as far as I understand it any character should be allowed if escaped (if necessary). So an URL like http://www.example.com?@ref=5 should work, and also parameter names like “öäü€” should work if escaped, which would look like http://www.example.com?%C3%B6%C3%A4%C3%BC%E2%82%AC=5

I tried that in a simple Tomcat servlet and also a simple PHP page, both give the correct anwer, if asking I got the respective parameter value by its name.

Question is if that is like it should be or if both are simply very forgiving?

A real edge case would be a parameter name like “[a='1']” which would look URL encoded like: http://www.example.com?%5Ba%3D1%5D=5

Should that actually work? At least a browser does not seem to escape this properly, if putting this into a HTML form like <input name=”[a='1']“>. But using Javascripts encodeURIComponent() function does result in the above escaped version, which should work when sending the form via Ajax (still need to try that out) (and in this case Ajax would be ok as its not an open web page).

Does anyone know if the above assumption are correct and a complete and proper escaping of parameter names should work?

BTW, this is not just a quest for knowledge ;) but I tried to use former XPath expressions as parameter names to use them later on the resulting values. Maybe a bit strange but so I may have parameter names like x[@y='5']…

April 29, 2007

jQuery and crossbrowser compatibility

Filed under: Javascript,Web — see @ 7:30 pm

Sadly jQuery has dropped full support for IE lower version 6. Until now I thought that was the edge that jQuery had compared to other libs like Prototype and the like (of course not the only one as I still do like the general API and easyness of jQuery). I do understand the reasons for this step though so this is only a minor complaint ;)

I myself tripped into at least two issues of newer versions of jQuery with IE 5.5, the first is really nasty, the second (which I reported myself) is rather unimportant as it will trip in certain special cases only I guess.

The consequence will probably be that I change my attitude regarding which browsers to support of at least the sites I am able to decide for and the ones I am able to be consulted for. IE 6 is quite a hassle (CSS etc.) already, so support for even lower IEs – also compared to their current usage (which of course gets only lower ;) – is really not a very important issue anymore.

Only problem will be major corporate sites or specific customers who need to support e.g. IE 5.5. There is hardly any major JS lib around with support for these old browsers and working without one these days does not really make sense. Writing your own lib is also kind of out of the question (in most cases “out of budget”).

Or is there a decent JS lib with support for old browsers? (I do not really expect lots of votes here though).

BTW, a strange thing I noticed in the stats for my own sites (e.g. this one). Since there is a bit more traffic on the site (due to the mention of my own cssutils on the W3C site) IE 5.5 is actually the browser most visitors have (or pretend to use ;) . With about 28% it is used much more often than the 2nd (IE 6[!] with about 13,5%) and 3rd (finally Mozilla 5.0 with about 12,5%). Maybe some robots or “feed fishers” set their UA to IE 5.5 and so the stats is not in sync with actual reality… Still I do wonder what the real reason is, before (with lower traffic) the stats were showing Mozilla leading with almost 30% and IE 5.5 with a meager 0.5% usage, very strange…

March 3, 2007

Ajax history

Filed under: Javascript,Programming,XML,XSLT — see @ 12:10 pm

I added Ajax functionality to parts of my showcase website cdot.de namely to most of the galleries (like the photo or portrait gallery) a while ago. The galleries are build using a simple homegrown gallery XML format which is rendered with XSLT. Adding the Ajax functionality was not very difficult, I use the fine JQuery library for that. (I still have to migrate my own scripts of the past years to use JQuery which should make most of them obsolete but also easier to use and also much shorter ;) .

Adding a working browser history to it was not as easy as expected though. I simply did not understand how to bring the available JQuery history plugins to work. The whole matter is not easy but not too difficult and to better understand what is going on I decided to build my own history (but still using JQuery of course).

First try was to use the URL hash method which does work perfectly on Firefox, but not on IE (for reasons query Google for “ajax history”, several interesting sites describe the problems much better than I can). The “hack” using dynamic built iframes does work xbrowser (at least Firefox and IE, Safari is a different beast [as far as I understand no working possibility yet at all], I did not test Opera yet) so I changed the implementation to use iframes instead.

It does work now, only missing bit is bookmarking which would be possible if I added the URL hash in addition to the iframe hacking. I may add it in the future, it is not a very important issue for the use case on the galleries though as they are too simple to actually need bookmarking on single works in one gallery (there is always an overview). More applicationary sites would need that though.

BTW, during testing I found a bug (at least I think it is one) in JQuery which was very hard to track down. Most people probably won’t be affected by it but for people using REST it might be quite relevant.

Basically IE below version 7 seems to use POST for all Ajax requests if initialized with the wrong ActiveX control. The servlet I wrote for my galleries implements GET only so it resulted in a “Method not implemented” HTTP error which I never saw before (as most servlets use the same implementation for GET and POST, which is even recommended by most books but maybe it is not too intelligent anymore) and did not know where it may came from. Tracking it down was not easy as I normally use all the fine Firefox plugins like Firebug or LiveHTTPheaders which simple are of no use debugging IE ;)
But I came accross Fiddler some time ago which actually tracks all HTTP traffic on a PC. So after checking that I saw that IE used POST for its Ajax requests which of course failed on a servlet implementing GET only…

November 9, 2006

JQuery and IE7

Filed under: Javascript — see @ 10:50 pm

Seems JQuery is IE7 compatible. I have a few glitches in IE7 on my private site for which I had no time to fix yet. I also wanted to try out JQuery for some time now, again a lack of time. At work I had a chance to do some tryouts for a projects and also found this great documentation for JQuery. So I started adjusting the scripts on my personal site to use JQuery. At least for the first problem I tackled it was easy and fixed the problem.

I actually have quite a lot of self-written scripts on my site for some years now which could have been build into a library I guess but I never came around actually doing it. I think I was more interested in other things (XML, Python) in the last years and ignored Javascript for the time. But in hindsight the stuff is not really that bad, e.g. I have a kind of effects lib for opening popups (sliding, moving, centered etc). This could be transferred to a JQuery plugin or at least application I guess.

Anyway, first I need to redo all scripts with JQuery, which does seem to simplify and shorten scripts quite a lot…

UPDATE:

I fixed all bug I knew with a few tweaks in my scripts using JQuery methods, mostly its excellent “dimensions.js” plugin which gives access to browser information like document or window height, width etc. I had a build a few methods myself for these kind of information but IE7 broke a few. IE6 was annoying enough I remember now as it handles even standards and quirks mode different in its DOM information. So much easier to use a lib like JQuery instead of hacking around in a script that actually hinders one doing the nice stuff…

September 2, 2006

and switching programming languages

Filed under: Java,Javascript,Jython,PHP,Programming,Python — see @ 11:18 pm

In Reqiem for an operator Barry Warsaw farewells the <> operator which will be removed in Python 3000. I have no real opinion on the topic itself although I think <> and != are one of the few not TOOWTDI things in Python and so a reasonable decision to remove one. But the followoing question in the same blog entry got me thinking:
“How often do you type semicolons at the end of your Python statements? How often do you type colons at the end of your C conditionals? Yeah, me neither.”

Actually I do tend to forget colons in Python after programming a while in Javascript or PHP, and I do forget using braces in e.g. “if” clauses in Javascript or PHP or Java after programming in Python for a while. Actually I forget to use a lot of things in other languages that are not needed in Python like () {} ; etc. What really made me nervous was building a simple JSP form this week where I had to use Java and I almost got angry about all the stuff I had to type which would have not been necessary if it would have been a Python or even Jython form. All the declarating, casting, complicated and verbose looping etc was simply a nervekiller.

So I guess getting rid of <> in Python in favor of != makes language hopping at least a bit easier.

About the only thing I sometimes wish for Python would be the removal of mandatory colons at the end of if, for, class, def etc. I guess this would make parsing of Python sourcecode impossible or at least “indeterminable” (is that an english word?). But the colon is one of the few places where a special character makes the code not more readable but a bit convoluted. Not a big problem as the parser complains about missing colons (which I see frequently ;) .

BTW, this post is somehow related. It makes me like the language even more as there still seems to be space for a bit of fun.

July 31, 2006

jquery tryout

Filed under: Javascript — see @ 9:00 pm

Today a colleaque at work asked for help on a small HTML/CSS problem, namely a design causing a bit of a headache. The underlying HTML coming from a CMS meant no possibilities of starting from there and using a CSS solution only proved not possible.

So I suggested using a bit Javascript DOM magic – actually to just insert a br or a surrounding div in this case. This would solve the problem rather nicely while being still fully usable for people with Javascript disabled (really just a small design wish, effective but not content relevant).

Writing the small script by hand would not have been a big problem but as it was for a mock-up only and I wanted to try out jquery anyway I wrote the script using that “framework”. Framework is just too big a word for such a small library which nevertheless is very powerful and because of its smallness very easy to use and write. It took only about 10 minutes to find the relevant calls in the API documentation and putting the script together which ended up being just a 3 liner…

I knew jquery was good and even suggested it to another colleaque some time ago to use in a big project we work on together but never had the time to actually use it myself. Now I know it was the right suggestion ;)

Older Posts »

Powered by WordPress