сряда, 28 май 2008 г.

jQuery Equal Columns Plugin


/**
*
* Copyright (c) 2007 Tom Deater (http://www.tomdeater.com)
* Licensed under the MIT License:
* http://www.opensource.org/licenses/mit-license.php
*
*/

(function($) {
/**
* equalizes the heights of all elements in a jQuery collection
* thanks to John Resig for optimizing this!
* usage: $("#col1, #col2, #col3").equalizeCols();
*/

$.fn.equalizeCols = function(){
var height = 0;

return this
.css("height", "auto")
.each(function() {
height = Math.max(height, this.offsetHeight);
})
.css("height", height)
.each(function() {
var h = this.offsetHeight;
if (h > height) {
$(this).css("height", height - (h - height));
};
});

};

})(jQuery);

вторник, 27 май 2008 г.

Preloading Content With jQuery

Preloading Images



For some time there has been a snippet of code floating around the Internet that provides image preloading. To use it add the following function to your site (usually in a separate javascript file):


jQuery.preloadImages = function()
{
for(var i = 0; i < arguments.length; i++)
{
jQuery("<img>").attr("src", arguments[i]);
}
}


To take advantage of this plugin use it in a form like:


$.preloadImages("image1.gif", "/path/to/image2.png", "some/image3.jpg");


Each argument to the function in this comma separated list should be a url to an image to load. It's that easy.

Preloading Content



Let's take this a step further. What if you received some content via AHAH and want to preload the media in that content before presenting it? This is a common use case for images. If this is your case here is a little trick that works. It's a modification of the code above.

First, the plugin code:


jQuery.preloadContent = function(){
for(var i = 0; i < arguments.length; i++)
{
jQuery("<div>").html(arguments[i]);
}
}


Notice the change in the code here? Instead of placing an image path as an src element on an image tag we are taking the content and placing it as html on a div. This will preload the content and, just like with the image plugin, the content will not display at this point.

To use the code do something like:


$.preloadContent(myvar1, myvar2);



In these cases myvar1 and myvar2 are javascript variables that contain the html that needs to be preloaded.

After preloading your content will be cached in the browser and right at your fingertips to use.

четвъртък, 15 май 2008 г.

How to submit multiple form elements having the same name in PHP

In PHP, it is possible to have multiple form elements having the same name. However, the element's name must be appended with "[]".


<input name="hoho[]" value="first element" type="text">
<input name="hoho[]" value="second element" type="text">
<input name="hoho[]" value="third element" type="text">


At the processing PHP, the values of the submitted element can be retrieved as an array via:


$myarray = $_POST['hoho']; // Note that the name does not end with "[]" when retrieving
echo $myarray[0];
echo $myarray[1];
echo $myarray[2];

неделя, 11 май 2008 г.

(Re)Introducing Javascript And Hidden Applets (JAHA)

I borrowed this article for my own safe-keeping as I needed it for one of my projects. Originally, it was posted here http://windyroad.org/2006/08/14/reintroducing-javascript-and-hidden-applets-jaha/

Java applets are so late 90's and so web 1.0, so what place do that have (if any) in the web 2.0 craze?
Overview

You can fairly easily today create an attractive web page using (X)HTML and CSS, but the moment you throw a Java applet into the mix you are asking for trouble. There is a jarring disconnect between the design of your page and the design of your applet. This has never been truer that today, where rounded corners, gradients and fake reflections are all the web 2.0 rage.

