Thursday, 8 January 2015

The 10 text based CSS styles

CSS and Text

Text Colour

You’ve already seen this being used in the examples in the preceding tutorials, so you should know it now. To change the colour of your text you simply use the property, color, like so:
h2 {color: silver; }
a:active {color: #ff0000; }
As in every part of web design, you can specify the colour as a HEX code or a named colour value.

Typeface

The property for defining the typeface (or font, whatever), is font-family. You can define a list of alternative fonts like we used to do with the <font> tag; and as always, you’re advised to leave the last entry as a general family of fonts. A typical line using this command would be:
h3 {font-family: Verdana, Arial, Helvetica, sans-serif; }
Your browser deals with this the same way as it did with font face definitions before: it will keep going down the list of faces you’re specifying until it finds one that’s installed on the user’s system. If all else fails, your final family should cause the text to display in at least afont similar to what you wanted.
sourcetip: if any of your fonts have multiple-word names, wrap some double-quotes around the whole name, to make it clear to your browser that they’re all part of the same entity.
p {font-family: Georgia, "Times New Roman", serif; }

Text Size

CSS gives you full control over the size of your text. Using CSS, you can set your text in any point size, the same way that all other print and graphic designers can already. This is immediately great for creating text bigger than what was originally possible (going up to size 7 with <font size> — the equivalent of only 36pt text). Now you can get infinitely big text.
It also means you can be far more precise with your font sizes — never before have you been able to get 11pt text, which lay between sizes 2 and 3.
To size your text you use the font-size property, and have a number of different units and methods with which to set the exact size. They are:
  • units: ems, points and pixels
  • pre-defined keywords
  • percentages
As we will see, some of these units are better than others for certain purposes.

Ems

Ems are my preferred unit of sizing. They are text units that set the size of text relative to the surrounding text. They are fully resizable, so that if you choose a text size that a user is not comfortable with, they are able to resize the text in their browser so that it becomes readable (the option is under View > Text Size). Default text is set at 1em, so you set other text relative to this value. For instance:
p {font-size: 0.9em; }
strong {font-size: 1.5em; }
This CSS code sets the font size of all text in paragraphs to be slightly smaller than a user’s default text size. If you put any text between strong tags, which is already in a paragraph, this text would appear one and a half times the size of the text in its parent element (therefore, 1.5 times the size of text in paragraphs).
Exacting designers will bemoan the fact that their text is sized differently in different browsers, due to the differences of some user’s default text size. However, this is missing the point: users should have the ability to resize text. If a user has explicitly set their default text size to be bigger than normal, your site should accommodate them by having text that resizes accordingly.

Points

If you’ve ever used text in a graphics editor or used a word processor you should be aware of how text size is defined in points (abbreviated to pt). The default size for text in most word processors is about 12pt. Example:
p {font-size: 30pt; }
This will create some rather impressive big text.
Points were really introduced to CSS for the benefit of print designers used to the unit. They offer good control, but are most appropriate for sizing the text in a print stylesheet. The big problem which stands in the way of them being a good unit for screen text is that the font size cannot be modified using your browser’s font size buttons for users of Internet Explorer. This is a big problem for lots of people, especially those with impaired eyesight — it may make your content inaccessible.
If you’re going to use points — and you shouldn’t — don’t specify main body text anything lower than 10pt, or there’ll be trouble. It’s best that you don’t use points at all — a better option is...

Pixels

If you’ve been designing for any length of time you’ll probably have learnt all about pixels — all your layout elements will be specified in them. Formatting your text with them, while excellent on-screen, can cause problems when printing out a web page. Often each character will only print as a single dot. Not good.
h2 {font-size: 17px; }
Pixel-defined text will, however, circumvent the normal problem of text appearing slightly smaller through a Mac operating system as opposed to a Windows one. If you’re sure your content will be used purely online, this is a good choice. However, be aware of the drawbacks: Internet Explorer users will not be able to resize your text. Use ems for best results.

More Units

There are a few other units of text-measurement that are less widely used, but they may give you the options you need:
  • in is inches
  • cm is centimetres
  • mm is millimetres
  • pc is picas
  • ex is x-height

Keywords

There are a number of keywords that are part of the CSS specifications that you can use to size your text without having to get into measuring things out with units. They’re less precise, but friendly and helpful when the text size isn’t entirely critical. There are seven of these keywords, and they work similarly to the old <font size> values. You define them like so, and the possible values are below:
b {font-size: large; }
  • xx-small
  • x-small
  • small
  • medium
  • large
  • x-large
  • xx-large
What these values correspond to has been left open by the » W3C, and so the browsers display text differently. Thankfully, they allow the reader to adjust the size in their browser.
You can also use the two relative values smaller and larger. Like em values, these affect text relative to the governing value of the parent element.

Percentages

Percentage values are again relative to the size of the parent value, and very similar to emvalues. If you had the code
div {font-size: 20px; }
p {font-size: 200%; }
Every paragraph inside your div would be sized 40px. Simple.
And that’s the lot. You get a load of flexibility, don’t you? Just be sure to always have a look at your page in at least another browser and if possible across platforms to make sure what looks fine on one doesn’t look wrong on the other, as sizing is still a bit inconsistent.

Special Effects

We’ll start off with the not-so special effects like boldness and italics here, and go on to the newest formatting options.

Italics

The CSS command for italics is font-style. You can set it to either italicoblique or normal. Thus:
p {font-style: italic; }
Italic and oblique will cause the browser to look for that version of a font on your system (you should specify the version you think will be there). If one doesn’t exist it may generate the font for you. Setting it to normal will override any inherited values.

Boldness

The property that controls the boldness of text is font-weight. You get many options for this beyond our old choices of ‘bold’ and ‘not bold’.
th {font-weight: bold; }
That is the basic boldness command that will output bold text like you could have before. Using normal will allow you to go back to regular-weighted text.
You can also specify the weight using a number between 100 and 900, as long as it’s a multiple of 100. Normal text has a boldness of 400, so you can imagine what going up or down means. The distinct values for each number are up to the browser, and some fonts will not have this option available, as they don’t have all the weights built in. Stick with common fonts like Arial (and a larger than normal font size) and it should work and be noticeable. These levels are not fully supported in browsers yet though.
Also, there are two relative values for incrementing or decrementing the boldness by one level. They are lighter and bolder.

Capitalisation

There are two properties that allow you to automatically set the capitalisation of your text. First, font-variant allows you to set all your characters in small versions of capital letters.
p {font-variant: small-caps; }
That would create text like this. It looks cool, and works well for acronyms, like nato. The second property is text-transform.
div {text-transform: uppercase; }
Possible values are uppercase, which makes all the letters capitals; lowercase, which makes them all small characters; capitalize, which will capitalize the first letter in every word; and none, which will override any inherited transformation.

Final Effects

The last of the formatting properties is text-decoration. With this, finally, you can get rid of the underlines under links, as well as add lines and other effects to regular text.
a {text-decoration: none; }
The values available are none, which takes away any extra formatting and leaves only normal text; underline, which adds a simple underlineoverline, which adds a line over the textline-through, which creates a strike-through effect; and blink, which is the CSS equivalent of HTML’s most hated tag, Netscape’s <blink>, and makes the text flash on and off. It’s not supported by Internet Explorer.
If you want to take away the underlines on your links, read our short non-underlined linkstutorial.

Text Alignment

Just like old times, you can align your text to the sides and centre. The property for this istext-align. It will only work on block-level elements — i.e. those which add line breaks around themselves, like h1p and div.
div {text-align: center; }
Your options are the usual bunch of leftright and center. You also have a new option which I use here on HTML Sourcejustify. See how all the text ends in a straight right margin here? That’s the text being justified over the available space.

Vertical Alignment

This command allows values like img’s align attribute did in HTML. Vertical-align defines the alignment of an element (not just text this time) in relation to its parent. The values proposed are:
  • top aligns the top of the element with the tallest parent element on the line.
  • bottom aligns the bottom of the element with the lowest parent element on the line.
  • text-top aligns the top of the element with the top of the font of the parent element.
  • text-bottom aligns the bottom of the element with the bottom of the font of the parent element.
  • baseline aligns the baseline of the element with the baseline of the parent element.
  • middle aligns the midpoint of the element with the middle of the parent element.
The code below will align text to the top of an image entered alongside the text, and add a margin around the image so it has some space to breathe.
img {vertical-align: top; margin: 10px; }
Text can also be turned into superscript and subscript:
  • sub puts the element in subscript.
  • super puts the element in superscript.
This is useful if writing about mathematical equations and the like:
.superscript {vertical-align: super; }
<p>Einstein’s most famous equation was E=mc<span class="superscript">2</span></p>
Which will yield:
Einstein’s most famous equation was E=mc2

Text Spacing

But wait there’s more! With CSS comes another first: being able to control the exact spacing between your characters, words and lines. You now have even more ways to lay out your text for optimum readability and style. First up, letter-spacing:
p {letter-spacing: 3px; }
To create this groovy effect. Swish, no? You may know letter-spacing by its other name, kerning also. The value you set it to will be added onto the current browser default. You can use any of the units from above here too. Word-spacing is the same, it’ll just add more space between all your words. The same units are usable. Sadly, it isn’t very well supported, so you may not see any effects.

Text Indents


No more do you need to keep adding in all those &nbsp;s at the start of your paragraphs! With the text-indent property you can have your browser do it for you.
p {text-indent: 10px; }
This command indents the first line in every paragraph (or other block-level element you might want to use). Again, you can use any of the length units from above. You can use a negative value too to create a hanging-indent, where the first word or two start more to the left than the actual paragraph. Be aware of browser bugs here though. Proper margins are discussed in the margins and padding tutorial.

Line Spacing


Next we have line-height, or as you may know it, leading. The value you set this to is the space between the baselines of two lines of text (read about the parts of letters from this » typeface tutorial), and your specified value completely replaces the browser default.
There are three ways to specify a line-height, through numbers, units or percentages.
p {font-size: 10px; line-height: 2em; }
That example uses ems. Your browser multiplies the number you give it by the font size of the text and sets the spacing between lines to this value. This means your spacing will be relative to your text size. You can use decimals for the value too.
Specifying it in units involves using any of the units from earlier on in this tutorial to set the spacing. Percentages are relative to the font size, so 200% leading with 10pt text creates a 20pt space between lines. You can get text to overlap itself using this property, but it isn’t advisable due to differences in browser interpretation. If you want to overlap elements, read the layers tutorial.

The Shorthand Property

You can specify many of these properties in a shorthand property, font, like this:
p {font: bold italic 14px/1.2 Georgia, sans-serif; }
The rule above is equivalent to the rules below, though a good deal more efficient.
p {font-weight: bold; font-style: italic; font-size: 14px; line-height: 1.2; font-family: Georgia, sans-serif; }
This one property can be used to define the values for font-weightfont-variantfont-style,font-sizeline-height and font-family.
To use the font property, you must specify values for the font-size and font-family. If aline-height value is to be supplied, it must come directly after the font-size value, separated by a slash. All of the other properties are optional, and can come in any order; but must be specified before the font-size value. In simple terms, here’s the syntax, with brackets around the optional values:
font: [weight] [style] [variant] size [ / line-height] family;

Lists

CSS also has something to offer to snazz up your bulleted lists. Now you can use images as bullets and decide on what bullet-style your lists use through CSS instead of messing about with presentational attributes. The property that’s going to do all this for us is list-style. This is the shorthand property, which can be broken down into list-style-typelist-style-positionand list-style-image if you only need to modify one or two aspects of the list.
The list-style-type property has the same results as the old HTML attributes had. There are specific values for both ols and uls. You can guess which correspond to which. Available values are: discsquarecircledecimallower-romanupper-romanlower-alphaupper-alphanone. Here’s the HTML and CSS for a list with uppercase alphabetic bullets:
<ol class="upperalphalist">
  <li>Since this is the first list item, it will be bulletted with an “A”</li>
</ol>
.upperalphalist {list-style-type: upper-alpha; }
And here’s how it looks:
  1. Since this is the first list item, it will be bulletted with an “A”
You can set list-style-position to inside or outside to set whether the bullet is in the margin on its own or whether the text wraps in under it on the second line.

Using Images as Bullets

Undoubtedly one of the most interesting of the new CSS properties is the ability to set lists touse images as bullets. This is accomplished rather easily using a format like
ul.pool {list-style-image: url(media/redbullet.gif); }
Creating a ul element with the class="pool" will then result in a list that looks like this:
  • Groovy. The best thing about this, of course, is that you need not worry about the accessibility of using images as bullets, because the HTML is still using lists.
  • If the image can’t be found by the browser, the bullet will appear as the default dot.
Remember: the image’s source will be relative to the stylesheet, just as when you specifybackgrounds.
If you do want to set all of these properties at the same time, you can use the aforementioned shorthand property, which sets all three sub-properties in one command. It looks like this:
ul {list-style: circle inside url(media/redbullet.gif); }
You don’t really need to specify the list-style-type property (“circle”, in this case) if you’re also going to be specifying a list-style-image, but it helps if the image is ever unavailable

The 10 Jquerry undraggable options

Description Example
1 Constrain drag to within parent element.
$('#drag2').udraggable({
    containment: 'parent'
});

2 Constrain drag to a specified rectangular area.
$('#drag3').udraggable({
    containment: [ 40, 40, 180, 170]
});
Note: the coordinates constrain the possible positions of the top left corner of the draggable element

3 Constrain position of dragged item to a 30px by 30px grid.
$('#drag4').udraggable({
    containment: [ 0, 0, 270, 210],
    grid:        [ 30, 30 ]
});

4 Apply draggable behaviour to multiple elements at one time. Red elements can only be dragged on the "y" axis (up and down). Green elements can only be dragged on the "x" axis (left and right).
$('.blk-red').udraggable({
    containment: 'parent',
    axis:        'y'
});

$('.blk-green').udraggable({
    containment: 'parent',
    axis:        'x'
});

5 Constrain drag to a rectangular area larger than the containing element. The parent element uses the "overflow: hidden" style to apply a clipping region.
$('#map').udraggable({
    containment: [ -960, -395, 0, 0]
});

6 It is of course possible to drag an element that contains draggable elements.
$('#drag11').udraggable({
    containment: 'parent'
});

$('.sub-drag').udraggable({
    containment: 'parent'
});

7 The 'start', 'stop' and 'drag' options allow you to monitor the progress of a drag through callback functions. The item being dragged will also have the "udraggable-dragging" class applied to it automatically - you can use CSS to take advantage of this.
This example also sets the distance threshold. The drag operation will not start until the pointer has been moved at least 15px after the initial touchstart / mousedown.
$('#drag14').udraggable({
    distance: 15,
    containment: 'parent',
    start: function () {
      $('#stat-mode').text('Dragging');
    },
    stop: function () {
      $('#stat-mode').text('Idle');
    },
    drag: function (e, ui) {
      var pos = ui.position
      $('#stat-x').text(pos.left);
      $('#stat-y').text(pos.top);
    }
});

8 You can override the positionElement function used to adjust the position of the dragged element. This example uses CSS transforms rather than the default left, top.
$('#drag15').udraggable({
    containment: 'parent',
    positionElement: function ($el, dragging, x, y) {
        if (dragging) {
            $el.css({
                left: 'auto',
                top: 'auto',
                transform: 'translate(' + x + 'px,' + y + 'px)'
            });
        }
        else {
            $el.css({
                left: x,
                top: y,
                transform: 'none'
            });
        }
    }
});

9 This example defines a drag handle. Although the whole panel can be dragged, you can only drag it by the blue title bar.
$('#dialog').udraggable({
    containment: 'parent',
    handle:      'h1'
});

10 The handle selector can reference multiple 'drag handle' elements. In this somewhat silly example the dice can be dragged but only by the dots.
$('.dice').udraggable({
    containment: 'parent',
    handle:      '.dot'
});


Reference: http://www.jqueryrain.com/?oKeiXXJx

Wednesday, 10 July 2013

The 10 jQuery Common Mistakes

Common jQuery Mistakes


Well, Everyone makes mistakes and and best part would be not to repeat them again. You should "Always make new mistakes" :). jQuery is awesome library. But believe me, it can make you crazy if it is not used properly and efficiently. It can hit performance of your page and you don't even realize it. Ask yourself that as a developer while writing jQuery code do you really think about performance or it is only when your client shouts.

