Showing posts with label JavaScript. Show all posts
Showing posts with label JavaScript. Show all posts

Thursday, June 10, 2010

A simple slideshow using mouse wheel

A JavaScript event for developers to take advantage of that- the "onmousewheel" event. As its name suggests, this event fires whenever the user rotate the mouse wheel either upwards or downwards, most commonly to scroll a webpage, "onmousewheel" is supported in IE6, Opera9+, Safari2+, and Firefox1+, though in FF (as of FF3.x), the equivalent "DOMMouseScroll" should be used, as "onmousewheel" as an event name isn't yet recognized.
Lets start a tour with onmusewheel event:

<img id="slideshow" src="1.jpg" />

<script type="text/javascript">
    var myimages=["1.jpg","2.jpg", "3.jpg"];
    var slideshow=document.getElementById("slideshow");
    var nextslideindex=0;

    function rotateimage(e)
   {
        //equalize event object
        var evt=window.event || e;
     
       //delta returns +120 when wheel is scrolled up, -120 when scrolled down
        var delta=evt.detail? evt.detail*(-120) : evt.wheelDelta;
       
       //move image index forward or back, depending on whether wheel is scrolled down or up
        nextslideindex = (delta<=-120)? nextslideindex+1 : nextslideindex-1;
       
       //wrap image index around when it goes beyond lower and upper boundaries
        nextslideindex = (nextslideindex<0)? myimages.length-1 : (nextslideindex>myimages.length-1)? 0 : nextslideindex;

        slideshow.src=myimages[nextslideindex];
        if (evt.preventDefault)
        {//disable default wheel action of scrolling page
            evt.preventDefault();
        }
       else
      {
         return false;
       }

   }

//FF doesn't recognize mousewheel as of FF3.x
var mousewheelevt=(/Firefox/i.test(navigator.userAgent))? "DOMMouseScroll" : "mousewheel";

if (slideshow.attachEvent) //if IE (and Opera depending on user setting)
    slideshow.attachEvent("on"+mousewheelevt, rotateimage)
else if (slideshow.addEventListener) //WC3 browsers
    slideshow.addEventListener(mousewheelevt, rotateimage, false)
</script>

Note the use of preventDefault() and return false to disable the default mouse wheel action when the cursor is over the image, which is to scroll the page.

Thursday, May 13, 2010

Checking valid URL using javascript Regular Expressions

Using this function you can check is given URL valid or not. If url is valid this function will return true otherwise false


function validateUrl(url)
{
var regexp = /^(([\w]+:)?\/\/)?(([\d\w]|%[a-fA-f\d]{2,2})+(:([\d\w]|%[a-fA-f\d]{2,2})+)?@)?([\d\w][-\d\w]{0,253}[\d\w]\.)+[\w]{2,4}(:[\d]+)?(\/([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)*(\?(&?([-+_~.\d\w]|%[a-fA-f\d]{2,2})=?)*)?(#([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)?$/
return regexp.test(url);
}

//Usage
var is_valid = validateUrl('http://google.com');

In this case "is_valid" is true

Monday, February 22, 2010

Image preloading techniques deeply

For better display and visitor interaction, image preloading must be implemented in some cases. We can preload image following two techniques:

1.Using JavaScript
2.Using CSS

Using JavaScript :

The simplest way to preload an image is to instantiate a new Image() object in JavaScript and pass the URL of the image you want to preload.

For example, if you want to preload an image, simply create a new JavaScript Image() object and place the script in the head section of the page to ensure it runs as soon as the page loads.

<script type="text/javascript">
Image= new Image();
Image.src = "pic1.jpg";
</script>

Preloading Image with JavaScript array

In practice, you will need to preload more than just one image to smooth effect on image rollovers. A JavaScript array of images can be preloaded as:
<script type="text/javascript">
     images = new Array();
     images[0]="pic1.jpg";
     images[1]="pic2.jpg";
     images[2]="pic3.jpg";
    imageObj = new Image();
     // start preloading
     for(i=0; i<images.length; i++)
     {
          imageObj.src=images[i];
     }
</script>

Preloading Image with jQuery

Image preloading which is pretty simple with jQuery is the solution. The code snippet that is around the Internet for some time provides image preloading:

jQuery.preloadImages = function() {  
     for(var i = 0; i<arguments.length; i++)  
    {
          jQuery("<img>").attr("src", arguments[i]);  
    }
}
In order to use the above function, an array of image urls should be provided:
$.preloadImages("image.gif", "/themes/images/BD/image2.png", "/themes/images/BD/flicker.jpg");

Using CSS :

Image preloading with CSS can be achieved by a simple <div> with style "display:none;" containing all <img> tags of images to be preloaded.

<div style="display:none;">
  <img src="/images/imageA.jpg" >
  <img src="/images/imageB.jpg" >
</div>

The CSS preloading code must be in the BODY area of the HTML code. It will not work in the HEAD section. The optimum position depends on how the preloaded images will be used. If the images will be used sometime after the web page has finished loading, the preload <div> can be placed below the page content. If the images will be used immediately, such as automatic background image change, the preload <div> should be placed on the top section of the BODY area.

Now compare these two methods to understand the safest and easiest method for preloading images:

Preloading with JavaScript

In order to preload images with JavaScript, browsers should support JavaScript and it should be turned on. Without JavaScript, the preloading will not happen and each time the image is needed, it will be fetched. If the preloaded images will be used on image effects such as rollovers or other effects that require JavaScript, preloading with JavaScript is the best choice. That way, for browsers that are not supporting JavaScript, the images will not be preloaded. 

The JavaScript preloading code can be placed anywhere in the page including the HEAD area of the page. If all preloading is done with JS, most of the search engine spiders won’t index the images.

Preloading with CSS

Preloading with CSS will work even if the browser’s JavaScript is turned off. The CSS preloading section should be placed in the BODY of the HTML. 

Search engine spiders index the images when they are preloaded with CSS.

Notes on Image Preloading:

Users with slow Internet connection speeds will navigate away if you preload too many or too large images before page content is displayed. 

The JavaScript and the CSS/HTML image preloading code can be used on the same web page at the same time.

Both techniques can be used more than once on the same web page to preload additional images at different points.

Tuesday, February 16, 2010

Get query string using javascript

The following javascript code snippet facilitates Javascript's built in regular expressions to retrieve value of the key. Optionally, you can specify a default value to return when key does not exist.

function getQuerystring(key, default_)
{
  if (default_==null) default_=""; 
  key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
  var qs = regex.exec(window.location.href);
  if(qs == null)
    return default_;
  else
    return qs[1];
}

The getQuerystring function is simple to use. Let's say you have the following URL:

http://www.youtube.com/watch?v=Ywyw2YeOOPk&feature=featured

and you want to get the "v" querystring's value:

var id = getQuerystring('v');

The output of id will be Ywyw2YeOOPk

Sunday, January 17, 2010

JavaScript: The difference between null and undefined

JavaScript is different from other programming languages by containin both undefined and null values, which may cause confusion.

null is a special value meaning "no value". null is a special object because typeof null returns 'object'.

On the other hand, undefined means that the variable has not been declared, or has not been given a value.

Following snippets display 'undefined':

// x is not declared anywhere in code
alert(typeof x);


var x;
alert(typeof x);

Although null and undefined are slightly different, the == (equality) operator considers them equal, but the === (identity) operator doesn't.