Merge objects using $.extend() in jQuery

Have you ever come across a requirement in which you need merge many objects in one object? Okay let me clarify question in simpler words. Assume you have two objects as given below. object1 is defined as below,


var object1 = {
 red: 0,
 blue: { lightblue: 24, darkblue: 12 },
 black: 17
 };

And another object is object2.


var object2 = {
 white: 200,
 blue: {lightblue:40}
 };

Let us say you have to merge object2 in object1. Here merge means merging properties of object2 in object1. You can do this in jQuery using extend() function.


$.extend(object1, object2);
 console.log(object1);

 

Let us say you have to merge object2 in object1. Here merge means merging properties of object2 in object1. You can do this in jQuery using extend() function.

Now if you go ahead and view console you see following output. As you can see value for blue property in object1 has been changed with the value of object2’s blue property.

image

This is the way $.bind() merge two objects in jQuery. There could be another scenario in which you want to merge objects recursively. Recursively means property value which is unique in target object will persist. For recursive binding you need to set first parameter as True.

 $.extend(true,object1, object2);
 console.log(object1);

In output you can see that now blue property of object1 has darkblue and lightblue both. Value of darkblue has been modified with object2 property value.

image

You can merge more than two objects as below and always remember that $.bind returns target object as output,


var object1 = {
 red: 0,
 blue: { lightblue: 24, darkblue: 12 },
 black: 17
 };
 var object2 = {
 white: 200,
 blue: { lightblue: 40 }
 };

 
 var object3 =
 {
 yellow: 234
 };
 var targetresult = $.extend({}, object1, object2, object3);
 console.log(targetresult);

 

In this way you can merge objects in JavaScript using jQuery $.bind() function. I hope you find this post useful. Thanks for reading.

Two common tasks using jQuery

In this post we will take a look on how to perform two common tasks using jQuery . We will see how following tasks can be performed,

  1. Reading and setting text of label
  2. Reading value of selected item from drop down

Reading and setting text of label

Let us say you have label on HTML as following,


<label id="locationbox"> </label>

You can read value as following ,


var valueoflabel = $('#locationbox').text();

You can set text in label as following,


$('#locationbox').text("MyText");

Reading value of selected item from drop down

Let us say you have drop down as following on html,


<select id="typeofreport">
<option value="Rape">Rape</option>
<option value="EveTeasing">Eve Teasing</option>
<option value="Molestation">Molestation</option>
<option value="VerbalAbuse">Verbal Abuse</option>
<option value="Harassmentatwork">Harassment at work</option>

</select>

You can read text of selected value of drop down as following ,


var typeofincident = $("#typeofreport option:selected").text();

These are the two tasks I wanted to share with you. I hope you find this small blog post useful. Thanks for reading.

Learn jQuery Part4: Increasing and Decreasing font of paragraph text using jQuery

Part3: How to Filter in jQuery
Part 2: How to Select Elements or Nodes in jQuery
Part1: Introduction to jQuery


In this post we will learn applying CSS on HTML Elements using jQuery. On click of event of button we will increase or decrease FontSize of the text. See the below video for the expected output

You may come across scenario when you need to apply CSS styling on DOM element at the run time. For example on click event of button you may want to increase or decrease font size of the Paragraph Text. jQuery allows to apply or remove CSS on HTML elements.

image

Assume we have HTML as following. There are two buttons on the HTML, one to increase the font of the text in paragraph element and another to decrease the font size.

Code Listing 1


<body>
<h1>CSS styling using jQuery</h1>
<p id="infopara">
Cricket is a bat-and-ball game played between two teams of 11 players on a field,
at the centre of which is a rectangular 22-yard long pitch. One team bats,
trying to score as many runs as possible while the other team bowls and fields,
trying to dismiss the batsmen and thus limit the runs scored by the batting team.
A run is scored by the striking batsman hitting the ball with his bat,
running to the opposite end of the pitch and touching the crease there without being dismissed.
The teams switch between batting and fielding at the end of an innings.
</p>
<button id="btnincreasefont" type=button onclick="">Increase Font</button>
<button id="btndecreasefont" type=button onclick="">Decrease Font</button>
</body>

In browser you should get rendered HTML as following

image

