8 Javascript solutions to common CSS problems
CSS are definitely a great technique for web designers and web developpers. Though, cross-browser problems and lack of CSS3 support in modern browsers are a real problem for your creativity. Today, I have compiled a list of 8 common CSS problems that you can easily resolve with help from Javascript.
1- Transparent backgrounds with JQuery
Ah, transparent backgrounds. Due to the fact that IE6 can’t handle transparent png images, this has been a problem for years. Although many techniques are availables in order to solve this recurring bug, this one is really good because it allows you to make any element transparent, without even using transparent png files.
- Download theses files and include them in your website:
http://jqueryjs.googlecode.com/files/jquery-1.2.6.min.js
http://design-forge.ro/projects/opensource/transBG.jquery.plugin.js - Adapt the following code to your own needs and paste it in the head part of your html document, or even better, in a separate .js file. Basically, Just use the transBGdraw() function on each element you’d like to make transparent.
$("#id").transBGdraw(); $("#menu").transBGdraw(); $("#container").transBGdraw(); // !!!IMPORTANT!!! // if you use tagnames or classes, make sure every object affected has a unique id. $("div").each(function() { $(this).transBGdraw(); }); $("h6").each(function() { $(this).transBGdraw(); }); $(".class1").each(function() { $(this).transBGdraw(); }); $(".text").each(function() { $(this).transBGdraw(); }); $(".information").each(function() { $(this).transBGdraw(); });
- You’re done. Easy, isn’t it?
2 – Include different classes for different browsers
Thanks to Microsoft and Internet Explorer, the bigger problem for every front-end developper is definitely cross-browser compatibility. Even if Internet Explorer introduced conditional tags to include styles only for IE, it can be good to be able to deal with other browsers as well.
- This code works with the JQuery framework, so of course make sure you have it installed on your website.
- Paste the following code in the head part of your html document or in a separate .js file:
$(document).ready(function(){ $('html').addClass($.browser); });
- Now you can preprend your styles with .msie, .mozilla, .opera, .safari or .other depending on the targeted browser.
3 – Columns of equals height with JQuery
When using a table, all the columns of this table have the same height. During web design early days, everyone was using tables to style their web pages so creating columns of the same height weren’t a problem at all. But with the rise of CSS, things changed and now, creating columns of equal height isn’t an easy job.
Happilly, here’s a real life saver for everyone looking to create identical columns.
- As this code uses the JQuery framework, make sure you have it installed on your webiste!
- Paste the following script in a new file and include it to your web page:
/*-------------------------------------------------------------------- * JQuery Plugin: "EqualHeights" * by: Scott Jehl, Todd Parker, Maggie Costello Wachs (http://www.filamentgroup.com) * * Copyright (c) 2008 Filament Group * Licensed under GPL (http://www.opensource.org/licenses/gpl-license.php) * * Description: Compares the heights or widths of the top-level children of a provided element and sets their min-height to the tallest height (or width to widest width). Sets in em units by default if pxToEm() method is available. * Dependencies: jQuery library, pxToEm method (article: http://www.filamentgroup.com/lab/retaining_scalable_interfaces_with_pixel_to_em_conversion/) * Usage Example: $(element).equalHeights(); Optional: to set min-height in px, pass a true argument: $(element).equalHeights(true); * Version: 2.0, 08.01.2008 --------------------------------------------------------------------*/ $.fn.equalHeights = function(px) { $(this).each(function(){ var currentTallest = 0; $(this).children().each(function(i){ if ($(this).height() > currentTallest) { currentTallest = $(this).height(); } }); if (!px || !Number.prototype.pxToEm) currentTallest = currentTallest.pxToEm(); //use ems unless px is specified // for ie6, set height since min-height isn't supported if ($.browser.msie && $.browser.version == 6.0) { $(this).children().css({'height': currentTallest}); } $(this).children().css({'min-height': currentTallest}); }); return this; };
- Use the following code to make the top-level childs of an element having the same height:
$('.container').equalHeights();
4 – Cross browser rounded corners
Rounded corners are gorgeous, but they’re also a lot of images and <div> tags, due to the lack of the border-radius CSS3 property in current browsers.
This JQuery script allows you to round any element. Sweet, isn’t it?
- One more code that works with JQuery, so double check you have it installed on your website.
- Download this file and include it in your html page.
- Once done, use the following code to round a div:
DD_roundies.addRule('.myContainer', '8px');
5 – Fixing IE overflow problem
One more annoying IE problem is the rendering of the overflow property. Happilly this code can help.
- Simply paste the following Javascript code in the head part of your html document, or in a separate .js file:
window.onload = function () { // only apply to IE if (!/*@cc_on!@*/0) return; // find every element to test var all = document.getElementsByTagName('*'), i = all.length; // fast reverse loop while (i--) { // if the scrollWidth (the real width) is greater than // the visible width, then apply style changes if (all[i].scrollWidth > all[i].offsetWidth) { all[i].style['paddingBottom'] = '20px'; all[i].style['overflowY'] = 'hidden'; } } };
- The code, which will only apply to IE, will look for all elements having the well known overflow problem, and fix it. Althought this can be done in pure CSS, this Javascript solution is interresting.
Source: Fixing IE overflow problem
6 – Vertical alignments
In CSS, vertically centering an element within its parent isn’t always an easy thing, and this is why Javascript can help here.
- Simply paste the following code in a separate .js file or in the head section of your html document:
function AlignMiddle(Parent,Child) { //Generate content dynamically document.getElementById(Child).innerHTML="Hello there, I am dynamically align in the middle using a Javascript." //Center Vertically h = document.getElementById(Child).offsetHeight; //var a=Math.round(document.getElementById(Parent).style.pixelHeight/2); var a=Math.round(parseInt(document.getElementById(Parent).style.height)/2); var b=Math.round(h/2); var c=a-b; document.getElementById(Child).style.top=c+"px"; //Center Horizontally w = document.getElementById(Child).offsetWidth; //var x=Math.round(document.getElementById(Parent).style.pixelWidth/2); var x=Math.round(parseInt(document.getElementById(Parent).style.width)/2); var y=Math.round(w/2); var z=x-y; document.getElementById(Child).style.left=z+"px"; }
7 – Image preloading
The Mootools framework have a very nice image preloader. But not everyone like Mootools.
//this is my new preloading method preloadImages = { count: 0 /* keep track of the number of images */ ,loaded: 0 /* keeps track of how many images have loaded */ ,onComplete: function(){} /* fires when all images have finished loadng */ ,onLoaded: function(){} /*fires when an image finishes loading*/ ,loaded_image: "" /*access what has just been loaded*/ ,images: [] /*keeps an array of images that are loaded*/ ,incoming:[] /*this is for the process queue.*/ /* this will pass the list of images to the loader*/ ,queue_images: function(images) { //make sure to reset the counters this.loaded = 0; //reset the images array also this.images = []; //record the number of images this.count = images.length; //store the image names this.incoming = images; //start processing the images one by one this.process_queue(); } ,process_queue: function() { //pull the next image off the top and load it this.load_image(this.incoming.shift()); } /* this will load the images through the browser */ ,load_image: function(image) { var this_ref = this; var preload_image = new Image; preload_image.onload = function() { //store the loaded image so we can access the new info this_ref.loaded_image = preload_image; //push images onto the stack this_ref.images.push(preload_image); //note that the image loaded this_ref.loaded +=1; //fire the onloaded (this_ref.onLoaded)(); //if all images have been loaded launch the call back if(this_ref.count == this_ref.loaded) { (this_ref.onComplete)(); } //load the next image else { this_ref.process_queue(); } } preload_image.src = image; } }
To begin preloading images use the method preloadImages.queue_images([IMAGES]) where [IMAGES] is an array of images. Everything will be processed internally. There are two methods you can use: onLoaded and onComplete.
onLoaded will fire whenever an image has finished loading. All the properties of the loaded image are available in the variable loaded_image. For example if you want to find the width of the image that just finished loading your code would look like this.
Source: Javascript Image Preloader
8 – Killing IE6
Tired of having apefectly valid CSS code which didn’t display correctly in this obsolete browser for some unknown reason? Then, what about getting rid of this piece of crap? Just insert the following code in your html file, and say goodbye to IE6. It will crash automatically once the page is loading.
function getX( oElement ) { var iReturnValue = 0; while( oElement != null ) { iReturnValue += oElement.offsetLeft; oElement = oElement.offsetParent; } return iReturnValue; }
No comments:
Post a Comment