Friday, March 23, 2012

jQuery simple banner rotator plugin

Today I had a task, to create a simple image (banner) rotator in Javascript...so I thought: If I have to do it, then do it right and created a simple jQuery plugin. The code is really easy to understand... here is the essence of it:


setInterval(function () {
 var items = jQuery( jQuery(options.items, this).get().reverse());

 items.each(function () {
  // if visible, than hide
  if (jQuery(this).is(":visible")) {
   jQuery(this).fadeOut();

   return false;
  } 
 });

 // if nothing more to hide, show all
 if( jQuery(":visible", items).length <= 1 ) items.fadeIn();

}, options.timeout);


Basically there is an interval and it's hiding all the items backwards. When they are all hidden, then show them. Because the items are positionated "absolute" they are overlapping eachother. So when I hide one, another appears.


That's it. Simple and small! :)



Here is the full code:
jQuery.bannerRotate.js

Cheers,
Phil

Wednesday, March 14, 2012

How to build an HTML email

This is just a quick summary on how to create an HTML email:

DON'T use:
- "div"
- "padding"
- "background-image"

DO use:
- images
- "background-color" -s
- "width" with exact px values
- "table" -s (even if normally you would use a "div")
- inline styles everywhere

This list will be expanded over time and experience or if you have some own rule-of-thumb please share it with us.

Thursday, February 23, 2012

MySQL - Order users by address

Today I encountered a little SQL problem I had to solve...so here is the task:

Order the users by their address. Basically this isn't a big thing, but I had all the address parts separatedly in the database. There is a coloumn for the city, street...parts.

Here is the solution:

SELECT *, CONCAT_WS(' ', `users`.`zipcode`, `users`.`city`, `users`.`street`, `users`.`housenumber)` AS address FROM (`users`) ORDER BY `address` asc, `name` ASC


This is not such a great achievement, but it's good for reminding myself about this cool trick.

Wednesday, December 14, 2011

Javascript: Is date in range?

Today I encountered a little problem wich I had to solve with dates. I had to check, if today has a special event. The range is stored in a simple date format: YYYY.MM.DD-YYYY.MM.DD

Here is the solution:

var nowDate = new Date(2011, 12, 14).getTime();

var startDate = new Date(2011, 12, 13).getTime();
var endDate = new Date(2012, 1, 5).getTime();

if (startDate <= nowDate && nowDate <= endDate) {
 alert('It\'s in range!');
}


The "getTime()" method will create a timestamp from the created date. It's like a date in a number format wich can be easily compared to eachother.

Wednesday, October 26, 2011

Complete website on client side?

Javascript became very popular these days. There are countless frameworks and plugins developed to make our web developer life easier. But... I have a question.

What are the limits of Javascript? Can we make a complete website to work only on client side?

I'm developing a very interesting project recently. I have to solve everything (even content search) in the browser. The website has no contact to the internet at all...Yes. A website without internet connection or server contact. It will be an information box with touch screen on my former college. It will work as a digital doorman and it's quite nifty (and heavy like a mountain). Our designer did his job very well. It has now a very nice touch compatible interface. (Print screens and actual "in-use" images soon)

The computer runs on Ubuntu and unfortunately nobody knows the root password :) That's why I'm sticked with Firefox. The base hardware is... very environment (therefore not too user-experience) friendly, but I will do my best. Later, when I will have more time I will reinstall the system and use Chrome instead. The Javascript animations are much faster there. And I did a little test with flash. Surprisingly (at least for me) Opera handles Flash animation much more smoothly than any other browser. I designed a little active backgound for the whole system, and it looked awesome in Opera (I tested it with an Ubuntu live CD).

I have came up with a solution, I just want to test it. If it works, I will write a full post about it. If it won't than I will write it down, why it didn't worked.

But now I have a very tight deadline so I stop writing posts and go back to work :)

Sunday, October 23, 2011

JavaScript: Objects and the this keyword

Right now, I'm developing a complex jQuery plugin with a bunch of objects. Most of the these are connected together somehow in each others' definition. In one of these objects, the this keyword referenced to another object and I was not able to find a variable related to my object. The reason was I had to call one of its function in another context and with another this object. Here is the example:

var obj = function() {

    /* Private variables */ 
    var v1 = 0;
    var v2 = 0;
    
    /* Public variables */ 
    this.state = false;

    /* Public functions */
    this.update = function() {
       if(this.state) do_stuff();

       console.log(this.state); // undefined!!!
    }

};

So, when when I called the update function in another context with another this object, the this keyword referenced to the caller object, not to the object where it was. The result of this is that the state variable is undefined, because the caller object didn't have a state variable. I knew that the this keyword is the problem and I also knew that I need to reference to the object in its own functions. So the solution is to create a private variable and store a reference to the object in it.

var obj = function() {

    /* Reference to self */
    var _self = this;

    /* Private variables */ 
    var v1 = 0;
    var v2 = 0;
    
    /* Public variables */ 
    _self.state = false;

    /* Public functions */
    _self.update = function() {
       if(_self.state) do_stuff();

       console.log(_self.state); // false

       this.somethingElse = true;
    }

};

With this solution, if you create an object with the new keyword, the constructor is called and the _self variable will store a reference to itself. This won't mess up the this reference in other contexts.

Thursday, October 20, 2011

JavaScript: Drawing and appending an Image object

Let's have some fun with images tonight!

The <img/> tag is part of HTML, as you've already known from your previous studies in web technologies. :) You can create one programmatically with the Image object in JavaScript. See below:

var img = new Image();

Try to log it to the console. Right know, it's empty. To load an image, use the src tag:

var img = new Image();

// of course, don't forget to replace this url ;)
img.src = 'http://www.testsite.com/images/myimage.jpg';

The image is loaded, but you can't see it yet, because it isn't appended to the DOM. Let's use jQuery to do what is needed to do!

jQuery('#myDiv').html(img);

The image is visible right know. This JavaScript object has another property called onload. It fires when the image is loaded. Append these few lines after your code and refresh your page:

img.onload = function() {
    alert('image loaded');
}

In Internet Explorer, the onload function won't run, unless you place it before the definition of src attribute:

var img = new Image();

img.onload = function() {
    alert('image loaded');
}

img.src = 'http://www.mysite.com/images/an_image.jpg';

Go and have some fun with the onerror attribute! It runs when an error occurs while loading an image.

var img = new Image();

img.onerror = function() {
    alert('failed to load image :( ');
}

img.src = 'http://www.fakelink.com/images/non_existing_image.png';


Canvas element and Javascript drawImage function

Another way to use the image object is to draw it with the help of the canvas element. First, have one in your example html page:

<canvas id="myCanvas" width="400" height="300"></canvas>

Then, get the canvas and a context and use drawImage function.

var canvas = $("#myCanvas");

/* For browser compatibility issues, put error handling code here. I won't.. */
var ctx = canvas[0].getContext('2d');

var img = new Image();
img.src = 'http://static.yoursite.com/images/something.png';

ctx.drawImage(img, 0, 0);

The first parameter of the drawing function is the image object itself. The second and third parameters are for placing the image along the x and y coordinates. Note that the (0, 0) coordinate is the top left corner. Also note that canvas element is not supported yet in Internet Explorer.

That's all for today of the JavaScript Image object and its usage. I will tell more about the drawImage function in another post where I will talk about sprites, animation and a bit more JavaScript tricks. I hope you learned a little new today.