Showing posts with label CSS. Show all posts
Showing posts with label CSS. Show all posts

Sunday, March 13, 2016

Front-End Interview Questions and Answers


I have finished answering the Front-end-Developer-Interview-Questions, please refer to the answers at my git repo.

In my opinion, not only for interview, they really contains useful information/knowledge for Front-End/Full-Stack developers.

Hope this helps.

Friday, December 4, 2015

Monday, February 16, 2015

Add SyntaxHighlighter to Blog Post in One Minute

1. Edit your blog template.

2. Find the
tag.

3. Paste the fragment below before the tag you found above
(NOTE: this is my custom helper and will load js from my github cdn,
 you can modify it to create your own as needed)

4. Save template

Done

(It seems there is an autoloader feature but that page not works well so
I wrote my own.)

References:

My testing files

SyntaxHighlighter-themes

SyntaxHighlighter-configuration

Thursday, April 3, 2014

ZK, AngularJS and Pure HTML Template


Introduction

As we already know ZK used to generate all html content within 'redraw' function of a ZK Widget, this is a little bit (?) hard to maintain and customize dom structure and style of component.

This article describe how to create ZK Component with AngularJS Directive so you can use a pure HTML template to generate dom elements of ZK Component and has some advantages:
1. Easier to maintain.
2. Easier to customize.

And also some drawbacks (part of them has workaround):
1. Need to load html template via several ajax call.
  Workaround: You can load all templates at once,
       for more information please refer to
       AngularJS: load all templates in one file or AngularJS Merge Template
2. Will blink while rerender, you can use a fake dom to avoid blinking but this may affect the client side performance.
3. Has issue of dynamically insert and compile complex dom elements so need to rerender if dynamically add children.

Note:

1. This is just a POC done in a short time, probably not well organized and has some unknown issues.
2. I am not familiar with AngularJS so this POC may contains bad practice.

Pre-request

AngularJS Create Components

ZK Component Development Tutorial: Getting Started

ZK CDT: Fire Event to Server to Create a SelectableTextNote

Result

Online demo
http://screencast.com/t/nlLsNdbV8A

Description:

The concept is simple.

In AngularJS, a directive which support pure html template is a function that returns an Object Literal, and registered with a specific name (see Creating Custom Directives).
Both of them -- the name and the function -- can be declared at any places.
e.g. inside the Javascript of ZK Widget.

So we can specify Angular Tag (ngTag) and Angular Template Url (ngTemplateUrl) to each ZK Component and do below:

In ZK Component:
* Server Side:
** Make sure that each templateUrl maps to different tag.
* Client Side:
** Output ngTag in redraw function.
** Store component to zk.ngcomponents in redraw function.
** Register Angular Directive with ngTag.

In Angular Directive
* Use ngTemplateUrl as templateUrl in directive.
* Store $scope, $compile and controller to $element in controller function of directive.
* Bind ZK Widget with Angular Objects above in link function of directive.

Then we can use AngularJS Directive with pure HTML Template then control ZK Widget from AngularJS Directive and vice versa.

See

NgComp.java#fixTemplateMapping
NgComp.js#redraw
tabs.js#registerTemplate
zacomponents.js#addComponent
zacomponents.js#storeNgObjects
zacomponents.js#directive
zacomponents.js#bindng_

for more information.

Program Introduction

Testing zul page
index.zul

Testing Composer
TestComposer.java

AngularJS Library
angular.min.js

Bootstrap3 CSS Library
bootstrap.min.css

Utils for AngularJS ZK Widget
zacomponents.js

Basic APIs of AngularJS ZK Widget
NgComp.js

The Folder Contains All Default Templates
templates

Basic Java Class for AngularJS ZK Component
NgComp.java

Others:
Please refer to the full project below

Download

Full project at github

Demo Flash (click View Raw to download)

Tuesday, March 11, 2014

JSP Fileupload Progress Bar


Simple Note

JSP fileupload with Apache Commons FileUpload
Display upload progress bar

Pre-request

JSP Fileupload without Redirect/Refresh

Full Project

https://github.com/benbai123/JSP_Servlet_Practice/tree/master/Practice/Tools/FileUpload

Testing files

WebContent/fileupload_progressbar.jsp
src/test/UploadProgressServlet.java

Sunday, November 10, 2013

Font Awesome Getting Started


Simple Note

Result



Steps

1. Go to official site http://fontawesome.io/

2. Download and extract file to target folder

