Scrolling to different areas on same page

In-page links or # links are useful but not too appealing visually. You can scroll to different parts of the page smoothly, scroll to different div on click of a #link, using javascript. Or make a handy go to top link.

Check a demo on this page >> scrolling to div on same page

In-page links are useful when you have a long page with lots of content on it. User has to scroll up and down to read the content, so you provide a #link which takes user to different part on the same page. But the transition is spontaneous and not visually appealing. So you can make use of this little javascript which automatically adds smooth scrolling for all your in-page links or #links.

Here’s the javascript:

$(function(){
	$("a.js_onPageLink").bind("click", function (event) {
		event.preventDefault ? event.preventDefault() : event.returnValue = false;
		var target = $(this).attr("href");
		$("html, body").stop().animate({
				scrollLeft: $(target).offset().left,
				scrollTop: $(target).offset().top
			}, 1200);
	});
});

You can see that it simply binds an event to all links on your page which have a css class of ‘js_onPageLink’. So just throw in the above script in your page, if you are making a one-page website, you want a go-to-top link in your footer or you have any other #links on your page, you just assign them an additional css class of ‘js_onPageLink’ and rest all is taken care of. You get a smooth scrolling to the target of the link.

You can change the speed by changing the value ‘1200’ in the script.

Hope it helps


using google graphs on your website

Use googles graph api to draw graph on your website. Google provides an extensible javascript api using which you can draw beautiful graphs on your website. All the processing is done through javascript and therefore you can use it to draw graphs/charts in an asp.net website or a php webiste or just simple plain static html. Check a simple demo here.

There are many charting/graph libraries out there. And some are really cool. You have inbuilt charting libraries for .net, open source libraries for php. So why another one? Well coz its google!! that alone should suffice as to why you should use it over other libraries. Its extensible, intuitive, responsive and lightening fast – doesn’t add overheads in your page load time.

For a list of options available check this page.

OK, i liked it. now how do i add google javascript graph into my website ?

Its fairly simple.
1) You add the necessary javascript files to your page.

<script type="text/javascript" src="https://www.google.com/jsapi"></script><script type="text/javascript">// <![CDATA[
         google.load('visualization', '1', { packages: ['corechart', 'imagelinechart'] });
// ]]></script>

the first line loads the core js api. Second script loads only the required script, eg: corechat, imagelineChart.

2) Create a 2 dimensional array in javascript from your data. The api always takes the data in the form of a 2 dimensional array. For example:

var data = google.visualization.arrayToDataTable([
		['Brand', 'Asia', 'Europe', 'America', 'Australia'],
		  ['BMW', 100, 200, 300, 45],
		  ['Mercedes', 110, 210, 180, 55],
		  ['Audi', 75, 654, 24, 10],
		  ['Ford', 100, 400, 316, 111]
	]);

3) Call appropriate method to draw the type of graph you need passing optional arguments if any.
For example if you want to draw a bar graph from the above data you’d do something like:

var options = {
	title: 'Car Brands across continents',
	vAxis: { title: "Customers (*10000)" },
	hAxis: { title: "Car Brands" },
	seriesType: "bars",
	series: { 5: { type: "line"} }
};

var chart = new google.visualization.ComboChart(document.getElementById('holder'));
chart.draw(data, options);

Integrating google graphs with ASP.NET or php

Ok so that was all javascript. How to use it with some actual data coming from database through my server side code? Well, we’ll still use javascript, to perform the actual drawing of the graph. But we will generate the data passed to it (the 2 dimensional javascript array mentioned before) on server side. Perform some database operation and your business logic over it to generate the string corresponding to the aforementioned data array and then you can pass the string to javascript. Now this passing of values between your sever code to the javascript on client end can be done in many ways. In php you can simply ‘echo’ the value inside the javascript (if the javascript is on the page itself). In .net, well one of the ways could be storing the value in some hidden field and then readin it through your javascript.
I encountered one strange thing though. I was doing inline scripts to put the values, something like:

var data = google.visualization.arrayToDataTable([
<%= hdn_GraphData.Value.ToString();%>
]);

But it was causing single quotes ” ‘ ” to get replaced by its html character code ” &#39; “. So i had to do a workaround and i did this

<% string str =hdn_GraphData.Value.ToString().Replace("&#39;","'"); Response.Write(str);%>

🙂 (i know, that’s a dirty way of doing it but it was quick, so…)

