hello, my name is Aamir Afridi ...

a front-end developer at bynd.com, London. I write about JS, jQuery and stuff...

12

jQuery Marquee Plugin

22 Feb 2013 – pauseOnHover option added. Also events added to pause or resume the animations. Check on github

20 Feb 2013 – New version of plugin is released Check on github

Recently I been working on a project where a static text message needs to be animated similar to non-standard HTML marquee tag.

Googling gives me quite few jQuery plugins but they got so many options and complex html layout/structure was needed for the plugin to work. I decided to make a simple jQuery plugin which can scroll the text either left or right.

Get the plugin:

Plugin options:

  • speed: Speed in milliseconds of the marquee. Please make note that same speed value will react differently for text with different lengths. Default is 10000.
  • gap: Gap in pixels between the tickers. Default is 20
  • delayBeforeStart: Time in milliseconds before the marquee starts animating. Default is 1000
  • direction: Direction towards which the marquee will animate ‘left’ or ‘right’. Default is ‘left’

Demo:

Continue Reading →

6

JS/jQuery Code Snippets

Some common Javascript snippets I use in my projects. If you got something useful, please share in comments section.

Somebody has translated this article in Chinese language :P

  1. Check if element has scrollbar

    I was working on a project where I need to add jQuery UI resizable to a list but I have to check if it has a scrollbar. I endup with a tiny jQuery plugin

    (function($) {
        $.fn.hasScrollBar = function() {
            return this.get(0).scrollHeight > this.height();
        }
    })(jQuery);
    
    Usage
    Some long text...

  2. setInterval and setTimeout

    Whenever you use setInterval make sure you clear it just incase if it never gets cleared.

    var timer = setInterval(function(){
        if(someConditionIsTrue){
            clearTimeout(timer);
        }
    },100);
    /*But if, due to some reasons, the 'someCondition' never gets true than you need to
    clear the timer otherwise it might turn into an infinite loop*/
    setTimeout("clearTimeout(timer)",10000) //10 seconds or more
    

  3. Strip out duplicate items in an Array

    //Pure javascript
    Array.prototype.copyUnique = function removeDuplicateElement() {
    	var newArray=new Array(),
    	    arrayName=this;
    	label : for(var i=0; i < arrayName.length; i++ ) {  
    		    for(var j=0; j < newArray.length;j++ ) {
    			if(newArray[j]==arrayName[i]) continue label;
    		    }
    		newArray[newArray.length] = arrayName[i];
    	}
    	return newArray;
    }
    
    //Based on jQuery
    Array.prototype.copyUnique = function(original) {
    	var a = jQuery(original);
    	return jQuery.makeArray(a.filter(function(i, item) {
    		return i === jQuery.inArray(item, a);
    	}));
    }
    
    Usage
    [1,2,3,3,4,3,4,5].copyUnique(); // return [1, 2, 3, 4, 5]
    

  4. Check if a value is in an Array

    //jQuery version
    jQuery.inArray("value", arr); // Usage: if( jQuery.inArray("value", arr) != -1 ) { true };
    
    //Javascript version
    Array.prototype.inArray = function (value) {
    	var i;
    	for (i=0; i < this.length; i++) {
    		if (this[i] === value) {
    			return true;
    		}
    	}
    	return false;
    };
    
    //[1,2,3].inArray(2) > true
    //[1,2,3].inArray(22) > false
    

    Continue Reading →

4

Simple javascript files loader for embeddable javascript application

Problem:

To develop a large scale javascript application, embeddable to pages, the first problem I faced was including large number of javascript files in the page. So like google or yahoo applications you simply include one javascript file and after few lines of javascript to start the application, otherwise you will end up with something like this:

<script type='text/javascript' src='js/jsfile1.js'></script>
<script type='text/javascript' src='js/jsfile2.js'></script>
<script type='text/javascript' src='js/jsfile3.js'></script>
<script type='text/javascript' src='js/jsfile4.js'></script>
<script type='text/javascript' src='js/jsfile5.js'></script>
<script>
     myApp.init();
</script>

You might have a simple, advanced and other versions of your application and the end user will have to figure out (or you have to explain) which files need to be included for different versions of applications. Also it looks ugly and meaningless for the enduser to include a big list of javascript files.

You can simply include all your javascripts in one big file and minify it, but

  • Sometime you want to keep your javascript libraries separate from your code
  • Also you might want to include different number of javascript files depend on which features user want to use. You will never want to load all javascript files if user want to embed just a simple/basic version of your javascript application.

Append script tags to head?

