March 7, 2013

Pass function as css value in jQuery

In jQuery version 1.4, it allows us to pass a function as css value for the method .css(). According to the document :

.css( propertyName, function(index, value) )
propertyName
Type: String
A CSS property name.

function(index, value)
Type: Function()

Definition: A function returning the value to set. this is the current element. Receives the index position of the element in the set and the old value as arguments.

The basic idea is, when you use .css() method and pass function as value. It will call the function with passing back the current element index and current value (the css property) as argument for dynamic computation or set under some conditions. Then after computed, return value for to set the target "propertyName".

For example: You can think there is a "Increase font size" button in your web site and you would like to double size the current font size when clicked the button. You can make use of .css to achieve that.

Code example : Click the "Bigger hello world"


Hello world

Source code :

<input type="button" value="Bigger hello world" id="enlargeBtn" />
<div id="helloWorldContent">
 Hello world    
</div>

<script type="text/javascript">
 $("#enlargeBtn").on('click', function(){
   $("#helloWorldContent").css('font-size', function(index, value){
     var size = parseInt(value, 10);
     return size*2;
   });
 });
</script>

No comments:

Post a Comment