• Jquery for Beginners – Manipulation of CSS related properties

    Posted on July 30, 2012 by in Jquery, Other Programming

    In the previous article, we have seen how to get/set and change attributes, classnames etc. In this Article, we will go through some more of the methods provided by JQuery to manipulate CSS-related properties of elements. We will be using the below HTML through the code

    <html lang="en-US">
     <head>
    <title>::Qnownow - Jquery CSS Manipulation ::</title>
    <script type='text/javascript' src='js/jquery-1.7.2.min.js'></script>
    <style>
    	#bottomcontainer {
    		background-color:#66FCFC;
    		margin:10px;
    		padding:5px;
    		height: 240px;
    	}
    	
    	.boxtype1 {
    		float:left;
    		background-color:#76FC66;
    		margin:20px;
    		padding:15px;	
    		width : 150px;
    		height : 150px;
    		border:3px solid black;
    	}
    	.boxtype2 {
    		float:left;
    		background-color:#FCBC66;
    		margin:20px;
    		padding:15px;	
    		width : 150px;
    		height : 150px;
    		border:3px solid black;
    	}
    	.boxtype3 {
    		float:left;
    		background-color:#FC66B2;
    		margin:20px;
    		padding:15px;	
    		width : 150px;
    		height : 150px;
    		border:3px solid black;
    	}
    	</style>
    </head>
    <body>
    			<div id="container">
    				<div id="topcontainer">
    					<div style="background-color:#FCFC66;padding:5px;">Top Header</div>
    				</div>
    				<div id="bottomcontainer">
    					<div id="leftbox" class="boxtype1">Left</div>
    					<div id="centerbox" class="boxtype2">Center</div>
    					<div id="rightbox" class="boxtype3">Right</div>
    				</div>
    			</div>
    </body>
    </html>
    

    Output of the above code

    JQuery CSS Manipulation

    css

    .css() is easy method get or set style property of first matched element. The .css() is one of the examples that takes care of cross browser issues you might come accross when using traditional javascript. To elaborate further, if you were to get css property such as fontSize, fontFamily, margin, padding, backgroundColor etc you could use the below code

    // el  -- element, styleProp -- the property you want to retrieve
    	var x = document.getElementById(el);
    	if (x.currentStyle)
    		var y = x.currentStyle[styleProp];
    	else if (window.getComputedStyle)
    		var y = document.defaultView.getComputedStyle(x,null).getPropertyValue(styleProp);
    	return y;
    

    As you can see you need to check whether the browser supports getComputedStyle or currentStyle and get the value depending on it, JQuery does all this work for us., we can just use the .css() to retrive the properties

    $(document).ready(function(){
    	alert($("#header").css('background-color'));
    });	
    

    The above code get background-color property of div with id header, Setting a value is as simple as it is to get value. If you were to change the background-color of the header element you could use

        $("#header").css('background-color','#FFCCFF');
    

    If want to change multiple values at once, you can send all of them as name value pairs as shown below

        $("#header").css({'background-color':'#FFCCFF','padding': '7px'});
    

    addClass, removeClass and toggleClass

    As the name suggests .addClass is used to add a class to an element. Please note that addClass adds a class to existing list of classes, it does not replace the classes

        $("#leftbox").addClass('whatever');
    	
    	//the otput of the above statement would be
    	<div id="leftbox" class="boxtype1 whatever">Left</div>
    	
    	//and not
    	<div id="leftbox" class="whatever">Left</div>
    

    .removeClass([classname]) is used to remove class name of an element. If a class name is included as a parameter, then only that class will be removed from the set of matched elements. If no class names are specified in the parameter, all classes will be removed.

    //remove only whatever class name
    $("#leftbox").removeClass("whatever");
     
    //remove all the classes
    $("#leftbox").removeClass();
    

    This method takes one or more class names as its parameter. if an element in the matched set of elements already has the class, then it is removed; if an element does not have the class, then it is added. For example, we can apply .toggleClass() to above image

    $("#leftbox").toggleClass("whatever");
    

    It removes whatever if it is present or adds toggleclass if it is missing.

    width and height

    Gives the width of an matched element not including padding and margin. Please look at the image below

    JQuery CSS Manipulation

       var wid = $("#leftbox").width();
       // gives 150 which is the width of the div element 
    

    .innerWidth() gives the width of an element including the padding, ie. innerwidth = leftpadding + widthofelement + rightpadding

       var wid = $("#leftbox").innerWidth();
       // since the left and right padding for our div is 15px, innerwidth =  15 + 150 + 15; which is 180
    

    .outerWidth() gives the width of an element including the padding and borders of the element and optionally can include margins of the element too.

       // since the left and right padding for our div is 15px, border is 3px, outerwidth =  3 + 15 + 150 + 15 + 3; which is 186
       var wid = $("#leftbox").outerWidth();
       // if you want to include margins too, just pass true as parameter
       var wid = $("#leftbox").outerWidth(true);
       // the above includes margins too, which gives 226
    

    The .height(), .innerHeight(), .outerHeight() give the height but work in similar way as the width examples.

    offset and position

    <div id="main" style="position: absolute; top: 200; left: 200;">
         <div id="sub"></div>
     </div>
    

    The .offset() method allows us to retrieve the current position of an element relative to the document. .position(), which retrieves the current position relative to the offset parent i.e , the offset parent is the closest positioned parent. that is, an element with position set to absolute, relative or fixed.

       var left = $("#sub").offset().left;// gives 200
       var top = $("#sub").offset().top;// gives 200
       
       var posleft = $("#sub").position().left;// gives 0
       var postop = $("#sub").position().top;// gives 0
    

    you can also set offset as given below

        $("#main").offset({ top: 100, left: 150 });
    
    Be Sociable, Share!

    Written by

    Vanamali Juvvadi is a Web enthusiast and loves all things design and technology. Founded qnownow with a group of friends to share anything/everything they know/find on the internet.

    View all articles by

    Email : [email protected]

    Leave a Reply