Web development blog for Html, CSS, javascript, JQuery developers. At Kodecrash you will find best solution for complex problems.

JavaScript Animation Part- I

Posted in Javascript, JQuery

js-animation

In the trend of HTML 5 and CSS 3 it becomes easier to create animations which are supported by modern browsers. We can create any kind of animation using CSS 3. Also, JQuery provides animate() function to create simple animations. In this tutorial, we are going to learn a animation library Tweenmax.js.

Why Tweenmax.js?
JQuery animate function is used to create simple kind of animations. However, it is very difficult to perform reverse, pause, timeUpdate, 3D efffects such operations using animate method. It is very easy to achieve this using Tweenmax.js. We can create slideshow effect using Tweenmax. Advantage of using Tweenmax is we can control animation. Like Tweenmax there are some other objects TweenLite, TimeLineMax which are used to create video kind of animation.

Downloading Tweenmax.js
Use Tweenmax.js from CDN

<script src="http://cdnjs.cloudflare.com/ajax/libs/gsap/1.17.0/TweenMax.min.js"></script>

OR
Download it from https://greensock.com/tweenmax

Simple zoom effect using Tweenmax:

We can use scale() property of CSS 3 to create zoom effect.

<style>
    #boxImg{
      transform:scale(0);
      -webkit-transform:scale(0);
    }
</style>

var box=$("#boxImg")
TweenMax.to(box, 1, {css:{transform:"scale(1)"}, repeat:1});

<img id='boxImg' src="http://kodecrash.com/demos/galleria/images/gallery/daisy.jpg" width="400" height="300"/>

Here, We have used css property of tweenmax. You can use previous syntax also. Initially we have used transform scale to 0 in CSS. In tweenmax we are changing transform property of image. So, this looks like image is scaling through its center. Note, we haven’t use any yoyo, reverse, onUpdate property of tweenmax here. This depends on our requirement. If you want to perform any action during animation you can use those properties and methods.

Click here to see demo

Zoom effect at corner using Tweenmax:

You can scale image at corner using transform-origin property of CSS 3. Refer our previous article on Rotate div at Corner CSS 3 transform to know about transform-origin.

<style>
    #boxImg{
      transform:scale(0);
      -webkit-transform:scale(0);
      -ms-transform:scale(0);
      transform-origin:100% 100%;
      -webkit-transform-origin:100% 100%;
      -ms-transform-origin:100% 100%;
    }
</style>

var box=$("#boxImg")
TweenMax.to(box, 1, {css:{transform:"scale(1)"}, repeat:1});

<img id='boxImg' src="http://kodecrash.com/demos/galleria/images/gallery/daisy.jpg" width="400" height="300"/>

Click here to see demo

Basic Tweenmax example:
In this example we will animate a div using tweenmax.

     var box=$("#demo");
     TweenMax.to(box, 2, {left:"300px", repeat:10, yoyo:true,  repeatDelay:0.5, ease:Linear.easeNone});

In above code, we have used tweenmax object to animate a box. We are animating left position of a box.

Properties:

  • box: box is jquery selector
  • repeat: repeat animation for specified interval
  • repeatDelay: wait for next cycle to repeat.
  • ease: easing effect of animation.
  • yoyo: Boolean – If true, every other repeat cycle will run in the opposite direction so that the tween appears to go back and forth (forward then backward).
  • delay: Duration of one cycle of animation. Here, delay parameter is 2 seconds.
  • onUpdate: Function – A function that should be called every time the tween updates (on every frame while the tween is active)
  • onComplete: Function – A function that should be called when the tween has completed

Callback in Tweenmax:

Like jQuery animate function tweenmax provides callback functions (onUpdate, onComplete etc… )

Using onComplete() in Tweenmax:

 var box;
    $(document).ready(function(){
     box=$("#demo");
    
 TweenMax.to(box, 2, {left:"300px", repeat:4,   repeatDelay:0.5,onComplete:onCompleteHandler, ease:Linear.easeNone});
    });

function onCompleteHandler() {

  box.html("Completed");
 
}

Here, we are using onComplete() function of tweenmax. onComplete will call when animation with specified duration is completed.
Click here to see demo

Using onUpdate() in Tweenmax:

var box;
 var count=0;
    $(document).ready(function(){
     box=$("#demo");
     TweenMax.to(box, 2, {left:"300px", repeat:4,  repeatDelay:0.5, onComplete:onCompleteHandler,ease:Linear.easeNone, onUpdate:onUpdateHandler});
    });

function onCompleteHandler() {

  box.html("Completed");
  
}  
function onUpdateHandler(){
      count++;
      box.html("Count:"+ count );
}

onUpdate() will call every seconds during the animation. Here, you can perform any operations like updating dom elements.

Click here to see demo

Web development blog for Html, CSS, javascript, JQuery developers. At Kodecrash you will find best solution for complex problems.

Create Custom Dropdown using jQuery

Posted in JQuery

