Showing posts with label javascript. Show all posts
Showing posts with label javascript. Show all posts

Jan 1, 2018

Using SVG color filters

This is a follow on from my previous post about showing a sprite image using the SVG.js library. We will now add a colour filter to the image using the svg.filter.js plugin.

The color matrix is a 5 column, 4 row matrix. Each row represents an RGBA value, and each column is a multiplier for that particular colour value. Every column represents an RGBA multiplier, which intensifies (or reduces) the resulting colour value based on the original input value. The last column is just a straight value that just gets added on.

So for the following matrix:

1 0 0 0 0
0 1 0 0 0
0 0 1 0 0
0 0 0 1 0

The output image will have the exact same colour value as the input image. This is because the the RGBA multipliers simple times the input RGBA value by 1.

Here are some resources:


The following code shows off the concept.

var col = {
    x: 2,
    y: 0,
}
var draw = SVG('drawing2').size(300, 300)
var clip = draw.clip()
var rect = draw.rect(32, 32)
var image = draw.image('http://icons.iconarchive.com/icons/iconfactory/star-trek-ships/icons-390.jpg')

image.move(-1*(32+5)*col.x-5,-1*(32+5)*col.y-5);

image.filter(function(add) {
  add.colorMatrix('matrix', [ 1.0, 0,   0,   0,   0
                            , 0,   0.2, 0,   0,   0
                            , 0,   0,   0.2, 0,   0
                            , 0,   0,   0,   1.0, 0 ])
})
clip.add(rect)

image.clipWith(clip)

Dec 10, 2017

Using SVG.js to clip an image sprite

Let's say you have an image with few sprites in it (such as Star Trek: Starships by Corey Marion):


Let's also say you are using a SVG javascript library such as svgjs to build dynamic images and animations. You want to overlay an icon sprite on top of your existing image. To do this you use the following code:


var col = {
    x: 0,
    y: 0,
}
var draw = SVG('drawing2').size(300, 300)
var clip = draw.clip()
var rect = draw.rect(32, 32)
var image = draw
    .image('http://icons.iconarchive.com/icons/iconfactory/star-trek-ships/icons-390.jpg')
    .move(-1*(32+5)*col.x-5,-1*(32+5)*col.y-5)
clip.add(rect)

image.clipWith(clip)

An explanation of the code:
  • The col object stores the row and column coordinates for the icon we want. We have 9 columns and 6 rows to work with.
  • The draw object takes our HTML div object and uses it to make our SVG
  • The clip object is where the magic happens
  • The rect object is a standard rectangle, which is going to be used as our 'frame' to cut out our desired sprite using clip. It is 32x32 pixels because that is the size of our icons.
  • The image object is our compiled sprites, but note that we 'move' it relative to the rectangle  using an algorithm. This 'move' allows us to align our desired sprite so that is with the rectangle.
  • The next two lines allows us to 'clip' the image with the rectangle, cutting away everything else except for our desired sprite.
The next example expands upon the above, but now allows us to place our rect (and our sprite) at a desired point on the drawing.


var col = {
    x: 8,
    y: 1,
}
var pos = {
    x: 32,
    y: 32
}
var draw = SVG('drawing2').size(300, 300)
var clip = draw.clip()
var rect = draw.rect(32, 32).move(pos.x, pos.y)
var image = draw
    .image('http://icons.iconarchive.com/icons/iconfactory/star-trek-ships/icons-390.jpg')
    .move(-1*(32+5)*col.x-5+pos.x,-1*(32+5)*col.y-5+pos.y)
clip.add(rect)


image.clipWith(clip)

Aug 1, 2017

Webpack, code-splitting, require & require.ensure()

Webpack allows for global definitions to be defined and set, allowing for compile time switches. This is especially useful when compiling a single source for multiple targets.

require() will include the target as a whole, while require.ensure() will create a code split point. Paired with the above concept of Webpack compile time switches, this allows us to define a code-splitted and and non-split version of our code.

An example:

In webpack.config.js:


plugins: [
    new webpack.DefinePlugin({
        BUILD_PDF: JSON.stringify(true),
    }),
]

In the target .js source:


if (BUILD_PDF) {
    require(....),
} else {
    require.ensure([], () =>{
        require(....);
    }, err => {
        // error code
    }, "split-name");
}

Apr 11, 2014

Extending the JavaScript HTML5 Canvas object

I have been playing with JavaScript, trying to find new and interesting way to use it in browsers. I have found the wonder that is CANVAS, which allows you to do a whole lot of drawing and animation tasks.

The problem is that the features are low-level, meaning you need to write a lot of code to make anything useful or interesting. A nice technique is to use the prototyping feature of JavaScript to extend the features of canvas. Here are some examples:

