Safely adding events to DOM elements in Javascript for IE, Firefox, Opera and Safari
Posted by jimblackler on Sep 29, 2007
Recently I looked into some reported problems with my word game site Qindar.net and the Safari browser. This was a bit easier for me since Apple released a Windows version of Safari (which, albeit arguably surplus to requirements, is actually a very nice, usable browser on Windows).I discovered that the technique I was using to work out which method of event attachment to use was flawed and was failing for Safari. So I refined it slightly to fix the problem.
The problem is that Javascript on Firefox, Opera and Safari support the “W3C DOM Level 2 event binding mechanism”, which uses a function on DOM elements called addEventListener. Internet Explorer however uses a technique that was apparently from before that particular standard was drawn up, employing a function called attachEvent. In addition, the names of the events are different. For instance, IE uses events such as “onmousemove”, “onmouseup”, but the other browsers omit the “on” and name these events “mousemove” and “mouseup”.
Curiously, Opera is the only browser to support both styles.
The simplest and safest way of working out which one to use is simply to test for the existence of a function called addEventListener. I quite like this method because it works on the latest version of the big four browsers, and IE 6, without having to do any browser version probing.
For instance, here is how to add focus and focus lost events to a page in a way that will work on all modern browsers:
[Javascript]
if (window.addEventListener != null)
{ // Method for browsers that support addEventListener, e.g. Firefox, Opera, Safari
window.addEventListener(“focus”, FocusFunction, true);
window.addEventListener(“blur”, FocusLostFunction, true);
}
else
{ // e.g. Internet Explorer (also would work on Opera)
window.attachEvent(“onfocus”, FocusFunction);
document.attachEvent(“onfocusout”, FocusLostFunction); //focusout only works on document in IE
}
[/Javascript]
This is how to add mouse events:
[Javascript]
if (document.addEventListener != null)
{ // e.g. Firefox, Opera, Safari
document.addEventListener(“mousemove”, MouseMoveFunction, true);
document.addEventListener(“mouseup”, MouseUpFunction, true);
}
else
{ // e.g. Internet Explorer (also would work on Opera)
document.attachEvent(“onmousemove”, MouseMoveFunction);
document.attachEvent(“onmouseup”, MouseUpFunction);
}
[/Javascript]
To remove the mouse events, I recommend…
[Javascript]
if (document.removeEventListener != null)
{ //e.g. Firefox, Opera, Safari
document.removeEventListener(“mousemove”, MouseMoveFunction, true);
document.removeEventListener(“mouseup”, MouseUpFunction, true);
}
else
{ //e.g. Internet Explorer (also would work on Opera)
document.detachEvent(“onmousemove”, MouseMoveFunction);
document.detachEvent(“onmouseup”, MouseUpFunction);
}
[/Javascript]
I personally pray there comes a time when these kinds of workarounds are not required. In the mean time, this will have to do.
Scraping text from Wikipedia using PHP
Posted by jimblackler on Sep 25, 2007
Wikipedia has grown from one of many interesting websites to being one of the most famous sites on the Internet. Millions of volunteer years have been invested over the years, and the pay off is what we have today – a wealth of factual data in one place.
When Wikis were a new concept, many predicted they would descend into chaos as they grew. In the case of Wikipedia the reverse is true. It seems to become increasingly well organised as the site develops. Rather than becoming more jumbled, the natural development of article conventions and the more planned use of standardised templates has created an increasingly neat and consistent structure.
This careful organisation of the prose leads to the interesting possibility of extracting more structured data from Wikipedia for alternative purposes, while staying true to the letter and spirit of the GFDL under which the material is licensed.
There’s the potential for a kind of semantic reverse engineering of article content. HTML pages could be scraped, and pages scoured for hints as to the meaning of each text fragment.
Applications could include loading articles about a variety of subjects into structured databases. Subjects for this treatment could include countries, people, chemical elements, diseases, you name it. These databases could then be searched by a variety of applications.
I’ve knocked up a simple page that gives a kind of quasi-dictionary definition when a word is entered. It looks at the first sentence of the Wikipedia article, which typically describes the article topic concisely.
I’ll show here how the basic page scrape works, which is actually very easy with PHP, its HTML reading abilities and the power of xpath.
- $html = @file_get_contents(“http://en.wikipedia.org/wiki/France”); will pull down the HTML content of the Wikipedia article on France.
- $dom = @DOMDocument::loadHTML($html); will read the HTML into a DOM for querying.
- $xpath = new domXPath($dom); will make a new xpath query.
- $results = $xpath->query(‘//div[@id=”bodyContent”]/p’); will find the first paragraph that is a direct child of the div with the id “bodyContent”. This is where the article always starts in a Wikipedia article page.
I then perform some more processing on the results including contingencies for if any of the steps fail. For instance to make the definitions snappier reading I strip any text in brackets, either round or square. There’s also some additional logic to pick the first topic in the list if the page lists multiple subjects (a “disambiguation” page). Predicting the Wikipedia URL for a given topic also involves a small amount of processing.Anyway, when you ask the page “what is France”, it will reply..
France, officially the French Republic, is a country whose metropolitan territory is located in Western Europe and that also comprises various overseas islands and territories located in other continents.
Can’t argue with that!
Edit, 1st March: By request, here is the source of the WhatIs application. It will work in any LAMP environment but the .sln file is for VS.PHP under Visual Studio 2005.
Overriding the backspace key using JavaScript, in Firefox, IE, Opera and Safari
Posted by jimblackler on Sep 21, 2007
In my web wordgame Qindar.net I wanted to allow the players to use the keyboard to place words on the game board. This included use of the arrow keys to navigate, and the backspace key to ‘delete’ wrongly placed letters.
The problem is that even when this is handled in JavaScript, most browsers still catch the backspace key and interpret it as a user request to go back to the previous page. Boom! There goes your game page, and one annoyed user.
I did find a way of masking the backspace key that works in all the browsers I have tested it against. The trick for most browsers is to override the onkeydown event, check for event number “8” and return ‘false’ from that event. This signals to the browser not to process that key.
As often happens one particular browser is troublesome, in this case it was Opera, that needed “onkeypress” overriding rather than “onkeydown”.
Yesterday I had an email query recently asking how this was done so I’ve detailed it here.
There’s a demo here. Select ‘View Source’ in your browser to see how it’s done.
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <html xmlns="http://www.w3.org/1999/xhtml" >
- <head>
- <title>Backspace Browser Trap Demo</title>
- </head>
- <body>
- <p>Try pressing backspace on this page.</p>
- <p>Note you can still go 'back' with Alt + Left</p>
- <p id="keypressed"></p>
- <script type="text/javascript" language="javascript">
- // function to possibly override keypress
- trapfunction = function(event)
- {
- var keynum;
- if (window.event) // eg. IE
- {
- keynum = window.event.keyCode;
- }
- else if (event.which) // eg. Firefox
- {
- keynum = event.which;
- }
- if (keynum == 8) // backspace has code 8
- {
- document.getElementById("keypressed").innerHTML = "Backspace pressed";
- // display a message
- return false;
- // nullifies the backspace
- }
- return true;
- }
- document.onkeyup = function(event)
- {
- document.getElementById("keypressed").innerHTML = ""; // clear the message
- return true;
- }
- document.onkeydown = trapfunction; // IE, Firefox, Safari
- document.onkeypress = trapfunction; // only Opera needs the backspace nullifying in onkeypress
- </script>
- </body>
- </html>
Flash card Scrabble learning quiz game for PalmOS
Posted by jimblackler on Sep 18, 2007
Two of my hobbies are programming, and trying to improve my Scrabble performance by cramming all the playable short words into my brain. It seems natural that I’d try to combine the two activities.
Five years on my Clie isn’t so shiny any more (in fact it finally died about a year ago after many years fine service). I’m still a Scrabble player, but this time I use a Windows Mobile smart phone for learning on the go. That’s nice because I can use a common .NET library for my dictionary utilities. On that subject, the Scrabble community has changed the official word list to CSW (Collins Scrabble Words) which required every word tool or game to be updated.
So wquiz has become obsolete. Which leads me on to the point of this post. Having given the program to a few people here and there it appears to have developed a miniature but vocal following. One good friend of mine in particular has been politely asking me to update it for him for a while. I declined because I don’t have the Clie any more and I lost the SDK. But when he started offering to pay me I knew he was serious.
Anyway I dusted out the SDK (Metrowerks for PalmOS), fired up the emulator, got the dictionary list out and viola, here is the mighty “wquiz”, 2007 style, for CSW. I’ve linked it here as a .prc file, I think the PalmOS software will install it for you if you open it from your browser. Enjoy.
Developing LAMP applications on a Windows PC
Posted by jimblackler on Sep 13, 2007
If you’re developing web applications for inexpensive hosting there’s really only one option. LAMP stands for Linux, Apache, MySQL and PHP. It represents a set of technology that’s reliable, battle-tested and totally ubiquitous in the world of web hosting.
Bit like lots of developers you might be working on a Windows computer, using Microsoft software like Visual Studio. This doesn’t feel like the most natural environment for developing for a LAMP setup. There’s a definite draw towards IIS, ASP and MSSQL, the Microsoft alternative to LAMP. This Microsoft tech has a different set of strengths to LAMP, but look for compatible hosting and you’ll find it’s typically twice the cost.
Fortunately you can and it’s not too difficult if you know what to install. A great free package called WampServer will set up and integrate Apache, MySQL and PHP in one go. What’s WAMP? It’s Windows Apache MySQL PHP. The bastard lovechild of two different schools of technology? Or a pragmatic way of combining the most common hosting technology with the most common desktop technology. You decide.
WampServer is ideal for developing on Windows before uploading your site to your Linux-based host. WAMP also comes with some nice configuration menus and the phpMyAdmin web console for MySQL. Get it here, and you can get started by putting the following index.php file in c:\wamp\www and pointing your browser at http://localhost.
<?php echo "hello world"; ?>
Visual Studio
How about using Visual Studio to develop and debug? I can recommend a product called VS.PHP that allows development of PHP applications within Visual Studio. It’s commercial, but it’s relatively cheap and there’s also a free trial available here. VS.PHP has its own Apache service and works very nicely out of the box. However you can configure the system to use WAMP’s Apache if you want to run your application alone or with other tools such as Dreamweaver.
Once you’ve installed VS.PHP and set up a project, this is how to set up debugging to use WAMP 1.7.3. These instructions assume that you store the project files and Visual Studio project files in a location such as c:\wamp\www\myproject, where myproject is the name of your project.
- Download the php_dbg modules.
- Copy the version for PHP 5.2.4. to C:\wamp\php\ext and rename it to php_dbg.dll.
- In the WAMP system tray menu select PHP setting, PHP extensions, Add extension, and type php_dbg.dll.
- From the WAMP menu Select Config files, and then php.ini.
- Put the following lines at the bottom of your php.ini:
- Under the Resource Limits section of php.ini change memory_limit = 8M for memory_limit = 32M. (Debugging needs more memory).
- Save your modified php.ini and restart WAMP from the system try menu.
- In the properties of your VS.PHP project, select Debug then change Debug mode to External mode.
- Change the Start Url to http://localhost/myproject/index.php, changing myproject to the name of your project.
[debugger]
debugger.enabled = true
debugger.profiler_enabled = true
debugger.JIT_host = clienthost
debugger.JIT_port = 7869
You should now be able to set breakpoints and step through your WAMP-based PHP applications with Visual Studio.
Design
Adobe Dreamweaver is a very popular package for web design and also offers some nice visual tools to create simple data enabled pages. Unfortunately it defaults to use IIS on Windows. However if you’ve installed WAMP you can configure Dreamweaver to use its services. Combined with the previous approach this will give you a combined LAMP-ready debugging and design environment on a Windows computer. These instructions are for Dreamweaver CS. Again, I assume that you store the website files in a location under c:\wamp\www such as c:\wamp\www\myproject.
- Select Manage Sites
- In the HTTP Address box type http://localhost/myproject/index.php, changing myproject to the name of your project.
- Select Next, and under the server technology select PHP MySQL.
- Select Edit and Test locally.
- Under the file location type C:\wamp\www\myproject\ (again, changing myproject ).
- Select Next. Under the Root URL type http://localhost/myproject/ (again, changing myproject ).
- Select Next twice, and then Done.
In Dreamweaver you can make use of the WAMP MySQL service to develop MySQL integrated Recordsets. You can also make use of the simple wizards in Dreamweaver to create HTML/PHP/MySQL log in services. Use the phpMyAdmin web admin under WAMP to set up a database, tables and a user for Dreamweaver to connect to. Then copy these details – alongside “localhost” as the MySQL server – in the Recordset configation windows in Dreamweaver.
In conclusion
So that’s it. You should be good to go for LAMP development on your Windows PC. Remember that your host is likely to have a different configuration of Apache and PHP with different versions, modules enabled and so on. Fortunately WAMP makes it quite easy to configure your local setup to match your host. Also look out for the fact that Windows isn’t cASe SenSItiVE at all on filenames, and this extends to Web hosting. Linux services generally are case sensitive by default. So if the live version of your application has problems locating files, that might be why.
Happy WAMPing!
FastGallery
Posted by jimblackler on Sep 11, 2007
I’ve recently published a Windows application that I wrote in .NET 2.0 (WinForms) to simplify the creation of HTML photo albums for putting on the web. I call it FastGallery, and it can be found … here.
I know there are a lot of similar apps out there, but I really wanted something that was very fast and simple to use. It also makes use of some of the special .NET controls I’ve been developing.