You might be thinking why don’t make an array of javascript files name, loop through this array and than for each file name, make a script tag and append it to the head tag. Well this is the solution but you might be loading external javascript files or host your javascript files outside on a CDN and some javascript files will load slower than others. Your javascript code might be depended on other javascript files, for example if you are loading jQuery library and than all your jQuery plugins, you might get an error “jQuery not defined” in your plugin files because jQuery might take longer to load than your plugins. So your plugins will load first and jQuery will still be loading so it will break your application.

jQuery’s getScript method can be used to load ONE javascript file at a time. You can use it inside a ‘for’ loop and use getScript’s callback to include the next script in an array of script file names. But you would never like to include a whole jQuery library just for this purpose (when you are not using jQuery anywhere else in your application).

Solution:

My idea to embed javascript application is include a single javascript file. Call a function and pass the type of application as argument. The function should make a list of javascript files to include, depend of the type of application and once all js files are loaded, call a callback function. Something like:

<script type='text/javascript' src='js/jsFileIncluder.js'></script>
<script type="text/javascript">
includeJs('basic','',function(){
	yourApp.init();
});
</script>

Demo

Continue Reading →

6

jQuery equal height columns plugin

Problem:

Recently I have been working on a project and I came across an issue where I have to display ‘Featured products’ in 4 columns with a ‘Read more…’ link at the end of each product details. The number of lines for these 4 columns were not equal and so was not looking clean. To demonstrate, I will take the following example where we have 3 panels/columns with unequal height (live demo):

Solution:

I wrote a small jQuery plugin (only 696 bytes) to achieve 2 main goals:

  • Make these panels of equal height by identifying the smallest height among these panels and than reduce the text in other panels to make it of equal height to the smallest.
  • and add an option to put three dots at the end of the paragraph if its not ending with a full stop.

It should also gracefully degrade if no Javascript support is available on the browser i.e people with Javascript disabled on their browsers will see the panels with unequal height.

Continue Reading →

9

Openlayers draggable popups

Problem:

Recently I have been working on Openlayers, vector features where the user can draw different vector features on the Openlayers map and than show the results like area covered or radius of the polygon drawn.

The best way I could found was to use Openlayers Popup but in this case a ‘draggable popup‘ so that user can drag this information popup around to see the map and features around. I didn’t find any built-in property to do so, so I tried jQuery-ui draggable plugin to drag the popup. It worked fine other than, when you double click the popup and the popup will stick to your mouse pointer forever and there is no way but to refresh the page to get rid of it. Here is the code I was trying:

;(function($) {
  //Create Openlayers map object
  map = new OpenLayers.Map( 'map' );
  //Layer object
  layer = new OpenLayers.Layer.WMS(
              "OpenLayers WMS",
              "http://labs.metacarta.com/wms/vmap0",
                {layers: 'basic'} );
  //Add layer to the map
  map.addLayer(layer);
  //Zooms out to the maximum extent of the map
  map.zoomToMaxExtent();
  //Openlayers popup
  popup = new OpenLayers.Popup(
      "dragging-issue",
      new OpenLayers.LonLat(5,40),
      new OpenLayers.Size(80,60),
      "Drag Me:
Single click, fine
Double click : ( ", true); //Add this popup to the map map.addPopup(popup); //Apply jQuery draggable to the map container of the popup $('.olPopup').draggable(); })(jQuery);

Live Demo of the problem

Continue Reading →

77

jQuery-ui Scrollable tabs plugin

Updates October 27, 2011

Since this plugin doesn’t work with newer versions of jQuery UI, I am not supporting this anymore. Instead I decided to work on a newer and improved version which is half done with most of the features but still need to be improved.

Also one of my friend mekwall (a jQuery guru) :) has written an extension for jQuery-UI tabs for the same purpose which he named Jizmoz Tabs.

Problem:

jQuery UI tabs is one of my favorite jquery plugin I use in most of my projects. It is so simple to use and it degrade gracefully. It has some very nice features and the events are really helpful.

However while I was working on a project where all the tabs contents are dynamic i.e user perform a search and than the results will be grouped up in tabs but the problem was that you never know how many tabs do i need as it can be just 1 or it can be 50. The problem is that you should know the number of tabs so you can give a width to the wrapper so all tabs can fit in one row.

Unfortunately in my case I could not use it because I cannot give the wrapper a width of like 1000px for many tabs. If you give the wrapper a fixed width, the tabs will try to adjust it self in as many rows as it can to adjust all the tabs, something like this:

//jQuery ui tabs
$('#example_1').tabs();

Continue Reading →

Copyright © 2013 — musings of Aamir Afridi
Aamir's QR code