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

Wednesday, November 21, 2012

Auto increase content on scrolling

Hi,

I recently got script request for developing something which has become very common in most websites. Mostly seen in sites like Facebook. For any given container in a web page, which has a scroll bar, when the user reaches the end of the scroll height, the content of that container auto populates itself. This article covers this functionality.

Lets see few screen shots to better understand the concept:


1. Normal div with sample content and a scroll bar

2. User reaches the end of scroll

3. Immediately the content of the div increases


Download: autoScrollContent.zip

Explanation:

Tuesday, June 7, 2011

Simple javascript tooltip or help text


Hi,

In this post I will discuss of a custom made tooltip which you can implement in your HTML, without breaking a sweat. As usual, in this also, I am using jQuery as my Javascript framework. I have used the basic concept of generating lightbox to generate the tooltips. So lets see how it looks in the front end:

Before we go into the explanation you can download the source code from here.

Code and Explanation:

First let us see the basic HTML structure as:

<div style="float:left;margin-right:5px">This is text 1 </div><div class="tooltip">This is tooltip 1...</div><br/>
<div style="float:left;margin-right:5px">This is text 2 </div><div class="tooltip">This is tooltip 2...</div><br/>
<div style="float:left;margin-right:5px">This is text 3 </div><div class="tooltip">This is tooltip 3...</div><br/>
<div style="float:left;margin-right:5px">This is text 4 </div><div class="tooltip">This is tooltip 4...</div><br/>

Thursday, May 5, 2011

Facebook style quick friend search and select


Hi,

In this post, I will discuss how to create a friend selection widget as in Facebook. When ever you are inviting your friends, or sending some application request to your friend in Facebook, you might get a friend selection widget as below:


In this I have made a similar functionality using jQuery. Here is what my screen looks like:


In the above, as you start typing the name of your friend, the list below gets filtered quickly accordingly. This is not refreshing the page nor is calling any AJAX. The whole thing is in realtime. Also you can select/unselect 1 or more friend by clicking them. And finally when you click the "Send Request" button the form gets submitted with selected friends user id. This is how I have achieved this.

Code and Explanation:

First you need to download the entire source code from here. Now here is the basic HTML:

Wednesday, April 13, 2011

Javascript accordion (collapsible menu)


Hi,

In this post, I have created a custom accordion in simple javascript, with a little help from jQuery. But this is not a plugin, so it wont take up too much time to load in the browser. You can download the full source code here. Before going to the explanation, lets first see how it looks like:



The HTML structure that is there, I have done it completely using <ul> and <li>, this would make it easier to customize. Here is a sample HTML of the above:

<ul class="acc_options_ul">
<li class="acc_options"><h1 class="acc_options_title">Option 1</h1>  
<ul class="acc_op_content_ul">  
<li class="acc_op_content">  
content of the section.....  
</li>  
</ul>  
</li>
</ul>

The convention that needs to be followed is, the title of the each section of the accordion must be kept inside an <h1> inside the  <li class="acc_options"> tags. Each <li class="acc_options"> represents each section. You just need to include the style.css and accordion.js in your page and let the JS take care of the rest.

Explanation:


The functionality of the JS file is very simple. First when the page loads I am opening the first section of the accordion by default by the following:

Monday, April 4, 2011

Creating widget with Javascript and PHP

Hi,

For those who do not know, a widget can be considered as a small section in your web page, whose content is being rendered from a different website. To understand this, google adsense is a very good example of a widget. In Adsense, you are provided with a javascript. All you need to do is to copy and paste the code in any part of your website to generate the advertisement. Now how the advertisement is getting generated, is not your concern.

But you need to configure the google adsense according to your need, e.g. the dimension of the adsense. After you are done with configuring it you are given a javascript code, as I mentioned above. Which you just need to copy and paste in your website or blog.

Click here to download the entire source code of the example given below, with full database.

So the basic things that we need to program for creating a widget is as:
1. A configuration section where the user will configure the widget, which may include color, title etc. as per your needs
2. Most importantly the embeddable code, which the end user will copy and paste after their configuration is done.

How ever there is one more thing needed from a programmers perspective, that is the content of the widget. The content of the widget is completely dependent on your business logic and the configuration data that the end users have set.

Example:

Monday, March 28, 2011

Rounded corners without CSS 3 - All browser compatible

