Showing posts with label jQuery. Show all posts
Showing posts with label jQuery. Show all posts

Monday, December 23, 2013

Remove duplicates in an array in Javascript

If you follow this approach, you need to create another array and if you have performance limitations you need to consider that.

This algorithm will be o(n)complexity in which n is the length.

With jQuery:

 var newArray = []; 
 var array=["amir", "amir", "rahnama", 1, 1]; 
 var newArray = [];

 $.each(array, function(i, element) { 
   if ($.inArray(element, newArray) === -1) {
       newArray.push(region); 
   }
 });

 console.log(newArray); // ["amir", "rahnama", 1];

Vanila Javascript:

 var newArray = []; 
 var array=["amir", "amir", "rahnama", 1, 1]; 
 var newArray = [];

 array.forEach(function(i, element) { 
   if (newArray.indexOf(element) === -1) { 
      newArray.push(region); 
   }
 });
 console.log(newArray); // ["amir", "rahnama", 1];

Friday, November 1, 2013

Merge two object literals into one another in Javascript

I faced this issue a while back that I wanted to achieve something like
var a,b,c;
a = b + c;
for object literals in Javascript. Moreover to that, I wanted to have an option to extend (merge, add or whatever you might want to call it) in a loop, something like the following for the string type:
var result = "",
    j = 0,
    array = ["Amir", "Rahnama"];

    for (; j< array.length;j++) {
       result += array[j] + " ";

}

console.log(result); //Amir Rahnama
I first tried to write my own code and then suddenly found a better solution: jQuery's extend method. In short, jQuery's extend method extends N objects into a target object:

jQuery.extend( target [, object1 ] [, objectN ] )

The target is an object that will receive the new properties, Object1 is an object containing additional properties to merge in and finally, objectN is the additional objects containing properties to merge in. One way of using the function is like following:
var personObject = {person: {name: "Amir", familyName: "Rahnama"}};
var workObject = { work: {workplace: "Stockholm", companyName: "Gapminder"}};
var personWorkObject = {};
    
personWorkObject = $.extend(personObject,workObject);
You could also use the method to extend an object recursively, within a loop for example and that is why I highly recommend you to use this method. If you want to extend the objects recursively, make target the return value of the method, like the code below:
personWorkObject = $.extend(personWorkObject, personObject,workObject);

Monday, July 8, 2013

Load jQuery UI with requireJS

RequireJS is one popular script loading framework out on the web. At the same time, most of the web applications and websites are now using jQuery and there are quiet a lot of them that use jQuery UI as well. You may know that jQuery UI is dependent on jQuery, meaning that in order for jQuery UI to load correctly, jQuery should be loaded first.

In older version of RequireJS, it was a lot more harder (and ugglier you may say) to include jQuery UI since the jQuery UI library (unlike jQuery) is not following an  Asynchronous Module Definition  (AMD) style. Then you need to include AMD-enabled scripts which were built within communities and especially James Burke. However, in the last versions of RequireJS, a lot of features were added regarding this.

Remark: If you are not familiar with Asynchronous Module Definition (AMD) and interested to know more, read this article Why AMD?

So let's get on with it. I presume that you are following a folder structure like this:




Here is how you minimal index.html file should look like:


    sample_app
    




One of the scripts that handles a lot of key information is the one attributed with data-main (i.e. main which stands for main.js). In this script you can define your library paths and a tag called shim which handles dependencies and non-AMD module loading. After that there is the code on how application will continue its initialisation process. This looks something like:


require.config({
    paths: {
        "jQuery": "../libs/jQuery//jquery-1.9.1",
        "jQueryUI": "../libs/jQueryUI/jquery-ui-1.10.3.custom"
    },
    shim: {
        "jQueryUI": {
            export:"$" ,
            deps: ['jQuery']
        }
    }
});

require(["app"], function(App)
{
    App.initialize();
});

As you can see with the paths you are declaring a key-value pair of library conventions and paths and with shim, you are flagging the non-AMD modules which in this case is also dependes on jQuery. In the last step, add the following to your app.js file:

define(["jQuery", "jQueryUI", "guiFunctions"], function ()
{
   var initialize = function ()
   {
      //jQuery, jQuery UI are added here now ...
   };
  
   return {
      initialize : initialize
   };
});
And that is it!

Monday, July 1, 2013

How to migrate from live() method in jQuery 1.9?

As jQuery documentation says it here, the famous live() method has been completely removed in jQuery 1.9, so you have to migrate from it, anyhow.

It is actually quiet simple. The jQuery Library has introduced a method called on() which is even more complete in what live() method was doing. The following is its signature:

.on( events [, selector ] [, data ], handler(eventObject) )

where events is of type String  and it is one or more space-separated event types and optional namespaces, such as "click" or "change", selector is also of type String and it is the selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. Data can be of any type and it is passed to the handler in event.data when an event is triggered, and lastly, handler is of type Function (to execute when the event is triggered).

There exist a rough formula to change your methods from live() to use on(), instead. Have a look at my example:
// This is the old live() method
$("#element-id").live('change', function(){ 
  // Event handler code goes here ...
});

//This is its equivalent in jQuery 1.9
$(document).on('change', "#element-id", function(){
  // Event handler code goes here ...
});
Were you able to find the formula? It is quiet easy: Change the place of first argument of live method to the third one in on(). Add the root DOM element to the first parameter of on() method and keep the event type. That's it!

Tuesday, June 18, 2013

Load JSON Files Synchronously with jQuery

In jQuery, the getJSON operator can load any JSON file, however this operation is done asynchronously. Meaning that, in cases where you need to wait until your data file is loaded, using getJSON method is useless. Here is one way you can achieve your goal of loading JSON files synchronously:

function loadJsonFileSynch()
{
        $.ajax({
            url: 'path/to/json/file.json',
            async: false,
            dataType: 'json',
            success: function (response) {
                $.each(response, function(key, val) {
                    // Do processing here
                });
            }
        });
}

Saturday, January 26, 2013

Creating Dynamic Tables with jQuery

I have been doing some search on a decent tutorial on how you can create and modify dynamic tables with jQuery but I was not so lucky, and I thought about writing one, myself. Let's get to it, then! 

Example Scenario:

In this example, we would like to insert a passenger's name and gender inside a list. The list will be dynamically created, of course.

1. Create the table's empty layout:

While you do not have to create your table per se, but a table layout is needed. Take a look at one way you can do this:

Passengers' List
ID Name Gender Row Operation
Also we would need to enter the passenger's name and gender. We do so by declaring an input textbox and drop-down list. Note that a button is supposed to fire up the event to insert the values in the dynamic table:
Enter passenger's name: 
  Enter passenger's gender: 
  


  

2. Add rows to dynamic table:

First step is to handle the click function of the Add Passenger button.
$('#add-new-passenger').click(function(){
  var passGender = $('#new-passenger-gender').val();
  var passName = $('#new-passenger-name').val();

   counter++;
   var row = $('table.passenger-list').find('.passenger').clone();
   row.attr("class", "")
   row.find('.rowId').html(fcounter);
   row.find('.rowName').html(passName);
   row.find('.rowGender').html(passGender);
   row.find('.rowLink a.delete').html('Delete');
   $('table.passenger-list').find('tbody').append(row);
 });


The challenge here is that we used the clone() function of jQuery to copy the layout of the first row, then we used the find() function to retrieve a row and then set the html attribute of each row according to the dynamic table layout of ours. Then one can select the table and finally appended the row to the table.


3. Delete rows from dynamic table:

This part somehow needs the smallest peace of code and at the same time can be a little bit tricky for some guys. What I encourage people to avoid using the old depreciated live() function, and as jQuery recommended use on('click', '', ) instead:

$('table.passenger-list').on('click',  'a.delete', function() {
  $(this).parents("tr").remove();
 });

As you can see, after handling the click event of the link within delete class, we select the parent row and perform deletion.

Wednesday, January 16, 2013

Add rows to HTML table using jQuery





Add Title Here


 
First HeaderSecond Header
Add Row
Find it in JSFiddle: Add rows to HTML table using jQuery