Skip to content

Easy to confirm!

January 26, 2012

A jQuery confirm plugin

 

I’m re-writing some components for our  world-wide selling Teamwork, and I was in the need to have a nicer way to confirm some “dangerous” user actions.

The standard JavaScript solution is something like

if (confirm(“do you want to destroy everything?”)) 
  … <em>here the code for destroying</em> 

 

While the code is very simple, the popup alert is unfashionable and old-smelling.

The best solution I found is the Nadia Alramli’s jQuery confirm plugin that I have already used massively in Licorize.

The first great idea in the Nadia’s plugin is that the confirm question is shown exactly where you clicked for the action.

The second idea is that the “confirm” is just “applied after” your code behavior.

Let se the simplest example (from Nadias’ blog):

// The action.
$('a').click(function() {
  alert('click');
  return false;
});
 
// The most simple use.
$('a').confirm();

 

As you can see, first you bind the event normally, then you will apply the confirm.

This approach is very nice, but its is very “javascript oriented”; what I mean is that you need a js piece of code for setting up the confirm, and this is a little bit rigid for an inline usage.

Example:

<button onclick=”destroyAll()”>

 

where “destroyAll” is your function.

 

So I wrote this little jQuery plugin that can be used like this:

<button onclick=”$(this).confirm(destroyAll)>

Here the code:

 $.fn.confirm = function(action, message) {
    if (typeof(action) != "function")
      return;
    this.each(function() {
      var el = $(this);
      var div = $("<div>").addClass("confirmBox").
              html(message ? message : i18n.DO_YOU_CONFIRM);
      div.css({"min-width":el.outerWidth(),"min-height":el.outerHeight()});
      div.oneTime(5000, "autoHide", function() {
        $(this).fadeOut(100, function() {
          el.show();
          $(this).remove();
        });
      });
      var no = $("<span>").addClass("confirmNo")
              .html(i18n.NO).click(function() {
        $(this).parent().fadeOut(100, function() {
          el.show();
          $(this).remove();
        }).stopTime("autoHide");
      });
      var yes = $("<span>").addClass("confirmYes")
              .html(i18n.YES).click(function() {
        $(this).parent().fadeOut(100, function() {
          el.show().oneTime(1, "doaction", action);
          $(this).remove();
        }).stopTime("autoHide");
      });

      div.append("&nbsp;&nbsp;")
              .append(yes)
              .append("&nbsp;/&nbsp;")
              .append(no);
      el.hide().after(div);

    });

    return this;
  };

few lines of CSS for the sake of completeness:

.confirmBox{
    display:inline-block;
    z-index:10000;
    vertical-align:middle;
    text-align:center;
    font-size:larger;
    font-style:italic;
    color:#a0a0a0;
  }
  .confirmBox .confirmNo{
    color:#e06060;
    cursor:pointer;
    font-weight:bolder;
  }
  .confirmBox .confirmYes{
  color:#60e060;
  cursor:pointer;
    font-weight:bolder;
  }

and two lines for internationalization:

var i18n = {
    YES:"Yes",
    NO:"No",
    DO_YOU_CONFIRM:"Do you confirm?"
  };

 

See a Demo page here

This component is released under MIT license.

Your feedback will be appreciated.

To JSON or not to JSON

January 18, 2012

How to simply convert a sqlite database to JSON

Last week my collegue Matteo (aka pupunzi) was porting an iPad application (booo!) to HTML5 (yeah!).

The iPad application was a virtual museum that was using a sqlite dabatase for reading data relative to rooms, biography, history and so on.

Even if sqlite is internally supported by some browsers (e.g. Chrome) the easiest way to read data in javascript is to have a JSON object.

I wrote a simple java code to dump the whole database into a JSON object.

import net.sf.json.JSONObject;
import net.sf.json.JSONArray;
import java.sql.*;
import java.util.List;
import java.util.ArrayList;
import java.io.FileOutputStream;
public class DB2JSON {

  public static void main(String[] args) {

    if (args.length<1)
      return;
    Connection conn = null;

    try {
      String dbFile = args[0];
      JSONObject ret = new JSONObject();
      Class.forName("org.sqlite.JDBC");
      conn = DriverManager.getConnection("jdbc:sqlite:" + dbFile);
      Statement stat = conn.createStatement();

      ResultSet tables = stat.executeQuery("SELECT name 
         FROM sqlite_master 
         WHERE type='table' ORDER BY name;");
      List tableNames = new ArrayList();
      while (tables.next()) {
        tableNames.add(tables.getString("name"));
      }
      tables.close();

      for (String tableName : tableNames) {
        JSONArray jsa = new JSONArray();

        ResultSet rows = stat.executeQuery("select * from " + 
           tableName + ";");

        while (rows.next()) {
          JSONObject row = new JSONObject();
          ResultSetMetaData meta = rows.getMetaData();
          for (int i = 1; i <= meta.getColumnCount(); i++) {
            row.element(meta.getColumnName(i), rows.getObject(i));
          }
          jsa.add(row);
        }

        rows.close();
        ret.element(tableName, jsa);
      }

      conn.close();

      // result on console
      System.out.println(ret.toString());

      //result on file
      FileOutputStream fos = new FileOutputStream(dbFile+".json");
      fos.write(ret.toString().getBytes());
      fos.close();     

    } catch (Throwable e) {
      try {
        if (conn != null)
          conn.close();
      } catch (SQLException s) {
      }
      e.printStackTrace();
    }
  }
}

The resulting JSON object will have a property for each table containing an array of records. Different types of properties are supported (String, int, long, dates etc.)

There are two dependencies to external libraries:

  1.  http://json-lib.sourceforge.net/
  2. http://www.zentus.com/sqlitejdbc/

Enjoy.

P.S.: the pupunzi’s porting result is an HTML5 application that runs everywhere and it is looks even more beautiful than the iOS one Smile !

Follow

Get every new post delivered to your Inbox.