Hi,

CSS 3 provides a wide range of design tweaks which change the entire attitude of the website. Most commonly used functionality is rounded corners to any element. In CSS 3 you can create rounded corners to any element. Apart from DIV's if you want to show some images with rounded corners or button, input boxes etc then also this javascript approach can be helpful, depending on your needs. The conventional CSS 3 approach is as follows:

-moz-border-radius:  5px;
-webkit-border-radius: 5px;
-khtml-border-radius: 5px;

But the problem is, few browser does not support it. So one way to achieve this is by using a jQuery plugin. For this you need jquery.corner.js and jquert.min.js. Click here to download the entire source code along with the required JS files.

This is the output you will get:


Explanation:

Monday, March 21, 2011

Proportionate Text Zoomer - Javascript

Hi,

In this I have made a custom script which can be used in any website to increase or decrease the text size of the entire page. You can find the entire source code at the end of this post. The zoom in and zoom out functionality is performed irrespective of their current font size. e.g. if a span has font size 10 and h1 as 14, then this will make span to 11 and h1 to 15, based on a certain percentage.

This is what the sample page looks like:

In this script you can choose tags whose text needs to be increased/decreased. This is what you have to do in script.js to add a new tag to have the functionality:


  $(".increaseFont").click(function(){  // for increasing font

$('a').each(function(idx, item) {    //adding the funtionality to anchor tag
       size=parseInt(jQuery(this).css("font-size"));
  size++;
  jQuery(this).css("font-size",size + "px")
    });
})

Sunday, March 20, 2011

AJAX + JSON

Hi,

JSON is a very lightweight script which is used to store data. It is useful because of its speed. Calling and working with JSON is much faster as compared to XML. This post deals with calling a JSON file via AJAX and parsing it accordingly.

To begin with we have the following json file, student.json with the following content:


{"students": [
        {"Name": "John Smith", "Age": "18", "Gender": "male"},
        {"Name": "Maratha", "Age": "19", "Gender": "female"},
        {"Name": "Rose", "Age": "17", "Gender": "female"},
    ]}

This of course is a sample data which I created manually. Now to call this file via ajax I will be using jQuery. Now I create a new file example.php and make a ajax call to the above "student.json" as follows:


jQuery(document).ready(function(){
jQuery.ajax({
type:"GET",
url: "student.json",
success: function(content){
.............
}
})
})

In the above example I am calling the json file after the entire page has been loaded in the browser. After the ajax call successfully executes, this is what I am doing:


success: function(content){
var students_json=eval("("+content+")");
total_students=students_json.students.length;
for(i=0;i<total_students;i++){
jQuery("body").append("Name: " + students_json.students[i].Name+ "  Age: "+students_json.students[i].Age+"  Gender: "+students_json.students[i].Gender+"<br>");
}
}

"eval()" function is used to convert a string into a JSON script. Next "students" is the name of the main root element. I am first finding the content length of "student", later I am executing a loop and extracting 1 field at a time and displaying the values in the web page. This is the output I get:

Friday, March 18, 2011

Website Security - How storing important information in cookie can be easily hacked

Hi,

This again adds to one of the security measures. Assuming you are storing some very vital information in your websites cookies e.g. transaction id in an e-commerce website.

It will take less than 10 seconds for any hacker to track down your cookies. All he has to do is to copy a code similar to this one:


javascript:alert(document.cookie.split(';').join('\n'))


go to your e-commerce website and paste it in the address bar and hit enter. As soon as he hits the enter button, immediately an alert box shows up listing all the cookies and PHP session id.


I created a simple example.php file with the following:



<?php
session_start();
setcookie("MY_COOKIE","this is the value of the cookie variable");
?>


then I executed example.php. The I copied and pasted "javascript:alert(document.cookie.split(';').join('\n'))" in the address bar and hit enter. This is what I got:



Apart from the above, every browser provides some way or the other to view the cookies and its values of a particular website. This is the fastest way to find out. This is useful for QA guys, while analyzing website.

Hope this helps.


Thursday, March 17, 2011

Object Oriented Javascript

Hi,

OOP is not just limited to PHP, you can implement its concepts to some extent in javascript as well. But before I move on with it in details, the most important thing you need to understand about OOP as fas as Javascript is concerned is the fact, that there are no classes as such, as we have conventionally known. Here the functions are treated as class, which may contain member functions and data members.