Now on the click event of the buttons we want to increase and decrease the font size of the paragraph text. First attach a click event to the button. Click event can be bind to button as below,

image

After attaching click event to button we need to read current font size of the text. To read that value select HTML element <p> with id and apply css selector with fontSize attribute to read current font size applied. You can read current font size as given below

image

If you alert divcurrentfont , you will get font size as following

image

Now we need to convert current font size to an integer value and we can do that as following

image

If you alert divcurrentfontinnumber, you will get integer part of font size as following

image

Next we need to extract unit part of font. We can do that as following

image

On alert you will get unit as following

image

After this we need to modify font size value as per our requirement. In this case I am going to increase font size twice with each button click. We can multiply font size by 2 as following

image

Last but not least we need to set fontSize value. To do this select element with id and set fontSize argument in css function. We can set fontSize as following

image

On consolidating codes from above discussion we may have following jQuery code to increase font size of paragraph text on click event of button.

image

To decrease font size we need to follow same steps but rather than multiplying font size by 2, we will divide by 2.

image

Find full jQuery source code to increase and decrease the font size in CodeListing2. CodeListing1 is used as HTML for CodeListing2.

CodeListing2


<script type="text/javascript">
$(document).ready(function () {
$('#btnincreasefont').click(function () {
var divcurrnetfont = $('#infopara').css('fontSize');
var divcurrentfontinnumber = parseInt(divcurrnetfont, 10);
var unitusedinfont = divcurrnetfont.slice(-2);
divcurrentfontinnumber *= 2;
$('#infopara').css('fontSize', divcurrentfontinnumber + unitusedinfont);
});

$('#btndecreasefont').click(function () {
var divcurrnetfont = $('#infopara').css('fontSize');
var divcurrentfontinnumber = parseFloat(divcurrnetfont, 10);
var unitusedinfont = divcurrnetfont.slice(-2);
divcurrentfontinnumber /= 2;
$('#infopara').css('fontSize', divcurrentfontinnumber + unitusedinfont);
});
});
</script>

I hope you find this post useful. You may find previous posts of this series useful too.

 

Part3: How to Filter in jQuery
Part 2: How to Select Elements or Nodes in jQuery
Part1: Introduction to jQuery

 

Thanks for reading.

 

Learn jQuery Part3: How to Filter in jQuery

Filtering elements in jQuery is very vital. We may come across many requirements when we need to filter HTML Elements or jQuery object to a subset of element on different set of criteria. We may have to filter on basis of

  • Some selection criteria
  • On basis of HTML elements name
  • On basis of callback function

To ease our task jQuery provides sets of filtering functions. Some of the functions are as following,

image

Let us explore each function one by one.

.eq(index)

This returns list of elements matching the set criteria. We apply .eq on jQuery object. For example .eq can be applied on elements like <li>, <tr>, < div> etc. on basis of index it filters the jQuery object and returns set of matching elements as a new single jQuery object. To understand it better let us take an example. Assume we have following HTML

image

And we need to select Item5. We need to change background and color of this element. We can perform this in two steps.

Step1: Select <li> element and convert it to jQuery object

Step2: Apply filter to fetch required element and apply desired CSS

We can select Item5 either by class name or using tag name. In both case we will have to apply filter using .eq.

image

In above code both filters will be returning same element [5th element in< li>]. We are passing index as 4 when selecting element by tag. Since there are five <li> elements and index starts from 0, so we need to pass 4 as index in first case. However when we are selecting element as class name then we are passing index 2 since there are only 3 elements exist with same class name.

Complete example of above discussion is given below.

Example 1

<!DOCTYPE html>
<html>
<head>
<title>Test</title>
 <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js">
 </script>
</head>
<body>
 <p>This is Test page for Filter in jQuery</p>

<ul>
 <li class='toselect'>Item 1</li>
 <li>Item 2</li>
 <li class='toselect'>Item 3</li>
 <li>Item 4</li>
 <li class='toselect'>Item 5 will be selected</li>
 </ul>
</body>
<script type="text/javascript">

$('document').ready(function () {
 alert('hello');
 $('li').eq(4).css('color', 'red');
 $('.toselect').eq(2).css('background-color', 'blue');
 });
 </script>