Hope you find it useful.


textbox watermark text effect

What is it

click on the textboxes below:



Add watermark text effect to your textbox and textarea controls. Texboxes will show default text to begin with. When the textbox gains focus, the default text goes off, user types in his own text and that persists. If user doesn’t type in anything and moves on to other parts of your web page, your textbox again show the default text.

How to achieve that

I’ve written this small javascript which renders the said effect to textboxes and textareas. To set things up all you need to do is:

  1. give the textboxes/textareas an additional class of ‘js_watermark’. eg:
  2. Add the following javascript somewhere
    $(document).ready(function(){
    /*---watermark functions ------------*/
    		$(".js_watermark").each(function(){
    			$(this).after("");
    		});
    		$(".js_watermark").focus(function(){
    			var wm_text = $(this).next('.js_watermar_text').html();
    
    			if($(this).val()==wm_text){$(this).val('');}
    		});
    		$(".js_watermark").blur(function(){
    			var wm_text = $(this).next('.js_watermar_text').html();
    			if($.trim($(this).val())==""){$(this).val(wm_text);}
    		});
    		/*--------------------------------------*/
    });

The approach is simple:
once the html is loaded the javscript adds a hidden <span> tag next to each textboxes/textareas which have the class js_watermark and ‘stores’ the default values of textboxes in those spans. When you click on any textbox (gain focus event) its text is deleted. When textbox loses focus the script check if its text is blank (after trimming blank spaces), if yes it fetches the default value from the hidden span next to the textbox and sets the textboxes value with the default value again.

Hope you find it useful.

text effects – giving random size and color

link for the demo is available at the end of the artile

Text effects – random size and color

What is it

This little demo show how to give random size and colors to the words . Lets say i have a <div> or <p> tag and i want all the words inside it to acquire random size and color. At the same time i also want a choice among those colors so that it suits my websites background and all. Check the demo page (link provided at the end of the article)

The setup

Give any <div> or <p> tag a class of js_typografy

<p class='js_typografy'>

Next Add the following javascript to your page

function typografy() {
            var minSize = 15;
            var maxSize = 80;
            var colorise = true;
            var colorArray = ['#369', '#000', '#aaa'];
            $(".js_typografy").each(function () {
                var retHTML = "";
                //get the text
                var allText = $(this).text().trim().split(' ');

                //now add each word one by one
                for (i = 0; i < allText.length - 1; i++) {
                    var size = getRandomInt(minSize, maxSize);
                    size = Math.ceil(size / 10) * 10;
                    if (colorise == true) {
                        var j = getRandomInt(0, colorArray.length - 1);
                        if (j < 0) { j = 0; }
                        retHTML += " " + allText[i] + "";
                    }
                    else
                    { retHTML += " " + allText[i] + ""; }
                }
                $(this).text('');
                $(this).html(retHTML);
                
            });
        }
        function getRandomInt(min, max) {
            return Math.floor(Math.random() * (max - min + 1)) + min;
        }
        $(document).ready(function () {
            typografy();
        });

you need to change the following according to your needs

var minSize = 15;//the minimum size of font - in pixels
var maxSize = 80;//the maximum size of font - in pixels
var colorise = true;//whether you want to give random colors or not
var colorArray = ['#369', '#000', '#aaa'];//the set of colors to choose from

What it does

Basically it finds all the elements with the class ‘js_typografy’, captures there text, wraps around each word in a span tag with style attribute having randomly generated size and color.

check the demo and refresh the demo page to see the random behaviour…


text with moving background

link for the demo is available at the end of the artile

Transparent text with moving image in background

First things first.. no fooling around, the text is not transparent, we are rather achieving that effect through an image.

The purpose

check the demo page (link provided at the end of the article) . What i want is to have my text on the html page and there should be some background image added behind the text in such a way that my text appears transparent and background image is visible. Furthermore i want to animate that background image.

The setup

I created a transparent image wherein all other parts of the image are opaque except the part where I’ve written my text (‘Logo’) so that my text part of the image is transparent.
Then i put that image on my html page inside a div. I set the div’s background with the background image of my choice. so now the background is visible through the transparent text part of my image.

The movement

Now jquery comes into play and animates the static background image. Basically a random number between 1 to 4 is genrated to decide the direction of movement of background image. and then background images position is set accordingly making the background image look like its moving. This happens in a loop resulting in a continuous movement of the background image in all different directions randomly.