Table

Tables in JavaScript — recommended solutions

The last time I worked on the web application, of which a large part was the presentation of processed data in tabular form, with the possibility of sorting, etc. We had to find a good and quick solution for this purpose.

Tables in JavaScript — solutions

There is a small list of good solutions.

1. Dynatable.js

It’s quite a fresh look at the issue of creating solutions for tabular data in JavaScript. Dynatable.js is a jQuery plugin, also based on HTML5 and JSON.

This solution allows quite comfortably reproduce the data in the form of an interactive table. There are also many opportunities, such as search (filtering), creating a table with pagination, sorting, embedding images and more.

Dynatable.js - demo

Dynatable.js — demo

The website contains excellent documentation with examples. Available licenses: Open-source and commercial.

URL:

http://www.dynatable.com/

2. DataTables

I know this solution from one of older projects.

It is high quality product, with a paid support. Working with this solution was quite nicely.

As jQuery plugin, it’s easy to use:

$(document).ready(function() {
    $('#test-table').dataTable();
});

It also has a lot of customization options, including painless definition of CSS styles for tables.

DataTables - tabele w JavaScript

DataTables — tabele w JavaScript

Available on GPL or BSD license.

URL:

http://datatables.net/

http://datatables.net/examples/

jQuery tips and tricks

In today’s article we’ll do a small review of interesting jQuery tips. The framework itself gives the programmer a gigantic possibilities, that still can be extended through tricks and best practices.

jQuery tips

This time we focus more on practice and examples, rather than theory.

Tip 1. Determine the size of our document

In details, it’s a query of the DOM elements number, which the page contains. In jQuery this information is available in the following manner:

alert($('*').length);

2. Checking if a checkbox is checked 🙂

It’s simple — can be done in such a way:

if ($("#myCheckBoxID").is(':checked')) {
  …
}

or by checking an attribute:

if ($('#myCheckBoxID').attr('checked')) {
  …
}

3. Checking whether an element exists

if ($("#myElementID").length == 0)
    alert('#myElementID does not exist');
else
    alert('#myElementID exist!');

4. Checking if an element is visible

Is visible:

$("#myElementID").is(":visible");

Is hidden:

$('#myElementID').is(':hidden')

On the borderline — CSS and JavaScript

Working with JavaScript often is associated with CSS. And thanks to that, we can acquire practice in the use of CSS, even if we don’t deal directly with creating layouts.

CSS and JavaScript

Good CSS skill broadens our horizons, and helps in developing quick solutions and tricks.

CSS

For a good start — rotate an element in CSS:

.rotate {
    -webkit-transform: rotate(50deg);
    -moz-transform: rotate(50deg);
    -ms-transform: rotate(50deg);
    -o-transform: rotate(50deg);
    transform: rotate(50deg);
}

Sample:

<div style="border: solid 1px red; width: 400px; height: 250px"
    class="rotate" id="test-div">
</div>

In this case, the element will be rotated by 50 degrees.

Setting CSS classes in JavaScript

Probably the most popular task on the border of CSS and JavaScript is to set dynamic CSS classes for an HTML element from JavaScript level.

In “pure” JavaScript we can do it as following, by setting the className attribute:

document.getElementById('test-div').className = 'my_css_class';

Another example from the old school is to set a CSS class to the HTML element on mouse hover, and remove class on mouse out:

<div style="border: solid 1px red; width: 400px; height: 250px"
    id="test-div2"
    onmouseover=this.className='rotate';
    onmouseout=this.className=''; >
</div>

Set and remove CSS classes for the elements in jQuery

With jQuery this task is painless. We can set CSS class using addClass method:

$("#test-div").addClass("myClass myAnotherClass");

whereas the removal will be done by removeClass:

$("#test-div").removeClass("myClass");

We can pass many names as an argument and connect method calls in chains:

$("p").removeClass("oldClass").addClass("newClass");

The above code performs operations for all paragraphs in the document; remove the oldClass class, and then add the newClass CSS class.

Setting particular styles (not whole CSS classes)

Instead of CSS classes, only individual styles can be manipulated. In “pure” JavaScript it’s somewhat tedious, e.g.:

// border style
document.getElementById("test-div").style.border = "solid 1px #00f";

In jQuery we simply use the css() method.

Algorithms and data structures in JavaScript

In today’s article will be a very important topic, namely: algorithms and data structures in JavaScript. It is an important topic for programming in general. We should not have prejudices — Javascript is suitable for this purpose very well. Perhaps some things will be in ths language a bit harder, but that others will be simplified, e.g. basic stack implementation (FIFO).

Algorithms in JavaScript

Today we will focus more on examples of solutions, rather than the theory.

Factorial

A classic example at start — Factorial and recursion.

Example — calculating factorial in JavaScript:

function factorial(n) {
    if (n == 0)
        return 1;
    else
        return (n * factorial(n-1));
}

alert(factorial(5));

Leap year

The next algorithm is to check whether a given year is a leap year or not.