</html>

&nbsp;

When we run above code, we should be getting output as following,

clip_image001

.first

We apply .first on jQuery object {essentially can be HTML elements} and it returns first matching element as jQuery object. Let us take the same example we took earlier for .eq. if we want color of first <li> element to be changed then we can change that as following,

image

.first also works in same way of .eq. We need to select element then convert that to jQuery object and finally apply .first to fetch first element as jQuery object.

Complete example of above discussion is as following,

Example 2


<!DOCTYPE html>
<html>
<head>
<title>Test</title>
 <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js">
 </script>
</head>
<body>
 <p>This is Test page for Filter in jQuery</p>

<ul>
 <li class='toselect'>Item 1</li>
 <li>Item 2</li>
 <li class='toselect'>Item 3</li>
 <li>Item 4</li>
 <li class='toselect'>Item 5 will be selected</li>
 </ul>
</body>
<script type="text/javascript">

$('document').ready(function () {
 $('li').first().css('color', 'red');
 });
 </script>
</html>

We will be getting expected output as following,

clip_image001[6]

.last

We apply .last on jQuery object {essentially can be HTML elements} and it returns last matching element as jQuery object. Let us take the same example we took earlier for .eq. if we want color of last <li> element to be changed then we can change that as following,

image

.last also works in same way of .eq. We need to select element then convert that to jQuery object and finally apply .last to fetch last element as jQuery object.

Complete example of above discussion is as following,

Example 3


<!DOCTYPE html>
<html>
<head>
<title>Test</title>
 <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js">
 </script>
</head>
<body>
 <p>This is Test page for Filter in jQuery</p>

 <ul>
 <li class='toselect'>Item 1</li>
 <li>Item 2</li>
 <li class='toselect'>Item 3</li>
 <li>Item 4</li>
 <li class='toselect'>Item 5 will be selected</li>
 </ul>
</body>
<script type="text/javascript">

 $('document').ready(function () {
 $('li').last().css('color', 'red');
 });
 </script>
</html>

We will be getting expected output as following,

clip_image001[8]

.has()

We apply .has on jQuery object {essentially can be HTML elements} and it returns jQuery object from set of matching elements.

.has can take two types of input parameter. It can take either selector as string or HTML DOM Element. Given element will be matched and jQuery object will be returned from matched subset DOM elements.

For example consider following HTML

image

If we want to change background of div contains <ul> then in this scenario we can use has. We will select <div> has <ul> as following,

image

Complete example of above discussion is as following,

Example 4


<!DOCTYPE html>
<html>
<head>
<title>Test</title>
 <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js">
 </script>
</head>
<body>
 <p>This is Test page for Filter in jQuery</p>

<ul>
 <li class='toselect'>Item 1</li>
 <li>Item 2</li>
 <li class='toselect'>
 Item 3
 <ul>
 <li>3.1</li>
 <li>3.2</li>
 </ul>
 </li>
 <li>Item 4</li>
 <li class='toselect'>Item 5 will be selected1</li>
 </ul>
 <div>
 <ul>
 <li>p1</li>
 <li>p2</li>
 </ul>
 </div>
 <div>
 <p>
 This DIV is just like that
 </p>
 </div>
</body>
<script type="text/javascript">

$('document').ready(function () {
 $('li').has('ul').css('color', 'red');
 $('div').has('ul').css('background-color', 'blue');
 });
 </script>
</html>

We will be getting expected output as following,

clip_image001[10]

.map

We use .map to iterate through a jQuery object and apply a function on each element. .map is useful when we want to get or set values on collection of elements. For example we want to fetch values of all the input elements. .map returns array as output.

Let us suppose we want to fetch value of all <li> as comma separated from following HTML

image

We will apply .map function to <li> to fetch all the value as array and then we will apply joins on array to make values as comma separated.

image

Complete example of above discussion is as following,

Example 5


<!DOCTYPE html>
<html>
<head>
<title>Test</title>
 <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js">
 </script>
</head>
<body>
 <p>This is Test page for Filter in jQuery</p>

<ul>
 <li class='toselect'>Item 1</li>
 <li>Item 2</li>
 <li class='toselect'>Item 3</li>
 <li>Item 4</li>
 <li class='toselect'>Item 5 will be selected</li>
 </ul>