I have listed down 10 common jQuery mistakes from my personal experience and their fixes that you might be also doing while writing jQuery code.

1. Be courageous to remove jQuery


Sometimes things can be done easily via CSS without even thinking about jQuery but we don't realize it. Plain CSS is far better than jQuery. So be open and courageous to remove jQuery whenever needed.

2. Not using latest version of jQuery


jQuery team is keep on updating the jQuery library and the newer version comes with lots of bug fixes and performance enhancement. I understand that it is not always possible for you to use the latest version for your old projects but I suggest for your new projects, you can use latest version of jQuery.

Read "How to always reference latest version of jQuery"

3. Not using minified version of jQuery library


The jQuery library (when you download) comes in two versions.

1. Production (Compressed Version)
2. Development (Uncompressed Version)

For development purpose, you can choose the development version of .js file as if you want to make some changes then that can be easily done. But ensure that when your software or product goes on production, always use the production version of .js file as its size is 5 times lesser than the development version. This can save some amount of bandwidth.

4. Not loading jQuery from Google CDN


Google is sea of free services. Do you know that Google is also hosting jQuery libraries on its CDN(Content delivery network) and allows any website to use it for free.

Why to use Google CDN?
  • Caching: The most important benefit is caching. If any previously visited site by user is using jQuery from Google CDN then the cached version will be used. It will not be downloaded again.
  • Reduce Load: It reduces the load on your web server as it downloads from Google server's.
  • Serves fast : You will be also benefitted from speed point of view. As Google has dozen's of different servers around the web and it will download the jQuery from whichever server is closer to the user. Google's CDN has a very low latency, it can serve a resource faster than your webserver can.
  • Parellel Downloading: As the js file is on a separate domain, modern browsers will download the script in parallel with scripts on your domain.