We use “select” field of HTML while creating forms. But, sometimes we want to customize this “select” field as per our need. We cannot apply custom look and feel to select field. For that we need to create a custom dropdown. In this example, we are creating dropdown using custom jQuery plugin.

Create custom jQuery plugin

To create a custom plugin we need to create a function which is shown below. This indicates the name of your jQuery plugin.

$.fn.custom_dropdown = function(){
        
    // Your plugin code here….

     return this.each(function() {
            // Initialize Custom Dropdown Plugin
     });
    
};
$("#dropdown").custom_dropdown();

In this way you can call your jQuery plugin. This creates a custom dropdown inside “#dropdown” div.

Passing options/properties to jQuery plugin

$.fn.custom_dropdown = function(options) {
     
        var _defaults={
            
            drpOptions:[],
            optionText:"Select State",
            drpName: "custom_dropdown",
            slideTime:500,
            template: "<div class='drpDown'>"+
                          "<div class='selectedOption'></div>"+
                            "<div class='drop_btn' tabindex='0'></div>"+
                            "<div class='clearCB'></div>"+
                            "<ul class='select_drop_down'>"+
                            "</ul>"+
                          "<input type='hidden' val='' />"+
                      "</div>",
            
        };    
};

These are default parameters to our custom dropdown plugin.

  1. drpOptions:
    Type: Array
    – This is an array consisting of all options in custom dropdown.

  2. optionText:
    Type: String
    – This is default text in dropdown. If not provided it will use “Select State” as default value.

  3. drpName:
    Type: String
    – Name of the dropdown. This will override name of input field present in custom dropdown template parameter.

  4. slideTime:
    Type: Number
    – This is time to close and open all dropdown options. This is optional field. Default slideTime is 500 ms.

  5. template:
    Type: String
    – This is custom dropdown HTML template. You cannot override this.

Template consists of ‘selectedOption’ div which will show selected option from dropdown.
‘drop_btn’ div is to expand and close dropdown. There is ‘select_drop_down’ list here we will populate all dropdown options from drpOptions array.

$.fn. custom_dropdown = function(){
        
    // Your plugin code here….

        var _self=this;
        var _settings = $.extend( {}, _defaults, options );
        
        // initialize custom_dropsown
        var _init=function(){
            _setTemplate();
            _setEvents();
        };
};

Assign current (this) object to _self variable to avoid confusion. This object contains current jOuery selector to which you have applied custom dropdown plugin. For example, if you are using below code

$("#dropdown").custom_dropdown();

Then “this” variable contains #dropdown selector.

Except template property all other properties are optional. If you are not passing any property to your custom dropdown then default properties will be used. $.extend function will merge option object passed by user and _defaults object. So _settings will be merged object which contains both properties from option as well as _defaults. Properties in _defaults object will be overriden by option object.

_init function will initialize our custom dropdown plugin. This will also call _setTemplate and _setEvents functions.

var _setTemplate=function(){
           
            _self.empty();
            // append template to selector
            _self.append(_settings.template);
            var drpListEle=  _self.find(".select_drop_down");
            _self.find("input").attr("name",_settings.drpName);
            _self.find(".selectedOption").text(_settings.optionText);

            // Iterate drpOptions array and create list options
            $.each(_settings.drpOptions,function(index,value){
                if(index==0) drpListEle.append("<li tabindex='"+(index+1)+"' value='"+_settings.optionText+"'>"+_settings.optionText+"</li>")
             // append list option to ul tag
                else  drpListEle.append("<li tabindex='"+(index+1)+"' value='"+value+"'>"+value+"</li>")
            });
        };

In above code, we have used $.each function which iterates all drpOptions array and append all items to “.select_drop_down” list. This will set up our UI part of custom dropdown. Next we will bind events to our custom dropdown elements.

$.fn. custom_dropdown = function(){
        
    // Your plugin code here….

var _setEvents=function(){
            var drpBtn=  _self.find(".drop_btn");
            var drpOption=_self.find(".select_drop_down li");
            var drpSelectedOption= _self.find(".selectedOption");
            var drpInput=_self.find("input");
            var drpList=_self.find("ul");
            
            // Handle dropDown click event
            drpBtn.click(function(){
                  // toggle state of all options
                 drpList.slideToggle(_settings.slideTime)                     
            });

             // Handle option click event
            drpOption.click(function(){
                  drpSelectedOption.text($(this).text());
                  drpInput.val($(this).text())
                  // hide all options
                  drpList.slideUp(_settings.slideTime)
                  // Reseting styles of all options
                  drpOption.removeAttr("style");
            });
            
            
            // Handle option hover event
            drpOption.hover(function(){
                 drpOption.removeAttr("style");
                 $(this).css("background-color","#EEE");   
            });
            
            
        };
};

In _setEvents function, we are binding click to down arrow button. This will toggle state of all options in dropdown. On hover, we are just highlighting each option in dropdown. We are using jQuery slideToggle function to open and close dropdown options. You can change slideTime by overriding slideTime property in _defaults object. There is hidden field in this we are storing value of selected option. You can use it as a form variable while creating forms.

Demo

Download custom_dropdown plugin here…