In this post I want to suggest you 10 useful code snippets for web developers based on some frequetly asked questions I received in the past months for my readers. This collection include several CSS, PHP, HTML, Ajax and jQuery snippets.
1. CSS Print FrameworkCascading Style Sheets Framework for web printing. To use this framework download the CSS file here and use this line of code into your web pages
2. CSS @font-face
<link rel="stylesheet" href="print.css" type="text/css" media="print">This snippet allows authors to specify online custom fonts to display text on their webpages without using images:
3. HTML 5 CSS Reset
@font-face {
font-family: MyFontFamily;
src: url('http://');
}Richard Clark made a few adjustments to the original CSS reset released from Eric Meyers.
4. Unit PNG FixThis snippet fixes the png 24 bit transparency with Internet Explorer
5. Tab Bar with rounded corners
This code illustrates how to implement a simple tab bar with rounded corners:
6. PHP: Use isset() instead of strlen()
This snippet uses isset() instead strlen() to verify a PHP variable (in this example $username) is set and is at least six characters long.7. PHP: Convert strings into clickable url
<?phpif (isset($username[5])) {?>
// Do something...
}This snippet is very useful to convert a string in a clickable link. I used this snippet for several tutorials;
8. jQuery: Ajax call
<? php
function convertToURL($text) {
$text = preg_replace("/([a-zA-Z]+:\/\/[a-z0-9\_\.\-]+"."[a-z]{2,6}[a-zA-Z0-9\/\*\-\_\?\&\%\=\,\+\.]+)/"," <a href=\"$1\" target=\"_blank\">$1</a>", $text);
$text = preg_replace("/[^a-z]+[^:\/\/](www\."."[^\.]+[\w][\.\/][a-zA-Z0-9\/\*\-\_\?\&\%\=\,\+\.]+)/"," <a href="\\" target="\">$1</a>", $text);
$text = preg_replace("/([\s\,\>])([a-zA-Z][a-zA-Z0-9\_\.\-]*[a-z" . "A-Z]*\@[a-zA-Z][a-zA-Z0-9\_\.\-]*[a-zA-Z]{2,6})" . "([A-Za-z0-9\!\?\@\#\$\%\^\&\*\(\)\_\-\=\+]*)" . "([\s\.\,\<])/i", "$1<a href=\"mailto:$2$3\">$2</a>$4",
$text);
return $text;
}
?>This is the most simple way to implement an Ajax call using jQuery. Change formId and inputFieldId with the ID of the form and input field you have to submit:
9. CSS Layouts CollectionsThis page contains a collection of over 300 grids and CSS layout ready to use in your projects. Take a look, it's very useful.
10. Simple versatile multilevel navigation MenuSeveral months ago I found this simple code (HTML + CSS + JavaScript for jQuery) to implement a versatile multilevel navigation menu (please send me the original source if you find it!). I think it's the simpler and faster way to do that. The result is something like this:
The only thing you have to do is to create nested lists into a main list with id="nav", in this way:
<ul id="nav">
<li><a href="#">Link 1</a></li>
<li><a href="#">Link 2</a></li>
<li><a href="#">Link 3</a><ul><li><a href="#">Link 3.1</a></li><li><a href="#">Link 3.2</a></li><ul>
</li>
</ul>...and use this basic CSS code (you have to modify it to customize the layout of this menu with the style of your site!
...and this is the JavaScript code for jQuery you have to copy in the tag <head> of the pages that use this menu:
#nav, #nav ul{margin:0;
padding:0;
list-style-type:none;
list-style-position:outside;
position:relative;
line-height:26px;
}
#nav a:link,
#nav a:active,
#nav a:visited{
display:block;
color:#FFF;
text-decoration:none;
background:#444;
height:26px;
line-height:26px;
padding:0 6px;
margin-right:1px;
}
#nav a:hover{
background:#0066FF;
color:#FFF;
}
#nav li{
float:left;
position:relative;
}
#nav ul {
position:absolute;
width:12em;
top:26px;
display:none;
}
#nav li ul a{
width:12em;
float:left;
}
#nav ul ul{
width:12em;
top:auto;
}
#nav li ul ul {margin:0 0 0 13em;}
#nav li:hover ul ul,
#nav li:hover ul ul ul,
#nav li:hover ul ul ul ul{display:none;}
#nav li:hover ul,
#nav li li:hover ul,
#nav li li li:hover ul,
#nav li li li li:hover ul{display:block;}
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
<script type="text/javascript">
function showmenu(){$("#nav li").hover(function(){$(this).find('ul:first').css({visibility:"visible", display:"none"}).show();
}, function(){
$(this).find('ul:first').css({visibility:"hidden"});
});
}
$(document).ready(function(){
showmenu();
});
</script>If you have better solution, just tell me !
Using jQuery For The Animation
The animation is really quite simple. We’ll use jQuery to animate the opacity of the <span> tag. Remember that the <span> tag displays the “hover” state of the image. Hence, when the <span> is visible, the link takes the “hover” appearance. We’ll need the “hover” state to be invisible when the page loads. We can do this by setting the opacity of the <span> tag to “0″:
$(function() {
// set opacity to nill on page load
$("ul#menu span").css("opacity","0");
// the rest of the code will go here
});Placing the code inside of “$(function() { … });” tells the browser to execute the code when the document has loaded. The code that we’ll use to do the animation is as follows:
// on mouse over
$("ul#menu span").hover(function () {
// animate opacity to full
$(this).stop().animate({
opacity: 1
}, 'slow');
},
// on mouse out
function () {
// animate opacity to nill
$(this).stop().animate({
opacity: 0
}, 'slow');
});Hence the entire Javascript used is as follows:
<!-- Include jQuery Library -->
<script src="jquery-1.2.2.pack.js" type="text/javascript"></script>
<!-- Let's do the animation -->
<script type="text/javascript">
$(function() {
// set opacity to nill on page load
$("ul#menu span").css("opacity","0");
// on mouse over
$("ul#menu span").hover(function () {
// animate opacity to full
$(this).stop().animate({
opacity: 1
}, "slow");
},
// on mouse out
function () {
// animate opacity to nill
$(this).stop().animate({
opacity: 0
}, "slow");
});
});
</script>Notice that we first include the jQuery library. You can learn more about jQuery animations by reading up on the
documentation. One final addition to the CSS is required to ensure that the mouse cursor is display as a pointer when hovering over the <span> tag:ul#menu li a span:hover {
cursor:pointer;
}The full source code can be accessed via the demonstration page. I should just add that whilst this code seems to work well with FireFox and IE7, IE6 might (and probably will) be a different story.
If you have better solution, just tell me !
CSS Gradients in Action
Chris Williams has been having some fun with CSS gradients on a quest to create nice looking elements without images.
He uses CSS like this:
.albumInfo { background: -webkit-gradient(linear, 0% 0%, 0% 100%, from(#626262), to(#000000), color-stop(.5, #202020), color-stop(.5, #000000)); height: 8em; padding: 1em; border-top: 1px solid #858585; border-bottom: 1px solid #505050; } .albumInfo h1 { font-weight: bold; text-shadow: 0px -1px 1px black; font-size: 1.2em; } ul.tracks { background: -webkit-gradient(radial, 50% -70, 0, 50% 0, 200, from(#595959), to(#0d0d0d)) #0d0d0d; width: 25.7em; } ul.tracks li.odd { background: -webkit-gradient(linear, 0% 0%, 0% 100%, from(rgba(255,255,255,.05)), to(rgba(255,255,255,.05))); }This example demonstrates the power of WebKit’s implementation of gradients in css. This similar looking display to that of the iPhone album display uses a radial gradient (opposed to a linear) as the background for the track names. The overall effect is a dim light. The odd numbered tracks also use a gradient to take advantage of -webkit-gradient’s support of alpha values.
None of the gradients will work in other browsers. Check that your background and text are not the same color. The outermost div is set to black so it's viewable in other browsers.
Sheer Heart Attack is my favorite Queen album. I'm also quite fond of A Night At The Opera.
If you have better solution, just tell me !
And for a final little nugget of font goodness,
![]()
Zach Johnson is at it again, this time giving us a fun Friday treat with CSS text shadow, all via:
document.getElementById('text-shadow-box').onmousemove = function(e) { var xm = e.clientX - 300; var ym = e.clientY - 175; var d = Math.sqrt(xm*xm + ym*ym); text.style.textShadow = -xm + 'px ' + -ym + 'px ' + (d / 5 + 10) + 'px black'; xm = e.clientX - 600; ym = e.clientY - 450; spot.style.backgroundPosition = xm + 'px ' + ym + 'px'; }If you have better solution, just tell me !
Multiple font weights via CSS 3 and more font fun
The way @font-face works is that whatever font attributes you specify for a @font-face rule, they don’t determine how the font looks but rather when it’s gonna get used. For example if you have the following two rules.
@font-face { font-family: newfont; src: local(Arial); font-weight: 200; } @font-face { font-family: newfont; src: local(Calibri); font-weight: 300; }We posted on TypeKit recently, and we have another playa Kernest in the "fix friggin type on the Web" game.
And for a final little nugget of font goodness,
Typekit looks to include jQuery, loads CSS with base64-encoded data:font/otf URLs
for @font-face. "Safer" than a plain open .TTF, I suppose.If you have better solution, just tell me !
Text rotation for all
Jonathan Snook has posted a nice nugget on text rotation with CSS that takes a nice bit of markup like this:
and converts it to:
all via the CSS:
-webkit-transform: rotate(-90deg); -moz-transform: rotate(-90deg); filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=3);
If you have better solution, just tell me !
Even designers are using CSS3?...
Sean Martell is my hero. He did the Bespin logos and a bunch of the Mozilla works in general. When Ben and I were in Toronto we got to see him at work at his WACOM tablet, and it is a sight to behold.
I wish I could do that kind of design work, but for me it isn't to be.... my design is left to code :
Anyway, he has been working a lot on the Fennec (Firefox mobile) design and just
wrote about using CSS3 to build flexible UI elements without recutting UI graphics all over:Designing UI elements for a mobile browser has taught me a great deal when it comes to creating interactive graphical elements that are to be used in a very small space. Of course, when I say small space, I mean a small space that has the potential to be different for each handset out there. Not only are we talking resolution differences, but the screen DPI can change from device to device as well.
So after resizing and re-slicing the Fennec UI for the second time, I quickly realized that this could be a full-time job for a team of designers depending on the list of handsets Fennec will be appearing on.
Hold the phone… whats this? Firefox 3.5 enables a new slew of fun CSS3 design styles eh? Rounded edges eh? Embedded fonts eh?
* gears turning, monkeys typing, hamsters running *
What if we could replace almost all of the graphical UI elements within Fennec with CSS created equivalents? As a designer, am I comfortable bypassing Photoshop and letting CSS run the pixel rodeo? After a few initial tests, the answer to both of those questions was a very solid “yes”. A solid “friggin’ right” if in Cape Breton.
Here are some nice dark toggles:
with code looking like:
CSS:
.toggleONleft { font-family: ‘DroidSans-Bold’; text-transform:uppercase; padding: 0px 8px 0px 12px; -moz-border-radius-topleft: 0.5em; -moz-border-radius-bottomleft: 0.5em; -webkit-border-top-left-radius: 0.5em; -webkit-border-bottom-left-radius: 0.5em; border-top: 4px solid #aaa; border-left: 4px solid #ccc; border-right: 4px solid #ccc; border-bottom: 4px solid #ccc; -moz-border-top-colors:#aaa #bbb #ccc #ddd; -moz-border-left-colors:#aaa #bbb #ccc #ddd; -moz-border-bottom-colors:#aaa #bbb #ccc #ddd; -moz-border-right-colors:#aaa #bbb #ccc #ddd; background-color: #ddd; display: inline; } .toggleOFFright { font-family: ‘DroidSans-Bold’; text-transform:uppercase; color:#414141; padding: 0px 12px 0px 8px; -moz-border-radius-topright: 0.5em; -moz-border-radius-bottomright: 0.5em; -webkit-border-top-right-radius: 0.5em; -webkit-border-bottom-right-radius: 0.5em; border-top: 4px solid #ccc; border-left: 4px solid #ccc; border-right: 4px solid #ccc; border-bottom: 4px solid #aaa; -moz-border-top-colors:#aaa #fff #fff #fff; -moz-border-right-colors:#aaa #dedede #efefef #fafafa; -moz-border-left-colors:#aaa #dedede #efefef #fafafa; -moz-border-bottom-colors:#aaa #dedede #efefef #fafafa; background-color: #fff; display: inline; }If you have better solution, just tell me !