3. Follow Getting started page (http://fontawesome.io/get-started/), create html page

4. See icons page (http://fontawesome.io/icons/), write some icons and see whether it works well.

Download

Testing folder at github
https://github.com/benbai123/HTML_CSS_Javascript_practice/tree/master/bootstrap/font_awesome/getting_started

Saturday, November 9, 2013

Bootstrap Getting Started


Simple Note

Steps

0. Preview official Getting started page (http://getbootstrap.com/getting-started/)

1. Go to github page of bootstrap (https://github.com/twbs/bootstrap) and download latest release (see Quick start section at that page)

NOTE: For some reason the download link at official site (http://getbootstrap.com/) not works for me.

2. Unzip downloaded file and copy dist folder into target folder.

3. Copy an official example (e.g., http://getbootstrap.com/examples/signin/) to see whether it works.

Done.

References

Bootstrap Getting Started
http://getbootstrap.com/getting-started/

Bootstrap github
https://github.com/twbs/bootstrap


Download

Testing folder at github
https://github.com/benbai123/HTML_CSS_Javascript_practice/tree/master/bootstrap/getting_started

Sunday, October 27, 2013

Compile LESS with Java


Simple Note

From official site:
For production and especially if performance is important, we recommend pre-compiling using node or one of the many third party tools.

This article describe how to compile .less file to .css file in java code on server start-up.

Pre-request

LESS Getting Started
http://ben-bai.blogspot.tw/2013/10/less-getting-started.html

Do Something on Server Startup/Shutdown
http://ben-bai.blogspot.tw/2013/10/do-something-on-server-startupshutdown.html

Result

The same as the result in previous post.

Required jars

lesscss-engine-1.3.3.jar
http://mvnrepository.com/artifact/com.asual.lesscss/lesscss-engine/1.3.3

rhino-1.7R4.jar
http://mvnrepository.com/artifact/org.mozilla/rhino/1.7R4

commons-logging-1.1.1.jar
http://mvnrepository.com/artifact/commons-logging/commons-logging/1.1.1

Code

test.less

Copied from previous post, nothing changed.

https://github.com/benbai123/JSP_Servlet_Practice/blob/master/Practice/LESS/CompileLESSWithJava/WebContent/resources/less/test.less

less_test.html

Modified from previous post, load compiled css file instead of less file and do not load less.js.

https://github.com/benbai123/JSP_Servlet_Practice/blob/master/Practice/LESS/CompileLESSWithJava/WebContent/less_test.html

TestServletContextListener.java

Implements ServletContextListener, will compile less file to css file on server start-up.

package test;

import java.io.File;
import java.io.IOException;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import com.asual.lesscss.LessException;

import test.util.LESSUtils;

public class TestServletContextListener implements ServletContextListener {
    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        // do nothing on server shutdown
    }
    // compile less on server startup
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        try {
            String webContentPath = sce.getServletContext().getRealPath("/");
            LESSUtils.compile(new File(webContentPath + File.separator + "resources" + File.separator + "less" + File.separator + "test.less"),
                    new File(webContentPath + File.separator + "resources" + File.separator + "css" + File.separator + "test.css"));
        } catch (LessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}


LESSUtils.java

Contains utility function to compile less file, say Utils means (probably) will add more functions in future work.

package test.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

import com.asual.lesscss.LessEngine;
import com.asual.lesscss.LessException;

public class LESSUtils {
    public static void compile (File lessFile, File cssFile) throws LessException, IOException {
        if (lessFile == null 
                || !lessFile.exists()) {
            // less file should exist
            throw new FileNotFoundException("LESS file not exists !");
        }
        // create less engine
        LessEngine engine = new LessEngine();
        if (!cssFile.getParentFile().exists()) {
            // create folders for css file
            boolean cssFileCreated = cssFile.getParentFile().mkdirs();
            if (!cssFileCreated) {
                throw new IOException("Folders for CSS file are not created !");
            }
        }
        // compile less file to css file
        engine.compile(lessFile, cssFile);
    }
}


web.xml

Define listener.

https://github.com/benbai123/JSP_Servlet_Practice/blob/master/Practice/LESS/CompileLESSWithJava/WebContent/WEB-INF/web.xml

References

Java Compiler for Less CSS?
http://stackoverflow.com/questions/9739724/java-compiler-for-less-css

LESS Engine
https://github.com/asual/lesscss-engine

Download

Full project at github
https://github.com/benbai123/JSP_Servlet_Practice/tree/master/Practice/LESS/CompileLESSWithJava

Sunday, October 20, 2013

LESS Recursive Mixin


Simple Note

Pre-request

LESS Getting Started
http://ben-bai.blogspot.tw/2013/10/less-getting-started.html

Code

It is funny to write stylesheet with recursive function but probably not a good practice.

index.html

Simple html page
https://github.com/benbai123/JSP_Servlet_Practice/blob/master/Practice/LESS/RecursiveMixin/WebContent/index.html

test.less

Define a mixin .box to create nested selectors recursively.

// comments to displayed in compiled css
/* compiled css */

// define variable
@base-color: #EEEEEE;
@dec-base: #111111;

// define Mixin behave like function
// parameter @idx with default value 1
.box(@idx: 1) when (@idx < 6) {
    // create selector
    .class@{idx} {
        // border with calculated border color,
        // e.g., #EEEEEE - #111111*1*2 = #CCCCCC
        border: 10px solid (@base-color - @dec-base*@idx*2);
        display: inline-block;
        // increase @idx,
        // call .box recursively to create nested selectors
        .box(@idx + 1);
    } 
}
// call .box with default @idx
.box();


Result

Click to view large image



References

Official site
http://lesscss.org/

Do a loop with LESS css
http://blog.thehippo.de/2012/04/programming/do-a-loop-with-less-css/

Download

Full project at github
https://github.com/benbai123/JSP_Servlet_Practice/tree/master/Practice/LESS/RecursiveMixin



Saturday, October 19, 2013

LESS Getting Started


Simple Note

Code

Actually this is a pure html case, the only reason that I put it in a Dynamic Web Project is that I want to use the exiting run-jetty-run plugin in my Eclipse since I am lazy to config a server for it.

less_test.html

Simple html page, declare less file and load less.js. Say 'declare' since the .less file seems loaded by less.js with AJAX instead of load by link directly.

<html>
    <head>
        <!--  include .less file, need to include it before less.js -->
        <link rel="stylesheet/less" type="text/css" href="resources/test.less" />
        <!-- include less.js, will compile .less file at client side -->
        <script src="resources/less-1.4.2.min.js" type="text/javascript"></script>
    </head>
    <body>
        <!-- nested div -->
        <div class="class1">
            <div class="class2">
                <div class="class3">
                    <div class="class4">
                        <div class="class5"></div>
                    </div>
                </div>
            </div>
        </div>
    </body>
</html>


test.less

Stylesheet written by LESS.

// use // to comment in less file only
// use /* */ to commment in less and compiled css
/* compiled css */
// define variable
@base-color: #EEEEEE;

// define Mixin behave like function
// parameter @dec with default value #111111
.box(@dec: #111111) {
    // border with calculated border color,
    // e.g., #EEEEEE - #111111*2 = #CCCCCC
    border: 10px solid (@base-color - @dec*2);
    display: inline-block;
}

// nest selectors inside other selectors
.class1 {
    .box; // include .box with default value of parameter
    .class2 { // .class1 .class2
        .box(#222222); // include .box with @dec = #222222
        .class3 { // .class1 .class2 .class3
            .box(#333333);
            .class4 { // .class1 .class2 .class3 .class4
                .box(#444444);
                .class5 { // .class1 .class2 .class3 .class4 .class5
                    .box(#555555);
                }
            }
        }
    }
}


And less.js downloaded from official site of LESS.

Result

Click to view large image



Reference

LESS
http://lesscss.org/

Download

Full project at github
https://github.com/benbai123/JSP_Servlet_Practice/tree/master/Practice/LESS/GettingStarted

Sunday, March 10, 2013

ZK Basic: Load External Javascript and CSS Files


Introduction

This article describe how to load external javascript and css files in ZK.

Project Structure

The external css and js files are under WebContent folder as below



The Program

load_external_js_css.zul

A native button apply the custom class 'custom-button' defined in external css file 'WebContent/resources/css/test.css', calling custom javascript function 'customjs.sayHello' defined in external js file 'WebContent/resources/js/test.js'

<!-- load .js file under WebContent -->
<?script type="text/javascript" src="resources/js/test.js"?>
<!-- load .css file under WebContent -->
<?style href="resources/css/test.css" type="text/css" ?>
<zk xmlns:n="native">
    <!-- a native (pure html) button,
        apply custom css style,
        call the custom js function when clicked-->
    <n:button class="custom-button"
        onclick="customjs.sayHello('Ben');">
        test
    </n:button>
</zk>


The Result

Page loaded



Button clicked



Reference

The script directive
http://books.zkoss.org/wiki/ZUML_Reference/ZUML/Processing_Instructions/script

The style directive
http://books.zkoss.org/wiki/ZUML%20Reference/ZUML/Processing%20Instructions/style

Download

load_external_js_css.zul
https://github.com/benbai123/ZK_Practice/blob/master/Components/projects/Components_Practice/WebContent/load_external_js_css.zul

test.js
https://github.com/benbai123/ZK_Practice/blob/master/Components/projects/Components_Practice/WebContent/resources/js/test.js

test.css
https://github.com/benbai123/ZK_Practice/blob/master/Components/projects/Components_Practice/WebContent/resources/css/test.css

Saturday, January 12, 2013

Using CSS3 Animations to Perform Notification



Introduction

From W3schools:
With CSS3, we can create animations, which can replace animated images, Flash animations, and JavaScripts in many web pages.

The difference between transition and animation is transition can be applied to change a property smoothly once at a time and the changed property will be applied, animation can change style several times and the changed style do not need to really applied to element.

This article describe how to use CSS3 animation to perform a notification feature.

Try it

Try the sample below with modern browsers:

Mouseover 'User name' or 'Password' to test
User name:
The name used to login
Password:
The password of the name above


The HTML

animation_test.html

Define a keyframe (notificationAnima) while mouseover the parent div and make animation.

<!DOCTYPE html>
<html>
    <head>
        <style> 
            body {
                background-color: #333;
            }
            .container {
                width: 350px;
                background-color: white;
            }
            .notification {
                border: 2px solid #111;
                border-radius: 15px; /* rounded corner */
                background-color: #333;
                color: white;
                font-size: 18px;
                padding: 5px;

                opacity: 0; /* invisible at begining */
            }
            /* define the keyframes rule */
            /* define a keyframe named notificationAnima */
            /* animation in 5 seconds */
            .field:hover .notification {
                -webkit-animation: notificationAnima 5s; /* Safari and Chrome */
                -moz-animation: notificationAnima 5s; /* Firefox */
                -o-animation: notificationAnima 5s; /* Opera */
                animation: notificationAnima 5s;
            }
            /* control the notificationAnima frame */
            @-webkit-keyframes notificationAnima {
                75%        {opacity: 1;} /* display notification for a while */
                100%    {opacity: 0;} /* then hide it again */
            }
            @-moz-keyframes notificationAnima {
                75%        {opacity: 1;}
                100%    {opacity: 0;}
            }
            @-o-keyframes notificationAnima {
                75%        {opacity: 1;}
                100%    {opacity: 0;}
            }
            @keyframes notificationAnima {
                75%        {opacity: 1;}
                100%    {opacity: 0;}
            }
        </style>
    </head>
    <body>
        <div class="container">
            <div class="field">
                User name: <input type="text"></input>
                <br />
                <span class="notification">The name used to login</span>
            </div>
            <div class="field">
                Password: <input type="text"></input>
                <br />
                <span class="notification">The password of the name above</span>
            </div>
        </div>
    </body>
</html>


The Result

View demo on line
http://screencast.com/t/MDvO7pHaEfe4

Reference

w3schools CSS3 Animations
http://www.w3schools.com/css3/css3_animations.asp

Download

animation_test.html
https://github.com/benbai123/HTML_CSS_Javascript_practice/blob/master/CSS3/animation_test.html

animation_test.swf
https://github.com/benbai123/HTML_CSS_Javascript_practice/blob/master/CSS3/demo/animation_test.swf

Friday, January 11, 2013

Using CSS3 Transitions to Perform Animation


Introduction

From W3School:
With CSS3, we can add an effect when changing from one style to another, without using Flash animations or JavaScripts.

Try it

Try the sample below with modern browsers (FF 18, Chrome, etc)

mouse over to test


The HTML

Here we change 3 different properties width, height and border-color with different transition properties, separated by comma.

<html>
    <head>
        <style>
            .block {
                border: 1px solid green;
                width: 100px;
                height: 100px;
                
            }
            .block:hover {
                width: 500px;
                height: 350px;
                border-color: red;


                /* property duration timing-function delay */
                /* width ->change width smoothly */
                /* 2s -> change it smoothly in 2 seconds */
                /* ease-out -> slow end */
                /* 0.5s -> delay 0.5 second at the begining */
                /* separate different properties by comma */
                /*
                /* similarly */
                /* change height smoothly in 1.5 seconds with 1 second delay, slow start */
                /* change border-color smoothly in 1 second with 1.5 seconds delay, slow end */

                -webkit-transition: width 2s ease 0.5s, height 1.5s ease-in 1s, border-color 1s ease-out 1.5s;
                -moz-transition: width 2s ease 0.5s, height 1.5s ease-in 1s, border-color 1s ease-out 1.5s;
                -o-transition: width 2s ease 0.5s, height 1.5s ease-in 1s, border-color 1s ease-out 1.5s;
                transition: width 2s ease 0.5s, height 1.5s ease-in 1s, border-color 1s ease-out 1.5s;
            }
            /* return to original style smoothly while mouseout */
            .block:not(hover) {
                -webkit-transition: width 2s, height 2s , border-color 2s;
                -moz-transition: width 2s, height 2s , border-color 2s;
                -o-transition: width 2s, height 2s , border-color 2s;
                transition: width 2s, height 2s , border-color 2s;
            }
        </style>
    </head>
    <body>
        <div class="block">
            mouse over to test
        </div>
    </body>
</html>


The Result

View demo on line
http://screencast.com/t/myM87X1NtuX

Reference

http://www.w3schools.com/css3/css3_transitions.asp

http://stackoverflow.com/questions/9670075/css-transition-shorthand-with-multiple-properties

Download

CSS3_transition.swf
https://github.com/benbai123/HTML_CSS_Javascript_practice/blob/master/CSS3/demo/CSS3_transition.swf

transition_test.html
https://github.com/benbai123/HTML_CSS_Javascript_practice/blob/master/CSS3/transition_test.html

Sunday, March 11, 2012

JSP/Servlet: Use Jawr to reduce page load times.

Introduction

From official site:
Jawr is a tunable packaging solution for Javascript and CSS which allows for rapid development of resources in separate module files. Developers can work with a large set of split javascript files in development mode, then Jawr bundles all together into one or several files in a configurable way.
By using a tag library, Jawr allows you to use the same, unchanged pages for development and production. Jawr also minifies and compresses the files, resulting in reduced page load times.

Getting started

Get required jars:
download Jawr 3.3.3:
http://java.net/projects/jawr/downloads/directory/release
get log4j:
http://mvnrepository.com/artifact/log4j/log4j/1.2.16

Then put them into WEB-INF/lib

Create Javascript/CSS files:
The project architecture and Javascript/CSS files are as below



Config Javascript/CSS Servlet in WEB-INF/web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    version="3.0">
    <servlet>
        <servlet-name>JavascriptServlet</servlet-name>
        <servlet-class>net.jawr.web.servlet.JawrServlet</servlet-class>

        <!-- Location in classpath of the config file
            it should be a path under classpath,
            the value is /test/jawr.properties here because
            we put the file "jawr.properties" under /src/test and
            it will be moved to classpath/test/ after compiled -->
        <init-param>
            <param-name>configLocation</param-name>
            <param-value>/test/jawr.properties</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet>
        <servlet-name>CSSServlet</servlet-name>
        <servlet-class>net.jawr.web.servlet.JawrServlet</servlet-class>

        <!-- Location in classpath of the config file
            it should be a path under classpath,
            the value is /test/jawr.properties here because
            we put the file "jawr.properties" under /src/test and
            it will be moved to classpath/test/ after compiled -->
        <init-param>
            <param-name>configLocation</param-name>
            <param-value>/test/jawr.properties</param-value>
        </init-param>
        <init-param>
            <param-name>type</param-name>
            <param-value>css</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <!-- the url-pattern can be any value, we use *.jsbundle / *.cssbundle here -->
    <servlet-mapping>
        <servlet-name>JavascriptServlet</servlet-name>
        <url-pattern>*.jsbundle</url-pattern>
    </servlet-mapping> 

    <servlet-mapping>
        <servlet-name>CSSServlet</servlet-name>
        <url-pattern>*.cssbundle</url-pattern>
    </servlet-mapping>
</web-app>

Config jawr in src/test/jawr.properties:

# Common properties
jawr.debug.on=false
jawr.gzip.on=true
jawr.gzip.ie6.on=false
jawr.charset.name=UTF-8

# Javascript properties and mappings
jawr.js.bundle.basedir=/js

# All files within /js/bundleOne will be together in a bundle
# mappings to /bundles/jsbundle_one.jsbundle.
# All files within /js/bundleTwo will be together in a bundle
# mappings to /bundles/jsbundle_two.jsbundle.
# the jsbundleOne / jsbundleTwo in the mapping key
# can be any value  
jawr.js.bundle.jsbundleOne.id=/bundles/jsbundle_one.jsbundle
jawr.js.bundle.jsbundleOne.mappings=/js/bundleOne/**
jawr.js.bundle.jsbundleTwo.id=/bundles/jsbundle_two.jsbundle
jawr.js.bundle.jsbundleTwo.mappings=/js/bundleTwo/**

# CSS properties and mappings
jawr.css.bundle.basedir=/css

jawr.css.bundle.cssbundle.id=/bundles/cssbundle.cssbundle
jawr.css.bundle.cssbundle.mappings=/css/**

########## another way ##########
## note: singlebundle currently only works with
##       url-pttern ends with .css,
##       have to modify the web.xml and
##       test.jsp before use this way
## CSS properties and mappings
# jawr.css.bundle.basedir=/css
#
## CSS files will be all bundled together automatically
# jawr.css.factory.use.singlebundle=true
# jawr.css.factory.singlebundle.bundlename=/bundles/cssbundle.css

Note singlebundle currently only works with the url-pattern endswith .css for css files,
please refer jawr tracker:
http://java.net/jira/browse/JAWR-228

test file index.jsp (without Jawr)

<%@ page isErrorPage="true" language="java"
    contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page isELIgnored ="false" %>
<html>
    <head>
        <meta http-equiv="Content-Type" 
            content="text/html; charset=UTF-8"/>
        <title>Normal - without JAWR</title>
        <link href="css/aaa.css" rel="stylesheet" type="text/css">
        <link href="css/bbb.css" rel="stylesheet" type="text/css">
        <link href="css/ccc.css" rel="stylesheet" type="text/css">
        <link href="css/ddd.css" rel="stylesheet" type="text/css">
        <link href="css/eee.css" rel="stylesheet" type="text/css">
        <script type="text/javascript" src="js/bundleOne/aaa.js"></script>
        <script type="text/javascript" src="js/bundleOne/bbb.js"></script>
        <script type="text/javascript" src="js/bundleOne/ccc.js"></script>
        <script type="text/javascript" src="js/bundleTwo/ddd.js"></script>
        <script type="text/javascript" src="js/bundleTwo/eee.js"></script>
        <script type="text/javascript">
            onload = function () {
                funcA();
                funcB();
                funcC();
                funcD();
                funcE();
            }
        </script>
    </head>
    <body>
        <div class="class_a">
            js file <span id="funcA"></span> loaded
        </div>
        <div class="class_b">
            js file <span id="funcB"></span> loaded
        </div>
        <div class="class_c">
            js file <span id="funcC"></span> loaded
        </div>
        <div class="class_d">
            js file <span id="funcD"></span> loaded
        </div>
        <div class="class_e">
            js file <span id="funcE"></span> loaded
        </div>
    </body>
</html>

test file test.jsp (use Jawr)

<%@ page isErrorPage="true" language="java"
    contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page isELIgnored ="false" %>
<%@ taglib uri="http://jawr.net/tags" prefix="jwr" %>
<html>
    <head>
        <meta http-equiv="Content-Type" 
            content="text/html; charset=UTF-8"/>
        <title>Normal - without JAWR</title>
        <jwr:style src="/bundles/cssbundle.cssbundle" />
        <jwr:script src="/bundles/jsbundle_one.jsbundle"/>
        <jwr:script src="/bundles/jsbundle_two.jsbundle"/>
        <script type="text/javascript">
            onload = function () {
                funcA();
                funcB();
                funcC();
                funcD();
                funcE();
            }
        </script>
    </head>
    <body>
        <div class="class_a">
            js file <span id="funcA"></span> loaded
        </div>
        <div class="class_b">
            js file <span id="funcB"></span> loaded
        </div>
        <div class="class_c">
            js file <span id="funcC"></span> loaded
        </div>
        <div class="class_d">
            js file <span id="funcD"></span> loaded
        </div>
        <div class="class_e">
            js file <span id="funcE"></span> loaded
        </div>
    </body>
</html>

Test Result:

In short, it is about 2 times faster.

The result that load index.jsp  (without Jawr) 3 times as below:







The result that load test.jsp (with Jawr) 3 times as below:






Download:
The full project at github
https://github.com/benbai123/JSP_Servlet_Practice/tree/master/Practice/Tools/JAWR

References:
http://jawr.java.net/
http://jawr.java.net/tutorials/quickstart.html

Sunday, January 8, 2012

CSS and Javascript trick - The Fancy Checkbox

Below is a normal checkbox


<input type="checkbox" value="normal checkbox" onclick="alert('checked: ' + this.checked);">normal checkbox</input>


It works well and looks... normal, sometimes we want a more beautiful, fancy checkbox.

How to style it? There are several steps, described as follows:

Step 1: Separate the checkbox and label.

So we can create a fancy element to replace the normal checkbox and style it,
and style the label as need.

The outer 'i' tag also can handle the 'onclick' event that bubble up from fancy element,

and make easier to get fancy checkbox instance if we assign a CSS class to it.

The checkbox after this step becomes:


<head>
 <style type="text/css"> 
  .fancy_label { 
   font-style: normal;
  } 
 </style> 
</head>
<body>
 <i>
  <input type="checkbox" value="normal checkbox" onclick="alert('checked: ' + this.checked);"></input>
  <span class="fancy_label">normal checkbox</span>
 </i>
</body>


nothing changed, just separate the box and label.

Step 2: Throw out the normal checkbox.

Because we want replace it with a fancy one, we have to throw it out at first. We can not just drop it because we would like to use the functionality of original checkbox.

The checkbox after this step becomes:


<head>
 <style type="text/css">
  .normal_checkbox {
   position: absolute;
   left: -9999px;
  }
  .fancy_label { 
   font-style: normal;
  }
 </style> 
</head>
<body>
 <i>
  <input class="normal_checkbox" type="checkbox" value="normal checkbox" onclick="alert('checked: ' + this.checked);"></input>
  <span class="fancy_label">normal checkbox</span>
 </i>
</body>


The box is out of the screen, we can only see the label.

Step 3: Add the fancy element before the label.

We have to add a fancy element as the box of the fancy checkbox.

The checkbox after this step becomes:


<head>
    <style type="text/css">
        .normal_checkbox {
            position: absolute;
            left: -9999px;
        }
        .fancy_label { 
            font-style: normal;
        }
        .fancy_default {
            display: inline-block;
            height: 15px;
            width: 15px;
            background-repeat: no-repeat;
            background-image: url('img/fancy_default.png');
        }
        .fancy_over {
            background-image: url('img/fancy_over.png');
        }
        .fancy_down {
            background-image: url('img/fancy_down.png');
        }
        .fancy_checked {
            background-image: url('img/fancy_checked.png');
        }
        .fancy_disabled {
            background-color: #AAFFAA;
        }
    </style> 
</head>
<body>
    <i>
        <input class="normal_checkbox" type="checkbox" value="normal checkbox" onclick="alert('checked: ' + this.checked);"></input>
        <div class="fancy_default"></div>
        <span class="fancy_label">fancy default</span>
    </i>
</body>


the image above just list all status of fancy checkbox,

only the fancy default displayed now.

Step 4: Add the event with respect to each status.

To make it active, the event control is required.

Add style with mouseover/mousedown event and remove it while mouseout/mouseup,

also sync the checked/disabled status from the normal checkbox.


<html>
    <head>
        <script type="text/javascript">
            onload = function initFancyCheckbox () {
                var fancyElements,
                    element,
                    old;
                fancyElements = getElementsByClassName('fancy_default');
                for (var i =  0; i < fancyElements.length; i++) {
                    old = element;
                    element = fancyElements[i];
                    // IE need fix inline
                    if (navigator.appName == 'Microsoft Internet Explorer')
                        element.className += ' fancy_fix_inline';
                    // add style fancy_over while mouse over
                    element.onmouseover = function (event) {
                        if (!event)
                            event = window.event;
                        var fancy = (event.currentTarget) ? event.currentTarget : event.srcElement;
                        if (fancy.className.indexOf('fancy_disabled') == -1) {
                            var clsnm = fancy.className;
                            if (clsnm.indexOf('fancy_over') == -1)
                                fancy.className += ' fancy_over';
                        }
                    }
                    // remove style fancy_over while mouse out
                    element.onmouseout = function (event) {
                        if (!event) // IE will not pass event
                            event = window.event;
                        // IE do not have currentTarget
                        var fancy = (event.currentTarget) ? event.currentTarget : event.srcElement;
                        fancy.className = fancy.className.replace(/fancy_over/g, '').replace(/(^[\\s]*)|([\\s]*$)/g, "");
                    }
                    // add style fancy_down while mouse down
                    element.onmousedown = function (event) {
                        if (!event)
                            event = window.event;
                        var fancy = (event.currentTarget) ? event.currentTarget : event.srcElement;
                        if (fancy.className.indexOf('fancy_disabled') == -1) {
                            var clsnm = fancy.className;
                            if (clsnm.indexOf('fancy_down') == -1)
                                fancy.className += ' fancy_down';
                        }
                    }
                    // remove style fancy_down while mouse up
                    element.onmouseup = function (event) {
                        if (!event)
                            event = window.event;
                        var fancy = (event.currentTarget) ? event.currentTarget : event.srcElement;
                        fancy.className = fancy.className.replace(/fancy_down/g, '').replace(/(^[\\s]*)|([\\s]*$)/g, "");
                    }
                    element.onclick = function (event) {
                        if (!event)
                            event = window.event;
                        var fancy = (event.currentTarget) ? event.currentTarget : event.srcElement;
                        if (fancy.className.indexOf('fancy_disabled') == -1) {
                            var normal = fancy.previousSibling;
                            // try find the checkbox before the fancy element
                            while (normal && (!normal.tagName || normal.tagName != 'INPUT'))
                                normal = normal.previousSibling;
                            // not found, do nothing
                            if (!normal) return;
                            // change the checked status
                            normal.checked = !normal.checked;
                            syncChecked(fancy);
                        } else {
                            // stop the event bubble up
                            if (event.stopPropagation)
                                event.stopPropagation();
                            else
                                event.cancelBubble = true;
                        }
                    }
                    syncChecked(element);
                    syncDisabled(element);
                }
            }
            // get elements by class name with respect to specific element
            function getElementsByClassName (clsnm, parent) {
                var result = [];
                if (!parent)
                    parent = document;
                // IE do not have getElementsByClassName
                if (parent.getElementsByClassName)
                    result = parent.getElementsByClassName(clsnm);
                else {
                    var tmp = parent.getElementsByTagName('*');
                    for (var i = tmp.length-1; i >= 0; i--)
                        if (tmp[i].className && tmp[i].className.match(new RegExp('(\\s|^)'+clsnm+'(\\s|$)')))
                            result.push(tmp[i]);
                }
                return result;
            }
            // sync the checked status
            function syncChecked (element) {
                var clsnm = element.className,
                    normal = element.previousSibling;
                // try find the checkbox before the fancy element
                while (normal && (!normal.tagName || normal.tagName != 'INPUT'))
                    normal = normal.previousSibling;
                // not found, do nothing
                if (!normal) return;
                if (normal.checked) {
                    if (clsnm.indexOf('fancy_checked') == -1)
                        element.className += ' fancy_checked';
                } else {
                    element.className = element.className.replace(/fancy_checked/g, '').replace(/(^[\\s]*)|([\\s]*$)/g, "");
                }
            }
            // sync the checked status
            function syncDisabled (element) {
                var clsnm = element.className,
                    normal = element.previousSibling;
                // try find the checkbox before the fancy element
                while (normal && (!normal.tagName || normal.tagName != 'INPUT'))
                    normal = normal.previousSibling;
                // not found, do nothing
                if (!normal) return;
                if (normal.disabled) {
                    if (element.className.indexOf('fancy_disabled') == -1)
                        element.className += ' fancy_disabled';
                } else
                    element.className = element.className.replace(/fancy_disabled/g, '').replace(/(^[\\s]*)|([\\s]*$)/g, "");
            }
        </script>
        <style type="text/css">
            .normal_checkbox {
                position: absolute;
                left: -9999px;
            }
            .fancy_checkbox {
                
            }
            .fancy_label { 
                font-style: normal;
            }
            .fancy_default {
                display: inline-block;
                height: 15px;
                width: 15px;
                background-repeat: no-repeat;
                background-image: url('img/fancy_default.png');
            }
            .fancy_over {
                background-image: url('img/fancy_over.png');
            }
            .fancy_down {
                background-image: url('img/fancy_down.png');
            }
            .fancy_checked {
                background-image: url('img/fancy_checked.png');
            }
            .fancy_disabled {
                background-color: #AAFFAA;
            }
            .fancy_fix_inline {
                display: inline;
                margin-right: 2px;
            }
        </style>
    </head>
    <body>
        <i id="fancy_checkbox_one" onclick="alert('checked: ' + this.getElementsByClassName('normal_checkbox')[0].checked);">
            <input class="normal_checkbox" type="checkbox" disabled="true" checked="true" value="normal checkbox"></input>
            <div class="fancy_default"></div>
            <span class="fancy_label">fancy default</span>
        </i><br />
    </body>
</html>


the image above is a fancy checkbox with initial checked and disabled.

Step 5: Create a test case.

After the fancy checkbox is done, we should create a use case and test it.

the test case:


<html>
    <head>
        <script type="text/javascript">
            onload = function initFancyCheckbox () {
                var fancyElements,
                    element,
                    old;
                fancyElements = getElementsByClassName('fancy_default');
                for (var i =  0; i < fancyElements.length; i++) {
                    old = element;
                    element = fancyElements[i];
                    // IE need fix inline
                    if (navigator.appName == 'Microsoft Internet Explorer')
                        element.className += ' fancy_fix_inline';
                    // add style fancy_over while mouse over
                    element.onmouseover = function (event) {
                        if (!event)
                            event = window.event;
                        var fancy = (event.currentTarget) ? event.currentTarget : event.srcElement;
                        if (fancy.className.indexOf('fancy_disabled') == -1) {
                            var clsnm = fancy.className;
                            if (clsnm.indexOf('fancy_over') == -1)
                                fancy.className += ' fancy_over';
                        }
                    }
                    // remove style fancy_over while mouse out
                    element.onmouseout = function (event) {
                        if (!event) // IE will not pass event
                            event = window.event;
                        // IE do not have currentTarget
                        var fancy = (event.currentTarget) ? event.currentTarget : event.srcElement;
                        fancy.className = fancy.className.replace(/fancy_over/g, '').replace(/(^[\\s]*)|([\\s]*$)/g, "");
                    }
                    // add style fancy_down while mouse down
                    element.onmousedown = function (event) {
                        if (!event)
                            event = window.event;
                        var fancy = (event.currentTarget) ? event.currentTarget : event.srcElement;
                        if (fancy.className.indexOf('fancy_disabled') == -1) {
                            var clsnm = fancy.className;
                            if (clsnm.indexOf('fancy_down') == -1)
                                fancy.className += ' fancy_down';
                        }
                    }
                    // remove style fancy_down while mouse up
                    element.onmouseup = function (event) {
                        if (!event)
                            event = window.event;
                        var fancy = (event.currentTarget) ? event.currentTarget : event.srcElement;
                        fancy.className = fancy.className.replace(/fancy_down/g, '').replace(/(^[\\s]*)|([\\s]*$)/g, "");
                    }
                    element.onclick = function (event) {
                        if (!event)
                            event = window.event;
                        var fancy = (event.currentTarget) ? event.currentTarget : event.srcElement;
                        if (fancy.className.indexOf('fancy_disabled') == -1) {
                            var normal = fancy.previousSibling;
                            // try find the checkbox before the fancy element
                            while (normal && (!normal.tagName || normal.tagName != 'INPUT'))
                                normal = normal.previousSibling;
                            // not found, do nothing
                            if (!normal) return;
                            // change the checked status
                            normal.checked = !normal.checked;
                            syncChecked(fancy);
                        } else {
                            // stop the event bubble up
                            if (event.stopPropagation)
                                event.stopPropagation();
                            else
                                event.cancelBubble = true;
                        }
                    }
                    syncChecked(element);
                    syncDisabled(element);
                }
            }
            // get elements by class name with respect to specific element
            function getElementsByClassName (clsnm, parent) {
                var result = [];
                if (!parent)
                    parent = document;
                // IE do not have getElementsByClassName
                if (parent.getElementsByClassName)
                    result = parent.getElementsByClassName(clsnm);
                else {
                    var tmp = parent.getElementsByTagName('*');
                    for (var i = tmp.length-1; i >= 0; i--)
                        if (tmp[i].className && tmp[i].className.match(new RegExp('(\\s|^)'+clsnm+'(\\s|$)')))
                            result.push(tmp[i]);
                }
                return result;
            }
            // sync the checked status
            function syncChecked (element) {
                var clsnm = element.className,
                    normal = element.previousSibling;
                // try find the checkbox before the fancy element
                while (normal && (!normal.tagName || normal.tagName != 'INPUT'))
                    normal = normal.previousSibling;
                // not found, do nothing
                if (!normal) return;
                if (normal.checked) {
                    if (clsnm.indexOf('fancy_checked') == -1)
                        element.className += ' fancy_checked';
                } else {
                    element.className = element.className.replace(/fancy_checked/g, '').replace(/(^[\\s]*)|([\\s]*$)/g, "");
                }
            }
            // sync the checked status
            function syncDisabled (element) {
                var clsnm = element.className,
                    normal = element.previousSibling;
                // try find the checkbox before the fancy element
                while (normal && (!normal.tagName || normal.tagName != 'INPUT'))
                    normal = normal.previousSibling;
                // not found, do nothing
                if (!normal) return;
                if (normal.disabled) {
                    if (element.className.indexOf('fancy_disabled') == -1)
                        element.className += ' fancy_disabled';
                } else
                    element.className = element.className.replace(/fancy_disabled/g, '').replace(/(^[\\s]*)|([\\s]*$)/g, "");
            }
            // disable/enable a fancy checkbox by its instance or id
            function setDisable (fancyCheckbox, disable) {
                // assume it is an id if type is string
                if (typeof fancyCheckbox === 'string')
                    fancyCheckbox = document.getElementById(fancyCheckbox);
                var normal = getElementsByClassName('normal_checkbox', fancyCheckbox)[0],
                    fancy = getElementsByClassName('fancy_default', fancyCheckbox)[0];
                normal.disabled = disable;
                if (disable) {
                    if (fancy.className.indexOf('fancy_disabled') == -1)
                        fancy.className += ' fancy_disabled';
                } else
                    fancy.className = fancy.className.replace(/fancy_disabled/g, '').replace(/(^[\\s]*)|([\\s]*$)/g, "");
            }
            function updateDisable() {
                var food_list = getElementsByClassName('fancy_checkbox', document.getElementById('food_list')),
                    food_group = document.getElementById('food_group'),
                    checked = getElementsByClassName('normal_checkbox', food_group)[0].checked;
                for (var i = food_list.length-1; i >= 0; i--) {
                if (checked)
                        setDisable(food_list[i], false);
                    else
                        setDisable(food_list[i], true);
                }
            }
            function showResult() {
                var str = 'The food you chose: ',
                    food_list = getElementsByClassName('fancy_checkbox', document.getElementById('food_list'));
                for (var i = food_list.length-1; i >= 0; i--) {
                    if (getElementsByClassName('normal_checkbox', food_list[i])[0].checked)
                        str = str + getElementsByClassName('fancy_label', food_list[i])[0].innerHTML + ', ';
                }
                alert(str);
            }
        </script>
        <style type="text/css">
            .normal_checkbox {
                position: absolute;
                left: -9999px;
            }
            .fancy_checkbox {
                
            }
            .fancy_label { 
                font-style: normal;
            }
            .fancy_default {
                display: inline-block;
                height: 15px;
                width: 15px;
                background-repeat: no-repeat;
                background-image: url('img/fancy_default.png');
            }
            .fancy_over {
                background-image: url('img/fancy_over.png');
            }
            .fancy_down {
                background-image: url('img/fancy_down.png');
            }
            .fancy_checked {
                background-image: url('img/fancy_checked.png');
            }
            .fancy_disabled {
                background-color: #AAFFAA;
            }
            .fancy_fix_inline {
                display: inline;
                margin-right: 2px;
            }
        </style>
    </head>
    <body>
        <i id="food_group" onclick="updateDisable();" class="fancy_checkbox">
            <input class="normal_checkbox" type="checkbox" value="normal checkbox" onclick="alert('checked: ' + this.checked);"></input>
            <div class="fancy_default"></div>
            <span class="fancy_label">Choose food</span>
        </i><br />
        <div id="food_list">
            <i id="bread" style="margin-left: 3px" class="fancy_checkbox">
                <input class="normal_checkbox" type="checkbox" value="normal checkbox" disabled="true" onclick="alert('checked: ' + this.checked);"></input>
                <div class="fancy_default"></div>
                <span class="fancy_label">bread</span>
            </i><br />
            <i id="ham" style="margin-left: 3px" class="fancy_checkbox">
                <input class="normal_checkbox" type="checkbox" value="normal checkbox" checked="true" disabled="true" onclick="alert('checked: ' + this.checked);"></input>
                <div class="fancy_default"></div>
                <span class="fancy_label">ham</span>
            </i><br />
            <i id="beef" style="margin-left: 3px" class="fancy_checkbox">
                <input class="normal_checkbox" type="checkbox" value="normal checkbox" disabled="true" onclick="alert('checked: ' + this.checked);"></input>
                <div class="fancy_default"></div>
                <span class="fancy_label">beef</span>
            </i><br />
        </div>
        <button onclick="showResult()">show the result</button>
    </body>
</html>


Download
The full resource with a demo flash can be downloaded from github

https://github.com/benbai123/HTML_CSS_Javascript_practice/tree/master/fancy_checkbox

References:

Fancy checkboxes and radio buttons with CSS