Read "Why to use Google hosted jQuery CDN"

5. Not loading jQuery locally when CDN fails


It is a good approach to always use CDN but sometimes what if the CDN is down (rare possibility though) but you never know in this world as anything can happen. So if you have loaded your jQuery from any CDN and it went down then your jQuery code will stop working and your client will start shouting.

I always recommend that write the code, if jQuery library is not loaded properly then it should use your local copy of jQuery.
1<script type="text/javascript"src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
2<script type="text/javascript">
3if (typeof jQuery == 'undefined')
4{
5  document.write(unescape("%3Cscript src='Scripts/jquery.1.9.0.min.js' type='text/javascript'%3E%3C/script%3E"));
6}
7</script>
It first loads the jQuery from Google CDN and then check the jQuery object. If jQuery is not loaded successfully then it will references the jQuery.js file from hard drive location. In this example, the jQuery.js is loaded from Scripts folder.

6. Not using selectors efficiently


Be smart while using selectors. As there are many ways to select element using selectors but that doesn't mean that all are equal. Always try to use ID and Element as selector as they are very fast. Even the class selectors are slower than ID selector.

When IDs are used as selector then jQuery internally makes a call to getElementById() method of Java script which directly maps to the element.

When Classes are used as selector then jQuery has to do DOM traversal.So when DOM traversal is performed via jQuery takes more time to select elements. In terms of speed and performance, it is best practice to use IDs as selector.