// is leap year - JavaScript
function checkLeapYear(year) {
    if ( ((year % 4 == 0)
          &&
          (year % 100 != 0)) || (year % 400 == 0) ) {
        alert(year + ' is leap');

        return true;
    } else {
        alert(year + ' is NOT leap');

        return false;
    }
}

alert(checkLeapYear(2012));
alert(checkLeapYear(2013));

Min-Max algorithm

So determining the lowest and highest values ​​of the given set.

Example — implementation of the min-max algorithm in JavaScript:

var tab = new Array(16, 9, 86, 48, 59, 2, 78, 240, 18);
// default
var min = tab[0];
var max = tab[0];

for (var i = 0; i < tab.length; i++) {

    if (min > tab[i]) {
        min = tab[i];
    }

    if (max < tab[i]) {
        max = tab[i];
    }
}

alert("Min = " + min + ", Max = " + max);

It’s a simple, but effective implementation based on the comparison among elements in the array.

Random string

This algorithm is a simple generator of random string.

JavaScript WTF — strange elements of JS

This article is a little different. Namely, we revise the strange elements of JavaScript. Sometimes is called JavaScript WTF 🙂 Some are just funny, others cause debugging a bit longer. So let’s remember them, when our code starts to do weird things.

JavaScript WTF

Certainly much depends on the browser (implementation of JavaScript). In newer versions of the browser, some peculiarities can be removed / handled in a particular way.

NaN is a Number?

Not a Number (NaN) is a Number — welcome in JavaScript.

alert(typeof NaN); // 'Number'

alert(NaN === NaN); // false

To determine whether something is a number or not, simply use the isNaN() function.

Null is an object

alert(typeof null); // 'object'

“So what? In JavaScript everything is an object…”. Ok, but:

alert(null instanceof Object); // false

🙂

Functions can call themselves

Functions usually contain code to be executed at a specified time (calling the function). However, there is no blocking for code as below:

(function() { alert('hello'); })(); // 'hello'

So the function will be called and executed immediately.

0.1 + 0.2 equals 0.3 ?

Generally yes, but in JavaScript it’s 0.30000000000000004.

It’s about precision of floating point calculations. JavaScript implements it with a small oddity, which, however, can cause problems for developer working (especially comparing) with such numbers.

Just as in the following code, which unfortunately returns false:

var num1 = 0.1, num2 = 0.2, cmp = 0.3;
alert(num1 + num2 == cmp); // false

To avoid this, we can use for example a such workaround:

alert(num1 + num2 > cmp - 0.001 && num1 + num2 < cmp + 0.001);
// true

OK, who explored issues of handling floating point implementation knows that it is really a complicated subject.

Equal is not always equal

For example:

1 == 1; // true
'foo' == 'foo'; // true
[1,2,3] == [1,2,3]; // false

Comparison of arrays returns false. This is because, as in many other languages​​, operates in the references to the array, not the exact value.

XML in JavaScript

In this article we take a look on how to work with XML in JavaScript. About the processing of XML in JavaScript we already mentioned in an introduction to AJAX.

Today we go further, and of course will try to find solutions that help us in tasks related to XML.

XML in JavaScript

Though in JavaScript probably more popular is work with the JSON format, however, sometimes we have to deal with XML data.

For example, I prefer JSON, but in case of integrating the application with an external API, XML is imposed by the client.

Let’s move on to the examples, and start with test XML structure, defined as a string in JavaScript:

var inputXML = '<?xml version="1.0" ?><root>Tester</root>';

The inputXML variable is a simple string. The function presented below converts such string to the object (XML), so we will be able to operate in JavaScript.

function stringToXML(text) {
    try {
        var xml = null;

        if (window.DOMParser) {
            var parser = new DOMParser();
            xml = parser.parseFromString(text, "text/xml");

            var foundErr = xml.getElementsByTagName("parsererror");

            if ( !foundErr || !foundErr.length ||
                 !foundErr[0].childNodes.length) {
                return xml;
            }

            return null;
        } else {
            xml = new ActiveXObject("Microsoft.XMLDOM");
            xml.async = false;
            xml.loadXML(text);

            return xml;
        }
    } catch (e) {
        ;
    }
}

Using this function, we create an object based on a string containing XML, and then we process this object:

var xmldoc = stringToXML(inputXML);
var root_node = xmldoc.getElementsByTagName('root').item(0);
alert(root_node.firstChild.data);

I18n in JavaScript

I18n so internationalization, and also L10n, are important issues, whenever we create applications targeted for users from many countries.

I18n in JavaScript

Certainly, many solutions such as frameworks, SDKs for mobile apps and programming languages, have support for multiple languages ​​in developed application.

Today we try to find such solutions in JavaScript. We look at some of the ways to support multiple languages ​​in the JavaScript code.

Simple solutions for I18n in JavaScript (pure language)

Let’s start with the simplest of solutions, based on fundamental JavaScript structures. Such solutions may be sufficient for simple web applications.

Example — simple support for I18n in JavaScript:

// set language
var _lang = &quot;de&quot;;