if (window.CanvasRenderingContext2D) {
    /**
     * Rounded Rectangle
     */
    CanvasRenderingContext2D.prototype.roundedRect = function(x, y, width, height, radius, colour, border, lineWidth, alpha) {
        // if certain values are not set just exit
        if(!x || !y || !width || !height) { return true; }
        // Set other values
        if (!radius) { radius = 5; }
        if (!alpha) { alpha=1; }
        // Start drawing the rounded rectangle
        this.beginPath();
        this.moveTo(x + radius, y);
        this.lineTo(x + width - radius, y);
        this.quadraticCurveTo(x + width, y, x + width, y + radius);
        this.lineTo(x + width, y + height - radius);
        this.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
        this.lineTo(x + radius, y + height);
        this.quadraticCurveTo(x, y + height, x, y + height - radius);
        this.lineTo(x, y + radius);
        this.quadraticCurveTo(x, y, x + radius, y);
        // Colour it in
        if (colour) {
            this.globalAlpha = alpha;
            this.fillStyle = colour;
            this.fill();
        }
        // Add in optional border
        if (border) {
            this.lineWidth = (lineWidth) ? linewidth : 1;
            this.strokeStyle = border;
            this.stroke();
        }
        // Reset Alpha if it was changed
        this.globalAlpha = 1;
        this.closePath();
    };
    /**
     * Ellipse
     */
    CanvasRenderingContext2D.prototype.ellipse = function(x, y, width, height, colour, border, lineWidth, alpha) {
        // if certain values are not set just exit
        if (!x || !y || !width || !height) { return true; }
        if (!alpha) { alpha=1; }
        // Calculate some points
        var xLeft = x - (width / 2);
        var xRight = x + (width / 2);
        var yTop = y - (height / 2);
        var yBot = y + (height / 2);
        // Draw the ellipse
        this.beginPath();
        // NOTE: The moveTo() is needed to start the drawing from the correct spot
        this.moveTo(x, yTop);
        // Start drawing two bezier curves to create an ellipse
        this.bezierCurveTo(xRight, yTop, xRight, yBot, x, yBot);
        this.bezierCurveTo(xLeft, yBot, xLeft, yTop, x, yTop);
        // Colour it in
        if (colour) {
            this.globalAlpha = alpha;
            this.fillStyle = colour;
            this.fill();
        }
        // Add in optional border
        if (border) {
            this.lineWidth = (lineWidth) ? linewidth : 1;
            this.strokeStyle = border;
            this.stroke();
        }
        // Reset Alpha if it was changed
        this.globalAlpha = 1;
        // Finish the drawing
        this.closePath();
    };
    /**
     * Rounded arcs and circles
     */
    CanvasRenderingContext2D.prototype.circularArc = function(x, y, radius, startAng, endAng, colour, border, lineWidth, enclosed, direction, alpha) {
        // if certain values are not set just exit
        if (!x || !y || !radius) { return true; }
        // Set other values
        if (!alpha) { alpha=1; }
        if (!startAng) { startAng = 0; }
        if (!endAng) { endAng = Math.PI; }
        if (!direction) { direction = false; }
        // Start drawing
        this.beginPath();
        this.arc(x, y, radius, startAng, endAng, direction);
        if (enclosed) {
            this.closePath();
        }
        // Colour it in
        if (colour) {
            this.fillStyle = colour;
            this.fill();
        }
        // Add in optional border
        if (border) {
            this.globalAlpha = alpha;
            this.lineWidth = (lineWidth) ? lineWidth : 1;
            this.strokeStyle = border;
            this.stroke();
        }
     // Reset Alpha if it was changed
        this.globalAlpha = 1;
        // Finish the drawing
        this.closePath();
    };
}

References

Feb 27, 2014

JavaScript cheat-sheet: Basic

If you are here to learn how to code in JavaScript, I highly suggest you DON'T use this as your only resource. Go to CodeAcademy or w3schools to get a more comprehensive guide to coding.

=== means equals to (useful in if statements)
!== means not equal to (again, useful in if statements)