The standard look and feel for an applet is driven primarily by the AWT and Swing toolkits and let's face it, they're damn ugly. I don't know of anybody who has praised Java for it's beautiful UIs (those people may exist, but then again there is always people on the net with strange fetishes). It is possible using customised widgets to create applets with the same look and feel as a modern web page, but unless you implement some sort of CSS parser in your applet (let's not go there) any changes to your design will result in a duplicated effort within your applet. With an applet that is heavily tailored to the look and feel of your site, your applet's re-usability on other sites is basically nil. An option that seams to have been overlooked is hidden Java applets. A hidden Java applet is an applet that provides no user interface (UI) and is not visible on the web page. Without a UI the applet no longer creates a blemish on your page, is no longer affected by changes to your page's design and is portable between sites. Interaction with a hidden applet is possible using Javascript and LiveConnect. LiveConnect provides a bridge to access Java from within Javascript and visa-versa. This means you can create your page in normal (X)HTML and CSS, add logic within a hidden applet and use Javascript to capture events to invoke methods on the applet.

The addition of hidden applets to your site allows to provide client side functionality that may not be possible or feasible to implement in Javascript. You may simply want to re-uses an existing library rather than re-implement it in Javascript or you may need more complex IO than is allowed by Javascript. For instance, you may want a page that displays live updating stock prices. Using AJAX you would need to periodically poll the server for updates. Using a hidden applet, you could have an open connection to the server, which it would send updates to as they occur. The applet would simply block on the socket waiting for data and update the page via LiveConnect and Javascript when data was received. Another example would be an applet for uploading a file (such as infomentum's File Upload applet) that additionally (say for performance reasons) compresses the file before it uploads it. Such functionality would very difficult (if not impossible) to implement via Javascript.

Hidden applets are nothing new, but once again we find that an existing technique (combining Javascript and hidden applets) is lacking a name, something that developers can use to know immediately what they talking about. So, in the vain of AJAX and Comet, and similarly lacking a better term, I would like to name the combination of Javascript And Hidden Applets JAHA.

How it's done
Adding hidden applets to your pages should be a fairly simple affair, given that applets and LiveConnect have been around for years. Unfortunately, discovering how to create hidden applets (supporting multiple browsers) has been painful to say the least. If you are not interested in the technical details, skip the the example section. The behaviour described in this article was observed with:
  • IE 6.0
  • Firefox 1.5.0.6
  • Opera 9.01
Whilst preparing a demonstration for this article, I encountered the following issues:
  • If an applet is hidden by using the CSS "display: none;" then it's init and start methods will not be called in Firefox, IE and Opera. Using "width: 0; height: 0;" to hide the applet causes the init and start methods not to be called in IE.

  • If you use Javascript to set the style of the applet to "display: none;" then it's stop and destroy methods will be called in Firefox and Opera. Setting "width: 0; height: 0;" will hide the applet in Firefox, IE and Opera and the stop and destroy methods not to be called.

  • The applet tag has been deprecated in favour of the object tag, yet creating an applet via the object tag quite different in IE compared to other browsers.

  • Creating an applet dynamically by using Javascript to insert an applet element into the DOM, works in IE but not Firefox or Opera.

  • Creating an applet dynamically by using Javascript to insert an object element into the DOM, works in Firefox but not IE or Opera.

  • Adding an applet dynamically using Javascript and document.write apparently works (I didn't bother testing that technique as I don't see much benefit compared to just using the appropriate (X)HTML in your document).
During the preparations, I also managed to crash Firefox numerous times and caused IE to hang on many and occasion. My advice to avoid this suffering is to be very careful and use the example here as a starting point.
Adding a Hidden Applet to Your Page
To include a hidden applet in your page you use something like the following HTML:
     <applet id="applet_name"   
       code="path_to_applet_class/class_name"   
       style="width: 1px; height: 1px; float:  left;"
       mayscript>
   </applet>

Attribute
Description
id
A normal element ID.
code
The location and class name of your applet (do not use a .class or .java suffix)
style
Used to make the applet initially as discreet as possible (we'll make it less visible later)
mayscript
Allows the applet to call out to Javascript.

The equivalent in XHTML is a mess.Sun actually recommends using the applet tag despite it being deprecated and you can see why with the following mess:
     <!--[if !IE]>
   <object id="applet_name"
       classid="java:path_to_applet_class/class_name.class"
       type="application/x-java-applet"
       style="width: 0px; height: 0px; float:  left;">   
<param name="mayscript" value="true"/>   
<![endif]–->   
<object id="ie_applet_name"
       classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93"
       codebase="http://java.sun.com/update/1.5.0/jinstall-1_5_0-windows-i586.cab"
       style="width: 1px; height: 1px; float:  left;">   
<param name="code" value="path_to_applet_class/class_name" />   
<param name="mayscript" value="true" />
<param name="id" value="ie_applet_name" />
</object>   
<!–-[if !IE]>   
</object>   
<![endif]–->
The XHTML 2.0 Working Draft is a lot more specific about how the object tag should be used, so hopefully this issue will disappear in the future though I'm not holding my breath.
In the above code, the outer object is understood by Firefox and Opera, so they ignore the inner object. The conditional comments hide the outer object from IE, so it only tries to create the inner object. You can find out more about this in the article (Multiple Browser Supported) Java applet using XHTML 'object' tag.

In Firefox and Opera the attributes have the following meaning:

Attribute
Description
id
A normal element ID.
classid
The location and class name of your applet, prefixed with java: and including the .class suffix
style
Used to hide the applet
type
Tells the browser that the object is a java applet.

In IE the attributes have the following meaning:

Attribute
Description
id
A normal element ID. To be valid XHTML, this has to be different from the ID used in the outer object.
classid
WTF? Apparently the value above tells IE to use the latest version of the Java plugin. Obviously.
codebase
Tells IE where to find the Java plugin if it is not currently installed.
style
Used to make the applet initially as discreet as possible (we'll hide it properly later)

The parameters have the following meaning:

Parameter
Description
mayscript
Allows the applet to call out to Javascript
code
The location and class name of your applet (do not use a .class or .java suffix)
id
Allows applet running under IE to access the ID of the applet with getParameter("id"). Firefox and Opera automatically pass the ID to the applet as a parameter.

Accessing the Applet from Javascript

To retrieve the applet element from the DOM, you can use document.getElementById('applet_name') . In Firefox and Opera but not IE you can use document.getElementById('applet_name').someMethod() to invoke someMethod. In IE you must use document.applet_name.someMethod(), which can also be used in Firefox, but in Opera you must use document.applets.applet_name.someMethod(). In the example used in this page, I created a global called my_applet, which is initialised to null. Then during the Applet.start() method I call a Javascript function that sets my_applet to reference the applet object. For example:
In Javascript land I use something like:
    var your_applet = null;      
    function appletLoaded(applet)
   {
        your_applet = applet;
       …
   }
and in your applet I have something like:
    public void start()
   {
       Object[] args = { this };
       JSObject.getWindow(this).call("appletLoaded",  args );
   }
Not only does this make it easier for you to access your applet (no branching logic in your Javascript), it also guarantees that within appletLoaded or if your_applet != null your applet has been initialised; i.e. it's safe to call it's methods.
Accessing Javascript from the Applet
From within a Java, the simplest way to communicate with Javascript is via your methods' return values. While this may be sufficient for simple cases, more complex behaviour is available via the netscape.javascript.JSObject class. This class allows you to execute Javascript via:
     netscape.javascript.JSObject.call(String jsfuncname,  Object[] args);
or by using:
     netscape.javascript.JSObject.eval(String js);
The call method will execute the Javascript function jsfuncname with arguments passed in with args. The eval method will call the Javascript eval method on the string that is passed in. To access the netscape.javascript package, you will need to add plugin.jar to your classpath, usually found at JRE/lib/plugin.jar.
Hiding the Applet
Ideally the applet would be hidden by adding "display: none;" to the style of the applet or a parent element. As mentioned earlier, do so will prevent the init and start methods from being called, or if added dynamically, will cause the stop and destroy methods to be called. Strangely, in IE if the applets height and width are initially zero then the init and start methods will not be called, but changing the width and height to zero after the applet as been started will keep it in an active state. Fortunately we can use this behaviour to our advantage, by setting the initial height and width to 1px and then, when the applet is loaded, setting the height and width to zero. Extending the earlier example we can have:
     var your_applet = null;     
     function appletLoaded( applet )
    {
        your_applet = applet;
       document.getElementById( your_applet.getParameter("id")  ).style.width='0';
       document.getElementById( your_applet.getParameter("id")  ).style.height='0';
       …
    }

неделя, 4 май 2008 г.

Java: Removing Any XHTML/XML/JSP/ASP/PHP Tags from a String

String noTags = someHtmlString.replaceAll("\\<.*?>", "");