7. Using jQuery selectors repeatedly


Take a look at below jQuery code. The selectors are used thrice for 3 different operation.
1$("#myID").css("color""red");
2$("#myID").css("font""Arial");
3$("#myID").text("Error occurred!");
The problem with above code is, jQuery has to traverse 3 times as there are 3 different statements.But this can be combined into a single statement.
1$("#myID").css({ "color""red""font""Arial"}).text("Error occurred!"); 
This will ensure that jQuery traverse only once through DOM while selecting the element.

8. Not knowing how selectors are executed


Do you know how the selectors are executed? Your last selectors is always executed first. For example, in below jQuery code, jQuery will first find all the elements with class ".myCssClass" and after that it will reject all the other elements which are not in "p#elmID".
1$("p#elmID .myCssClass");

9. By not caching the stuff


Caching is an area which can give you awesome performance, if used properly and at the right place. While using jQuery, you should also think about caching. For example, if you are using any element in jQuery more than one time, then you must cache it. See below code.
1$("#myID").css("color""red");
2//Doing some other stuff......
3$("#myID").text("Error occurred!");
Now in above jQuery code, the element with #myID is used twice but without caching. So both the times jQuery had to traverse through DOM and get the element. But if you have saved this in a variable then you just need to reference the variable. So the better way would be,
1var $myElement = $("#myID").css("color""red");
2//Doing some other stuff......
3$myElement.text("Error occurred!");
So now in this case, jQuery won't need to traverse through the whole DOM tree when it is used second time. So in jQuery, Caching is like saving the jQuery selector in a variable. And using the variable reference when required instead of searching through DOM again.

10. Not checking while using various plugins


One of the great feature of jQuery is various plugins available created using jQuery are available for free. You like a jQuery plugin and start using it in your project. But while using plugins do you really consider,

  • File size
  • Performance of plugin
  • Browser Compatibility

Before using any plugin, always ensure that it must not hit performance of your page and it should not conflict with other plugins that you are using already.