</body>
<script type="text/javascript">

$('document').ready(function () {

var r = $('li').map(function () {
 return $(this).text();
 }).get().join(',');
 alert(r);

 });
 </script>
</html>

We will be getting expected output as following,

clip_image001[12]

.not

We apply .not on a jQuery object to fetch elements which does not match the selector. .not can take four different types of input

  • Selector
  • jQuery object
  • Elements
  • Function

As an output it returns jQuery object.

Let us consider following HTML and we want to change background color of all the odd <li> elements.

image

We can change that as following,

image

Complete example of above discussion is as following,

Example 6


<!DOCTYPE html>
<html>
<head>
<title>Test</title>
 <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js">
 </script>
</head>
<body>
 <p>This is Test page for Filter in jQuery</p>

<ul>
 <li class='toselect'>Item 1</li>
 <li>Item 2</li>
 <li class='toselect'>Item 3</li>
 <li>Item 4</li>
 <li class='toselect'>Item 5 will be selected</li>
 </ul>
</body>
<script type="text/javascript">

$('document').ready(function () {

$('li').not(':even').css('background-color', 'red');
 });
 </script>
</html>

We will be getting expected output as following,

clip_image001[14]

.slice

.slice can be applied on a jQuery object. It returns subset of elements as jQuery object on basis of specified criteria. We pass index of first element and last element of the returned subset. If index of last element is not specified then .slice will return all the elements from index of start element.

Consider following HTML and we want to change background color of all the <li> after second element

image

We can change background color using .slice as following,

image

Complete example of above discussion is as following,

Example 7


<!DOCTYPE html>
<html>
<head>
<title>Test</title>
 <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js">
 </script>
</head>
<body>
 <p>This is Test page for Filter in jQuery</p>

<ul>
 <li class='toselect'>Item 1</li>
 <li>Item 2</li>
 <li class='toselect'>Item 3</li>
 <li>Item 4</li>
 <li class='toselect'>Item 5 will be selected</li>
 </ul>
</body>
<script type="text/javascript">

$('document').ready(function () {

$('li').slice(2).css('background-color', 'red');
 });
 </script>
</html>

We will get expected output as following,

clip_image001[16]

Conclusion

These are the jQuery functions we may be using to filter. Sometime we may have to apply more than one function together to filter to a specific subset of elements. I hope this post is useful. Thanks for reading.

Learn jQuery Part 2: How to Select Elements or Nodes in jQuery

Learn jQuery Part1: Introduction to jQuery

Objective

In this part we will see different ways we can select element or node in jQuery. Before you start with this part, I strongly recommend you to read first part of this series.

In jQuery an element or node can be selected in many ways. An element can be selected

  • By ID
  • By Class name
  • By Attribute or value of an attribute
  • If we want to select all elements then that can be selected by using tag name.

Before we go ahead and understand many ways of selecting an element or node, let us first understand what is an Element? In below HTML all the div and P can be called as nodes or elements. Any HTML elements on the HTML page can be termed as node. A node is called as Child Node if it is inside some other node. For example in below HTML snippet P inside div with id hellodiv is child node of this particular div.

image

Let us use above HTML and we need to select all the div. Since we need to select all the div then we can select that using tag name. All the div can be selected as following. In alert we will be getting number of div is on page.

 image

In the same way if we want to select all the anchor tag <a>, all the page tag <p>, all the table tag <table> , we can do that as following

image

We can select more than one tag together by separating them with comma. Like following in one statement we can select all the p, table and a elements on the page.

image

If we want to select a specific element then we can select that using its class name or id. Let us say we have HTML as following

image

We want to select div with id is hellodiv. This can be selected as following

image 

We will be getting following output in alert box.

image

Essentially, an element can be selected with ID by using # symbol. If we want to select elements with class name we can do that with the use of period operator.

image

Now we need to select div using class name. Selecting with class name is exactly the same as selecting by id. However there is performance issue in selecting using class name. Since jQuery iterate through all the DOM objects in memory whereas in case of selecting using ID, jQuery directly fetch the DOM object from memory.

image

And you will be getting expected output in alert as following,

image