// define translations
var hello_message_homepage = {
  en: &quot;English hello&quot;,
  fr: &quot;French hello&quot;,
  de: &quot;German hello&quot;,
  pl: &quot;Polish hello&quot;};

var introduction_text_homepage = {
  en: &quot;English text…&quot;,
  fr: &quot;French text…&quot;,
  de: &quot;German text…&quot;,
  pl: &quot;Polish text…&quot;};

// etc …

// get translation for current language
alert(hello_message_homepage[_lang]);
alert(introduction_text_homepage[_lang]);

In this example we simply display an alert with obtained translation. In practice it may be, for example, substitution of a text label of selected HTML element.

We used language symbols (en, de, etc) as keys of the array with translations for particular messages. Simple and effective.

Another way

In this case we introduce some order, and we will keep translations in separate files.


var _lang = &quot;de&quot;;

document.write(&quot;&lt;scr&quot;+&quot;ipt
  src='lang/&quot;+lang+&quot;/messages.js'&gt;&lt;/scr&quot;+&quot;ipt&gt;&quot;);

Having defined the files in lang/ directory, our script will include the appropriate file for the current language.

For example:

// file lang/en/messages.js
var hello_message_homepage = &quot;English hello&quot;;
var introduction_text_homepage = &quot;English text…&quot;;
// file lang/de/messages.js
var hello_message_homepage = &quot;German hello&quot;;
var introduction_text_homepage = &quot;German text…&quot;;

… and other languages, which we want to support.

When the script attach the file into HTML document, we refer to our variables, for example:

alert(hello_message_homepage), obtaining correct translation.

Mouse and keyboard in JavaScript

Welcome to the article, in which we will try to comprehensively but succinctly talk about working with the mouse and keyboard in JavaScript. We will also see how popular frameworks can help us.

Handling mouse and keyboard in JavaScript

Considerations we should start with events, because processing data from basic input devices will be based on event handling.

Events for the mouse in JavaScript:

onclick — single-click (press and release the mouse button),

ondblclick — double-click,

onmouseover — the mouse cursor is over the element (in the area of ​​an element),

onmousemove — the mouse cursor has been moved,

onmouseout — the mouse cursor is outside the element (left his area),

onmousedown — pressing the mouse button,

onmouseup — release the mouse button.

In addition, there are available (by object event) parameters for mouse events:

clientX and clientY — relative coordinates of the mouse cursor,

screenX and screenY — screen / absolute coordinates of the mouse,

button — the number of the pressed mouse button,

altKey — determines whether the Alt key is pressed,

ctrlKey — determines whether the Control key is pressed,

shiftKey — determines whether the Shift key is pressed.

The keyboard events are:

onkeypress

onkeydown

onkeyup

Handling mouse in JavaScript

Having to deal with the events, the first thing comes to mind is to implement handlers for them. This applies both to mouse and keyboard.

As in the following example:


document.onmousedown = mouseDown;

function mouseDown(e) {
  alert('Pressed …');
}

// document.onmousemove = xyz;
// myElement.onmouseup = foobar;
// etc …

We just assigned a handler for onmousedown event of an element (here for the document element). This is how it’s done.

Date and time functions in JavaScript

Today we take a closer look at ready-made tools to assist us in working with date and time. So libraries with functions to operate on date and time in JavaScript; formating, parsing, comparing, etc.

We already talked about basics of date and time functinos in JavaScript here. Now we turn to the more advanced tools.

The time functions in JavaScript

One of these types of tasks can be processing of date given as http://en.wikipedia.org/wiki/Unix_time to text and make it human readable.

We can write own function quickly:

function simpleTimeConverter(unix_timestamp) {
    var inputDate = new Date(unix_timestamp * 1000);
    var months = ['Jan','Feb','Mar','Apr','May','Jun',
                  'Jul','Aug','Sep','Oct','Nov','Dec'];

    var year = inputDate.getFullYear();
    var month = months[inputDate.getMonth()];
    var date = inputDate.getDate();
    var hour = inputDate.getHours();
    var min = inputDate.getMinutes();
    var sec = inputDate.getSeconds();

    var time = date + '. ' + month + ' ' + year + ' ' + hour;
    time += ':' + min + ':' + sec;

    return time;
}

var uxt = 1069497161;
alert(simpleTimeConverter(uxt)); // 22. Nov 2003 11:32:41

Maybe we don’t work with date and time in JavaScript everyday, but it’s good to have quick and tested solutions. So we need good libraries with time functions.

Below we placed solutions in our opinion worthy of attention.

Happy programmers’ day 2014!

Hello World and Happy programmers’ day 2014 for everyone!

Yes, today is our — programmers day!

We are celebrating programmers on the 256th day (2^8, Math.pow(2, 8)) of the Year!

So I wish us all the best, bug-free code, easy deadlines, amazing projects, great customers / managers.

But, wait, where’s your TP(S) report? 🙂

Office3_L

No way, not today!

Programmer Day is a day to celebrate Programmers and thank them for all that they do.