Primitive Data Types:
Strings are created simply by opening up a pair of quotation marks (")
Numbers are integers or floats (such as 4 or 3.14)
Booleans are only true and false values (you simply write "true" or "false", without quotes)

% is the modulo operator. It prints the remainder of division operation.

confirm("Do you want to continue?");
Will display a confirm dialogue box. Returns a true or false.

alert("Something went wrong");
Only displays a dialogue box (use if you do not care about user input)

prompt("Enter in your name:");
Will display a dialogue box with text input. Returns the input as a string.

console.log("This message will be printed to your console (not the HTML page)");
Prints a message to the JavaScript console (this is usually found on a developer dashboard in browsers)

"This is a string".length;
Returns the character length of a string

"This is a string".substring(x, y);
Print out the portion of the string, with 'x' the character to start cutting from and 'y' the final character

var name = "String";
Assigning a variable (in this case a string)

"This is a String".match(/string/i)
This is string pattern matching, or Regular Expressions. Please see elsewhere how to use Regular expressions

var newArray = ["item 1", "item 2"];
Assiging an array of items.

var newFunction = function(variable) { return variable; };
Declaring a new function called newFunction, which can be called as newFunction("String")

var newObject = { key: "value", key2: 10, key3: function(value){ return value; } };
Declares a new object called newObject, with three properties.

var testObject = new newObject; testObject.key;
Declaring a new testObject of type newObject, and accessing the 'key' property

if (true) { return "True"; } else { return "False"; }
An "IF" conditional statement (with optional "ELSE")

for (var i = 0; i < condition; i++) { condition--; }
A "FOR" loop statement, with increment and decrement operators

switch (name) { case "value": return name; break; default: return false; }
A "SWITCH" or "CASE" statement.

while (value < 5) { value++; }
A "WHILE" loop.

try { arbitraryFunction(); } catch (err) { alert(err) }
A "try-catch" block.

throw "This is an error message";
An error thrown that is meant to be caught by a try-catch block. This just throws a simple string.

Math Object constants
Math.E
Math.PI
Math.SQRT2
Math.SQRT1_2
Math.LN2
Math.LN10
Math.LOG2E
Math.LOG10E

Math.round(4.13);
Rounds the number to the nearest integer (in this example it will output 4)

Math.random()
Output a pseudo-random number between 0 and 1

document.getElementById("id");
Returns the HTML DOM element that matches the given id string

document.getElementsByClassname("class");
Returns the array of HTML DOM elements that matches the given class string

document.getElementById("id").innerHTML;
Gets (or sets) the HTML that is in between the element tag (make sure you note the capitalisation)

document.createElement("name");
Creates an DOM element (but it is not attached automatically!)

Sep 7, 2013

AJAX with JQuery and Google App Engine: Python

This is an adaption of AJAX with JQuery and PHP. It is a continuation of my Python 2.7 and Google App Engine series, and portions of the code builds upon my earlier work.

A first example...

AJAX stands for Asynchronous JavaScript And XML, and allows us to make our websites seem more dynamic. Let's start with the JavaScript side of things...

Create a file called static.html and add the following:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
    <head>
       <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
       <title>Ajax With Jquery</title>

       <!-- Grab the JQuery API from the Google servers -->
       <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js" type="text/javascript" charset="utf-8"></script>

       <!-- Our own JQuery code to do the AJAX-y stuff -->
       <script type="text/javascript" charset="utf-8">

          $(document).ready(function(){
             $('#txtValue').keyup(function(){
                 $('#display').html($(this).val());
             });
          });

       </script>
    </head>

    <body>
       <label for="txtValue">Enter a value : </label>
       <input type="text" name="txtValue" value="" id="txtValue">

        <div id="display"></div>
    </body>
</html>

Create a file called app.yaml and add the following:
application: almightynassar
version: 1
runtime: python27
api_version: 1
threadsafe: yes

handlers:
- url: /(.*).html
  static_files: \1.html
  upload: (.*).html

The above will simply serve ALL html page requests directly (which is enough for this example).

Now, if you are using Eclipse just right click on the project, select 'Run As' and choose the 'PyDev: Google App Run' option. Depending on how you configured your Google SDK, it will start up a server on your machine on port 8080. Open up a new tab and navigate to http://localhost:8080/static.html. You should now see a text box; when you type into the box it will automatically display the text in the space below.

Something a little more AJAX - The HTML

So our original example just showed how we could manipulate the DOM (Document Object Model) of the browser during run-time, without a page refresh. How can we use this knowledge utilizing the power of Google App Engine? Well, first let us edit static.html to something we can manipulate:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
       <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
       <title>Ajax With Jquery</title>
     
       <!-- Grab the JQuery API from the Google servers -->
       <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js" type="text/javascript" charset="utf-8"></script>

       <!-- Our own JQuery code to do the AJAX-y stuff -->
       <script type="text/javascript" charset="utf-8">
       $(document).ready(function(){
            // This will run when the item of class 'button' is clicked
            $(".button").click(function() {
               
                // Grabs the text input
                var name = $("input#txtValue").val();
        
                var dataString = 'txtValue='+ name;  
                // This creates the AJAX connection
                $.ajax({
                    type: "POST",
                    url: "/tutorial",
                    data: dataString,
                    success: function(data) {
                        $('#display').html(data.text);
                    }
                });
            return false;
            });
        });
       </script>
    </head>

    <body>
         <form name="contact" method="post" action="">
            <label for="txtValue">Enter a value : </label>
            <input type="text" name="txtValue" value="" id="txtValue">
            <input type="submit" name="submit" class="button" id="submit_btn" value="Send" />
         </form>
         <div id="display">
         </div>
   </body>
</html> 

Our JavaScript now sends some data to an external URL (in this case /tutorial) and inserts the returned data into the display div. Now all we need to do is code our Python script....

Our Python webapp

Create a file called tutorial.py and add the following code:

# The webapp2 framework
import webapp2

# The JSON library
import json

# Our JSON handler class
class JsonPage(webapp2.RequestHandler):
    # The POST handler
    def post(self):
        # Our POST Input
        txtinput = self.request.get('txtValue')
       
        # Create an array
        array = {'text': txtinput}
       
        # Output the JSON
        self.response.headers['Content-Type'] = 'application/json'
        self.response.out.write(json.dumps(array))

# URL map the JSON function
app = webapp2.WSGIApplication([('/tutorial', JsonPage)], debug=True)

Now we just need to edit app.yaml so it can serve up our tutorial script:

application: almightynassar
version: 1
runtime: python27
api_version: 1
threadsafe: no

handlers:
- url: /(.*).html
  static_files: \1.html
  upload: (.*).html

- url: /(.*)
  script: tutorial.app

Open up a new tab and navigate to http://localhost:8080/static.html. You should now see a text box with a button called 'Send'. Typing into this box and then clicking 'Send' will transmit the text to our tutorial script and then display the text in the space below.

References:

Aug 23, 2013

Coursera Notes: Stanford 'Start-up Engineering' (Lectures 5-8)

These are just some of my notes from Coursera's 'Start-up Engineering' course, taught by Balaji Srinivasan from Stanford.

This is a continuation of my existing series of notes.

Market Research, Wire-framing and Design

  • Idea \ne Mock-up
    Mock-up \ne Prototype
    Prototype \ne Program
    Program \ne Product
    Product \ne Business
    Business \ne Profit
  • Execution! It is not the idea, but the execution that matters. Sales rather than technology is what builds a business.
  • Market! Market will draw a product from a team, whether or not it is quality or the team is good.
  • An idea exists within a maze. A simple sentence is not enough to describe an idea; an idea is defined by the regulations, markets, and competition.
  • Execution mindset. This is essentially writing a to-do list and regularly checking off items. Rinse and repeat.
  • Market Research:
    1. News coverage and research papers. Google Books, SEC filings and Wikipedia.
    2. Back-of-envelope estimate of market size. Look for relevant statistics.
    3. Validate. Google keyword planner and Facebook advertiser tools help determine if there is actually a market need.
    4. Do a basic launch page with basic SEO. Use wireframes.
    5. Ad-word to discover the market. The launch page will then gauge market interest.
  • MVP or Minimum Viable Product.
  • Remember, a start-up aims to be very ambitious and scale rapidly.
  • Two features of successful start-ups:
    1. Exhibit economies of scale. Cost of production per unit decreases as more units are built (but revenue stays the same). We can then determine a break-even point and therefore the minimal capital required.
    2. Attack/Pursue large markets. Different pricing will attract different markets, but low price points require automation and industrial efficiency to make profits (because customer service is expensive). It may be better to charge higher initially to counter risks. Market sizing calculations should be done early and often.
  • Once a market and broad perspective has been set, versions and features need to be prioritized. Remember, it is execution and sales that matter!
  • Rough guide to prioritizing versions and features:
    • How much are they willing to pay for certain features or versions?
    • Which features are required in each version? What features make sense to bundle together?
    • Estimate the time and cost to build each feature. Is it feasible to implement the feature now, or wait for more funding?
    • Find the most popular features.
    • Calculate the market size for each feature.
  • Wireframing tools: omnigraffle, lucid chart, jet strap and popapp.
  • Copy-writing:
    • Home-page message must allow a customer to immediately figure out what the product is. This is a priority if this is going to be a major source of potential customers.
    • Work backwards from the press release (write the release then build the product). This allows you to figure out which features are making the news and which are not.
    • Find your competitors and explain why they are terrible options. Use this insight when explaining the benefits of your product.
    • Simple, factual and concise statements.
    • Call to action. Allow the customer to do something once they visit your website.
  • Vector graphics are better to work with.
  • In design remember Alignment, Repetition, Contrast and Proximity.
  • Start with a font heavy design (it is easier to do and images can always come later)

Mobile

  • Assumption behind the mobile phenomenon is that everything is going to be on the internet. The internet is going from a novelty to a utility.
  • Build for HTML5 and then move to native apps. HTML5 ensure your application works on all devices (and Android will soon utilise HTML5 and Javascript instead of native applications).
  • Internet of Things is the idea that every device will have it's own IP address. This offers a huge potential market.
  • Quantified self is the measuring of human beings and our actions. This is the collection of metrics that may revolutionize diagnosis and medicine.
  • One way to build mobile-aware applications is user-agent sniffing. This approach has the problems that a client can fake their own user-agent, and that the user-agent is inherently unreliable.
  • CSS media queries and Responsive web design allows the application of conditional styles depending on screen size. This is much more reliable, but does not have ubiquitous support (yet).
  • Some constraints with mobile include:
    • Unreliable networks (the fallacies of distributed computing)
    • Debugging requires logging (and bug reporting)
    • Minimization of user input (difficult problem to solve; how to collect everything you need without overwhelming the user)
    • Minimize the time to result (if you take too long the user will go elsewhere)

HTML / CSS / Javascript

  • HTML is the skeleton of a web application. It provides the structure of a page and the semantics. It is a set of finite elements with attributes.
  • CSS is the look and layout of a web application. It edits the element and attributes for styling and formatting.
  • Javascript is the dynamics and behavior of a web application. It allows you to provide client-side validation, pulling in content, playing games and much more.
  • Some useful tools include jsfiddle.net and Chrome Developer Tools.

Deployment, DNS and Custom Domains

  • Your code production environments should be along the lines of Development -> Staging -> Production
  • Separating environments bring the following benefits:
    • Testing of features before they reach the customer
    • Roll back of code in case of major bugs
    • Restore code or data in case of catastrophic crashes of the server
    • Incorporate contributions from multiple engineers
    • Perform AB testing of features
  • DNS (Domain Name System) converts IP address into human readable hostnames. The system first looks locally in a program, then the OS, then the ISP and then finally a trusted internet DNS server.

Nov 12, 2012

Get page width dynamically with Javascript (or JQuery)

This quick script will display the current width of your browser window (useful for creating responsive web designs).

The HTML

Simply make a <div> element, which we will be used by JQuery to print out the window width:
<html>
  <body>
    <div id="dimensions">
      <span class="width"></span>
    </div>
  </body>
</html>

JQuery method

If you already use JQuery, then this is for you. If you aren't using it, you should consider it; it makes programming in Javascript a breeze!

To use this snippet, just download the JQuery library, link it into your page and add the following script:

<script>
  $("#dimensions .width").html($(window).width());
  $(window).resize(function(){
    $("#dimensions .width").html($(window).width());
  });

</script>

Javascript method

If you don't have JQuery this should work equally well:

<script>
  window.onresize = displayWindowSize;
  window.onload = displayWindowSize;
  function displayWindowSize() {
    // your size calculation code here
    document.getElementById("dimensions").innerHTML = myWidth + "x" + myHeight;
  };
</script>

Further reading

You can also browse my other content such as:

Jul 18, 2012

AJAX, JQuery, CodeIgniter and PHP

This is an extension of an earlier blog of mine, but this time I have built it using the CodeIgniter PHP framework. I have also spiced it up with a dynamic JQuery form (kudos to Charlie Griefer and this blog post for the code!)

If you want to get your hands dirty doing something a little harder then I suggest you check out my earlier blog on creating a login system with CodeIgniter.

If you are just getting started, have a look at my other blog posts, 'Ubuntu, LAMP and CodeIgniter' and the 'Extended JQuery Tutorial'.

Getting started

I am going to assume that you are working with a fresh installation of CodeIgniter that simply displays the welcome message. I am going to start from there so we don't get into any confusion!

First, unzip the CodeIgniter source into your web-server's root directory (if you followed my LAMP guide above, this will default to /var/www/). Rename the extracted folder to test (so in the default example, the CodeIgniter framework will be stored in /var/www/test/).

Now delete ALL the php files in /var/www/test/application/controllers and /var/www/test/application/views. We are going to start completely fresh!

The final step is to configure the framework to use our new controller (once we create it...), so edit the file /var/www/test/application/config/routes.php with the following line:
$route['default_controller'] = "home";
Now to make our main controller....

The Home page controller

  1. Create a file in /var/www/test/application/controllers named home.php
  2. Add in the following code:
    <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

    class Home extends CI_Controller {

        /**
         * Index Page for the home controller.
         *
         * Maps to the following URL
         *         http://example.com/
    index.php
         *    - or - 
         *         http://example.com/index.php/home
         *    - or -
         * Since this controller is set as the default controller in
         * config/routes.php, it's displayed at http://example.com/
         *
         * So any other public methods not prefixed with an underscore will
         * map to /index.php/home/<method_name>
         * @see http://codeigniter.com/user_guide/general/urls.html
         */
        public function index()
        {
            $this->load->view('view');
        }
    }

    /* End of file ajax.php */
    /* Location: ./application/controllers/home.php */
  3. That's it. All this does is load up our view, which is our next step.

The Home page view

  1. Create a file in /var/www/test/application/views named view.php
  2. Add in the following code:

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <title>Test</title>

    <!-- JQuery code hosted by Google -->
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>

    <!-- Adding and Deleting form buttons -->
    <script type="text/javascript" src="form.js"></script>

    <!-- AJAX functionality -->
    <script type="text/javascript" src="ajax.js"></script>
    </head>

    <body>

    <form id="myForm">
    <div id="input1" style="margin-bottom:4px;" class="clonedInput">
    Name: <input type="text" class="name" name="name1" id="name1" />
    </div>

    <div>
    <input type="button" id="btnAdd" value="add another name" />
    <input type="button" id="btnDel" value="remove name" />
    <input type="button" name="submit" class="button" id="submit" value="Send" />
    </div>

    <div id="display">
    </div>
    </form>

    </body>
    </html>
  3. Our basic HTML page includes three JavaScript files (One is the JQuery API, the other two we write ourselves; see below). We have a form with an input text box and three buttons. The first two buttons add and remove input boxes from our form, while the last button performs our AJAX operation.

form.js - Dynamically adding form elements

  1. Create a file called form.js in /var/www/test/
  2. Add the following code:
    $(document).ready(function() {
                $('#btnAdd').click(function() {
                   

                    // how many "duplicatable" input fields we currently have

                    var num     = $('.clonedInput').length;                // the numeric ID of the new input field being added
                    var newNum  = new Number(num + 1);
     
                    // create the new element via clone(),
                    // and manipulate it's ID using newNum value
                    var newElem = $('#input' + num).clone().attr('id', 'input' + newNum);
     
                    // manipulate the name/id values of the input inside the new element
                    newElem.children(':first').attr('id', 'name' + newNum).attr('name', 'name' + newNum);
     
                    // insert the new element after the last "duplicatable" input field
                    $('#input' + num).after(newElem);
     
                    // enable the "remove" button
                    $('#btnDel').attr('disabled','');
     
                    // business rule: you can only add 5 names
                    if (newNum == 5)
                        $('#btnAdd').attr('disabled','disabled');
                });
     
                $('#btnDel').click(function() {
                   
    // how many "duplicatable" input fields we currently have
                    var num = $('.clonedInput').length;

                   
    // remove the last element
                    $('#input' + num).remove();
     
                    // enable the "add" button
                    $('#btnAdd').attr('disabled','');
     
                    // if only one element remains, disable the "remove" button
                    if (num-1 == 1)
                        $('#btnDel').attr('disabled','disabled');
                });
     
                $('#btnDel').attr('disabled','disabled');
            });
  3. This function attaches a JavaScript function to the add and remove button. The code is pretty well commented by Charlie Griefer, so if you want to know more I suggest you go visit his blog post.

ajax.js - AJAX with JQuery

  1.  Create a file called ajax.js in /var/www/test/
  2. Add the following code:
    $(document).ready(function() {
        // This will run when the item of id 'submit' is clicked
        $("#submit").click(function() {

        // Grabs the text input
    from the form
        var name = [];
        $(".name").each(function() { name.push($(this).val()) });

        // Create the key-value pair for POST

        var dataString = 'string=' + name.join(' ') + '';

        // This creates the AJAX connection
        $.ajax({
           type: "POST",
           url: "index.php/ajax",
           data: dataString,
           dataType: 'json',
           success: function(obj) {
              $('#display').html(obj.message);
           }
        });
        return false;
        });
    });
  3. This will send all of our dynamically generated form elements to index.php/ajax (which we will now create). Hopefully the code and comments are self explanatory; if you have any problems just shout out in the comments!

The AJAX controller

  1. Create a file in /var/www/test/application/controllers named ajax.php
  2. Add the following code:
    <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

    class Ajax extends CI_Controller {


       /**

        * Index Page for this controller.
        *
        * Maps to the following URL
        * http://example.com/index.php/ajax
        * - or -
        * http://example.com/index.php/ajax/index
        *
        * So any other public methods not prefixed with an underscore will
        * map to /index.php/ajax/<method_name>
        * @see http://codeigniter.com/user_guide/general/urls.html
       */
       public function index()
       {
           $txtValue = "We have recieved: " . $this->input->post('string');

           echo json_encode(array('message' => $txtValue));

       }
    }

    /* End of file ajax.php */

    /* Location: ./application/controllers/ajax.php */
  3. You should now be able to run this on your web-server and have a dynamic form that sends and recieves AJAX!

References:

Apr 19, 2012

Extended Jquery tutorial

This tutorial is an extension of the basic JQuery tutorial. We will not cover the same stuff here, so if you want a quick and easy primer on JQuery please click on that link. Instead, this offers some extra background information that help put the code examples into context.

You might also want to check out my other posts such as the JQuery Slideshow or AJAX with JQuery and PHP.

What is JQuery?

JQuery is a client-side JavaScript library that can do a wide variety of tasks. This includes browser effects, AJAX, and interact with the DOM. Despite the introduction of CSS3 (which will elegantly handle browser effects and limited DOM manipulation), JQuery still has alot to offer the web developer. It has also been around for longer which means, for the moment, it has better cross-browser support.

JQuery is not meant to be used as an application framework. It does not provide a blueprint around which a developer can build a website. Instead, it offers a wide set of tools to make development much, MUCH easier.

Getting started...

Getting started with jQuery is easy; download the library script from the website and include it in your web-application as you would any other JavaScript file. Alternatively, Google provides live hosting of the jQuery so you could link to that to save on your bandwidth.

<!-- Include the JQuery Library code... JQuery will not work without this -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>


Selectors

JQuery works best by manipulating the DOM (the fancy, technical name given to the HTML page displayed by the browser), but to do this it needs a way of finding the elements to manipulate. To do this jQuery sports a CSS selector engine, meaning you just use standard CSS nomenclature to select an element.

For instance, if we had a div element with an id set to foo, in CSS we would write #foo {} to declare the style for that id. In JQuery, to search for and manipulate element foo you would write:

$('#foo').function()

Make sure the DOM is ready!

A common problem new developers have with jQuery is they start querying the DOM before it is ready. Browsers sometimes execute JavaScript before they have completely parsed the DOM, and this leads to errors where you manipulate the #foo class but it has not loaded on the page yet.

This problem is solved by calling the jQuery function that waits until the DOM has completely loaded:

$(document).ready(function {
      $('#foo').css('colour', 'red');
});

References:

Mar 9, 2012

AJAX with JQuery and PHP

AJAX stands for Asynchronous JavaScript And XML, and allows us to make our websites seem more dynamic.

A first example...

Our first example outlines how this is done within a single page:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
    <head>
       <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
       <title>Ajax With Jquery</title>

       <!-- Grab the JQuery API from the Google servers -->
       <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js" type="text/javascript" charset="utf-8"></script>

       <!-- Our own JQuery code to do the AJAX-y stuff -->
       <script type="text/javascript" charset="utf-8">

          $(document).ready(function(){
             $('#txtValue').keyup(function(){
                 $('#display').html($(this).val());
             });
          });

       </script>
    </head>

    <body>
       <label for="txtValue">Enter a value : </label>
       <input type="text" name="txtValue" value="" id="txtValue">

        <div id="display"></div>
    </body>
</html>



Pretty much all this will do is update the display section of of the page with the latest text in the text box. The event the script will listen for is a 'Key Up' event on the txtValue item. Pretty simple really...

Something a little more AJAX - The HTML

So our original example just showed how we could manipulate the DOM (Document Object Model) of the browser during run-time, without a page refresh. How can we use this knowledge utilizing the power of PHP? Well, first let us edit our HTML to something we can manipulate:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
       <meta http-equiv="Content-type" content="text/html; charset=utf-8" />

       <title>Ajax With Jquery</title> <!-- Grab the JQuery API from the Google servers -->
       <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js" type="text/javascript" charset="utf-8"></script>

       <!-- Our external JS script file... we will write this up later -->
       <script src="tutorial.js"></script>
    </head>

    <body>
         <form name="contact" method="post" action="">
            <label for="txtValue">Enter a value : </label>
            <input type="text" name="txtValue" value="" id="txtValue">
            <input type="button" name="submit" class="button" id="submit_btn" value="Send" />
         </form>
         <div id="display">
         </div>
   </body>
</html>

The JavaScript and JQuery file

Now we need to create the JavaScript file:

$(function() {
    // This will run when the item of class 'button' is clicked
    $(".button").click(function() {
 
         // Grabs the text input
         var name = $("input#txtValue").val();
         var dataString = 'txtValue='+ name;
         // This creates the AJAX connection
         $.ajax({
            type: "POST",
            url: "tutorial.php",
            data: dataString,
            dataType: 'json',
            success: function(data) {
               $('#display').html(data.text);
            }
         });
         return false;
    });
});

This simply sends data to an external php script (tutorial.php) and then change the contents of <div id="display"> to whatever it returns. This is much more AJAX-y.

The PHP file

The final thing we have to do is write the PHP output...

<?php
if (isset($_POST['txtValue'])) {
    $txtValue = stripslashes(strip_tags($_POST['txtValue']));
} else {$txtValue = 'Nothing';}
    echo json_encode(array('text' => $txtValue));
?>


Of course, there are multiple ways of achieving the same result, but this should help you get started.

Reference

Dec 21, 2011

Basic JQuery Tutorial

I have been playing with JQuery and I am falling in love with it. It offers you a simple way to add powerful features to any website; I don't think there is anything out there that compares. If there is, please let me know so I can try it out!

Anyway, the purpose of this post is to offer a brief code example that uses JQuery to manipulate the DOM of your website. I also provided some references that I used, so if you want to do some exploring just click away!

What you need:

  • The JQuery framework for JavaScript
  • Some knowledge of HTML, CSS and Javascript
  • A web-server such as Apache or nginx

Summary:

This post will show a couple of quick 'Hello World' examples, followed by a quick overview of some interesting functions available in JQuery.

Hello world: Example 1

The following code includes HTML comments to explain the code:

<html>
    <head>
       <title>jQuery Hello World</title>

        <!-- Include the JQuery Library code... JQuery will not work without this -->

        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
    </head>

    <!-- Our JQuery function. This will search for #flag and inject the Hello world text -->

    <script type="text/javascript">
        $(document).ready(function(){
            $("#flag").html("Hello World !! (display due to jQuery)");
        });

    </script>
 

    <body>
        <!-- Note that this is empty, but upon execution will contain text -->
        <div id="flag">
        </div>
 
    </body>
</html>



Hello world: Example 2

This Hello World example differs slightly in that it now uses an alert box to display the text:

<html>
    <head> 
        <title>jQuery Hello World</title> 
        <!-- Include the JQuery Library code... JQuery will not work without this -->            <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script> 
    </head>
 
    <!-- Our JQuery function. This will output a text box on the click event -->
    <script type="text/javascript"> 
        $(document).ready(function(){
             $("#cl").click(function(){
                 alert("HELLO WORLD!"); 
            });
         });
     </script>
 
    <body> 
        <button id="cl">Click Me</button> 
    </body>
</html>



Editing and manipulating JQuery elements

This code will output the size of any div element that is of the "change" class:

alert($("div.change p").size());
// This will count any <p> element within <div class="change"></div>

This will slide a <p class="first"> element up or down to hide/show it when called:

$("div.change p.first:hidden").slideDown("slow");
$("div.change p.first:visible").slideUp("slow");

This will instantly change the CSS code of any <em> element within <div class="change"></div>:

$("div.change em").css({color:"#993300", fontWeight:"bold"});

References:

Dec 15, 2011

Jquery Slideshow

This was a little feature I wrote up for a website that wanted a slide-show. The code allows you to adjust some parameters and should be production ready, although it can definitely be optimised better. Feel free to post edits or comments!

What you need:

  • The JQuery framework for JavaScript
  • Some knowledge of HTML, CSS and Javascript
  • A web-server such as Apache or nginx (or use a hosting service)

Summary:

We create an JavaScript object using JQuery and set up some parameters such as fade-in time and intervals between switching the images. The object will then find all items tagged as 'rotating-item' and loop through each image (according to our parameter set).

The JavaScript/JQuery Code

This should be all the code you will need for the moment; save this as 'slideshow.js' in a place your server can access. The code comments should be adequate, but just in case here are some notes:
  • The function $(window).load() means that the following JavaScript code will execute once the HTML/CSS page has finished loading the elements
  • In JQuery, $('..') is a query that searches the HTML/CSS DOM (Document Object Model) for elements that matches the query. So $('.rotating-item') searches the HTML document for any element that is of the class 'rotating-item;
/**
  * @author AlmightyOlive
  */
$(window).load(function() { //start after HTML, images have loaded
     var InfiniteRotator =
     {
         init: function()
         {
             //initial fade-in time (in milliseconds)
             var initialFadeIn = 1000;

             //interval between items (in milliseconds) 
             var itemInterval = 5000;

             //cross-fade time (in milliseconds)
              var fadeTime = 2500;
             //count number of items
             var numberOfItems = $('.rotating-item').length;

             //set current item
             var currentItem = 0;

             //show first item
             $('.rotating-item').eq(currentItem).fadeIn(initialFadeIn);

             //loop through the items
             var infiniteLoop = setInterval(function(){
                 $('.rotating-item').eq(currentItem).fadeOut(fadeTime);

                 if(currentItem == numberOfItems -1){
                     currentItem = 0;
                 }else{
                     currentItem++;
                 }

                 $('.rotating-item').eq(currentItem).fadeIn(initialFadeIn);
             }, itemInterval);
         }
     };
     InfiniteRotator.init();
});

The CSS

This code defines the look and feel of the elements. Take care when changing these defaults as doing so may result in the slideshow not being displayed at all. I suggest you copy the code as is (although change the width and height parameters to the size of your largest image), test it out and then make your changes. Also, make sure you keep the display: none; property of the rotating-item element!

#rotating-item-wrapper
{
 position: relative;
 width: 768px;
 height: 512px;
}

.rotating-item 
{
 display: none;
 position: absolute;
 top: 0px;
 left: 0px; 
}
 

The HTML

The final part of the code is the HTML structure. Make sure you include the JQuery API and your JavaScript code (insert the following line inside the ... element of your document)!

<script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js'></script>
<script type='text/javascript' src='./slideshow.js'></script>


Now you just place the following code wherever you want the slideshow to appear. Just to clarify; the wrapper element sets up the position and size of the frame that the images will be displayed in, so all the images MUST be placed within the wrapper if you want it displayed properly.

<div id="rotating-item-wrapper">
<img src"./img1.jpg" alt="" class="rotating-item" />
<img src"./img2.jpg" alt="" class="rotating-item" />
</div>


Hope you find this code useful. Enjoy!