There is only difference of hash and period in selecting using id or class name.

image

There may be scenario when you want to select a specific type of tag on basis of class name. For example in below HTML all the elements having same class name ‘hellodiv’.

image

If we want to select element P with class hellodiv then we will be selecting as following,

image

Essentially we need to put class name with period after the tag name.

Now let us take some other selection examples. For example you from following HTML you want to select all the hidden div.

image

We can select all the hidden div as following,

image

If we want to check that whether a div is hidden or not, we can check that as following

image

There may be scenario when we need to select child elements. For example consider following HTML

image

Now if we want to print number of <li> elements. We can do that as following,

image

Let us say you want to print first and last <li> elements, we can do that as following,

image

If we want to get nth element in the list, we can do that as following,

image

If we want to select all the odd and even numbers we can do that as following,

clip_image001

In this way we can select Elements or Nodes in different ways.

Conclusion

In this part we focused on different ways of Element or Node selection in jQuery. I hope this post was useful. Thanks for reading.

 

Learn jQuery Part1: Introduction to jQuery

This is first part of Learn jQuery series. In this post we will see,

  • What is jQuery
  • How to start using jQuery
  • Understanding document.ready function

What is jQuery?

jQuery is a succinct and concise way to write JavaScript. It is a single JavaScript file and it is having cross browser support.

image

In simple terms we can say jQuery is simplified way of writing JavaScripts. It is a single file library with very smaller size. It helps in following

  • It eases the task of HTML elements traversing. Using jQuery elements can be traversed by tag name, id, and class name.
  • It simplifies the task of nested HTML elements traversing. With very readable syntax nested child elements can be traversed.
  • It helps in handling several events across browsers.
  • It provides many plugins for animations, sorting, searching etc.
  • It helps is making Service and Ajax call.
  • It adheres to CSS 3.0 and helps to applying them with minimal code on the HTML elements.

There are many other advantages are features are available in form of plugins. As a developer jQuery makes task of writing scripts and creating web based applications simpler and easier.

How to start using it?

To work with jQuery you need to download it and make a reference of the file on the HTML page. jQuery library can be downloaded From official site of jQuery. There are two versions of files to download there.

image

Production version is minified version and its size is 32 KB. Whereas Development version is uncompressed version and its size is 247KB. You need to be very careful while choosing the file because this file needs to be loaded at the client side. And larger file size may cause the performance loss.

Locally downloaded jQuery file saved in Scripts folder can be referred as below.

image

Other way of working with jQuery is refer the file from CDN of Microsoft or Google. In this case you do not need to download the file and add it locally. The other advantage of using file from CDN is, you will have always updated copy of the jQuery file. There is one disadvantage that your application will be dependent network always.

Link for Microsoft CDN is as below,

http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.5.1.js

Minified version is also hosted at Microsoft CDN .You can use jQuery file from CDN as below,

image

Essentially with reference of jQuery file hosted at Microsoft CDN, your will have structure of HTML file as following,


<html>
<head>
<title>Learning jQuery</title>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.5.1.js" > </script>

</head>
<body>
<h2>HTML Goes here</h2>
</body>
</html>

Understanding document.ready() function

Document.ready function is get executed when all the elements in DOM gets loaded. After all the DOM elements completes loading document.ready() function gets executed. Usually you call all the scripts from this function.

image

If you want to write some jQuery on click event of HTML element button then in that case, you may want to write code in some other function rather than ready function.

In above example we are calling an anonymous function in the ready function. In some cases you may want to call a named function. You can call a named function as following. However in the majority places you will find anonymous function being called in the document.ready

image

A complete example can be given as following;


<html>
<head>
<title>Learning jQuery</title>
<script type="text/javascript"
src="/scripts/jquery-1.4.1.js"> </script>
<script type="text/javascript">
$(document).ready(function () {
alert('Other scripts goes here');
alert('Hello jQuery');
});
</script>
</head>
<body>
<h2>HTML Goes here</h2>
</body>
</html>

$(document).ready() is one of the most important function and denotes all the HTML elements in DOM has been loaded.

Conclusion

In this post we got an introduction of jQuery. We also looked into usage and importance of ready function. I hope first post of the series was useful to you. Thanks for reading.