Here is the javascript

<script type="text/javascript">
function Person(name)
{
  this.name = name;
  this.getName = getName;
  this.setName = setName;
}
function getName()
{
  return this.name;
}  
function setName(name)
{
  this.name = name;
}
var personObj = new Person('Bob');

Facebook style hyperlinking - with/without javascript

Hi,

If you have seen facebooks hyperlinks, you will notice that most of the hyperlinks work using ajax calls. But what hackers love to do is to switch of javascript from the browser and try things. In case of facebook if javascript is enabled in the browser the page is called via ajax, but if javascript is disabled then also the hyperlinks do not stop working. What they do is instead of the ajax call, the page loads the conventional way i.e. simple href.

I have made a sample code for that, this is how it works. Its independent whether javascript is enabled or not. It works accordingly. Assuming javascript is enabled. The hyperlinks are as follows:


<a href="index.php?p=home.php">Home</a><br/>
<a href="index.php?p=page1.php">Page 1</a><br/>
<a href="index.php?p=page2.php">Page 2</a><br/>
<a href="index.php?p=page3.php">Page 3</a><br/>

Now I am loading a javascript which extracts the "href" parameter of all hyperlinks and stop the anchor tab to refresh the page by adding "return false" in the "onclick" event of the hyperlink as follows:


jQuery('a').click(function(){
link=jQuery(this).attr('href'); // extracts the value of the href attribute
.......
        .......
   return false;   // stops the page from refreshing on clicking the hyperlink
});



Now we parse the format of the 'link' variable and make a ajax call to load the destination page as:

Monday, March 14, 2011

Drag and drop shopping cart

Hi,

I am compiled this script where the users can simply drag and drop products to shopping cart. For this jQuery has been used. The important thing to keep in mind are the syntax which makes an item draggable and an item droppable. You will find the entire source code at the end of this post, featuring the shopping cart functionality. So the things to keep in mind are:


$( ".draggable" ).draggable({ opacity: 0.7, helper: "clone",
start: function(){
...................
        .....................
       },
});


The above draggable function makes the element whose class name is "draggable", a draggable element. Same goes for the element where I am dropping:


$( ".drop_zone" ).droppable({
drop: function( event, ui ) {
.....................
}
})

Apart from this everything else is just basic PHP concepts of shopping cart. Here is what happens:


When the products are dragged and dropped in the shopping cart box it gets added in the cart as:

The vital part in this is the drag and drop. Whenever an item is dropped in the shopping cart a function is called where I have put the ajax call. The event to call the function is as follows:

Wednesday, March 9, 2011

Performance Optimization - Part 2

Hi,

In my pervious post I had explained few reasons of slow server response time along with its solution. In this I will discuss how even after the response is received from the server, the page tend to load in the browser slowly. Following can be the reasons for that:


1. Heavy CSS and Javascript files
2. Too many images
3. Extensive DHTML processing loops


1. Heavy CSS and Javascript files
Sometimes using too many javascript libraries increases the size of Javascripts resulting in slow page. The best solution for this is choosing the Javascript framework smartly. If you are using common layout for multiple pages, then put only those JS files in the layout which will be common to all pages e.g. jquery.js. If you are using a package which is used only in few pages and not all, then do not put those in the layout, instead put them indivisually in each page e.g. the google map js.

Second and probably the best way to optimize JS and CSS usage is by JS/CSS compression. If you use gzip compression for CSS and Javascript, on an average it reduces the size by 80%, which really boosts up the speed. Click here to view my article on JS/CSS compression. It is really easy and extremely effective.

Install firebug in your Mozilla browser to analyze the above.

2. Too many images


Sunday, March 6, 2011

Trigger javascript events manually

Hi,

This is a very interesting code segment I got from one of my friends. In this you can actually trigger any event manually. This gets very useful in daily programming, when you want to perform same set of task/s with multiple events. I am not referring to creating a common function, but creating a single function or set of functions and the event which is calling the function, you can actually cause the event to occur via code.

First of all you need to download a stable version of jquery.js and use it in your following code:


<html>
<head>
<title> execute button click event automatically using jQuery trigger() method</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {          
$('#btn1').bind('click', function() {
alert('You selected the First Button');
});
$('#btn2').bind('click', function() {
alert('You selected the Second Button');
});