Frontendplace Blog

Sharing Frontend developing ideas

  • Adds

a Blog for frontend Webdevelopers

This frontendplace aims to offer web development and 3D modelling tutorials, tips and tricks. Written by a web-developer and multimedia consultant who is passionate about web standards, webdevelopment and 3D visualisation.

Resizing font unobtrusive with jQuery and save in cookie

Posted by info on January 23rd, 2010

Do you need an unobtrusive font resizing component which also remember the settings in a cookie?
With jQuery i’ve created a little piece of html and javascript. This piece can simply be loaded in your html container by using the jquery function load().

This is an unobtrusive way to add this component to your website and only is available in your source when javascript is enabled. Here is the simple code I used to add the functionality:

$(function() {
//show resize buttons
$('.resizers').load('setFontSizeComponent.html');
});

Inside the inserted piece of html I placed this javascript code block:

	//load the font-size cookie if it exists and change body font
	var currentFontSize = $('html').css('font-size');
	var currentFontSizeNum = parseInt(currentFontSize, 10);
	$.originalFontSize = parseInt($.cookie('fontsize'),10) || currentFontSizeNum;
	$('html').css('font-size',$.originalFontSize + 'px');
	$('.font-label').text('Size: ' + $.originalFontSize);

	// Reset Font Size
	$('.bh_resetFont').click(function(event){
		event.preventDefault();
		fsCResizeText(0);
	});

	// Increase Font Size
	$('.bh_increaseFont').click(function(event){
		// prevent url
		event.preventDefault();
		fsCResizeText(1);
	});

	// Decrease Font Size
	$(".bh_decreaseFont").click(function(event){
		// prevent url
		event.preventDefault();
		fsCResizeText(-1);
	});

	/**
	* resize html base font size. when 0 value is passed the original fontsize on start of the page is reset
	* @addition{integer} number to increase the fontsize
	*/
	function fsCResizeText(addition) {
		var newFontSize;
		if (addition == 0) { // reset size
			newFontSize = $.originalFontSize;
		}
		else {
			var currentFontSize = $('html').css('font-size');
			var currentFontSizeNum = parseInt(currentFontSize, 10);
			// set fontsize between 8 and 20 px
			newFontSize = Math.max(8,Math.min(20,currentFontSizeNum+addition));
		}
		$('html').css('font-size', newFontSize);

		// Create (or update) the value of a cookie:
		$.cookie('fontsize', newFontSize);
		$('.font-label').text('Size: ' + newFontSize);
	}

You need the jquery library and the cooky plugin for jquery
Here you can find the simple example page
http://www.frontendplace.nl/bb/wp-content/uploads/2010/resizer/setpagesize.html

The separate component you can load here

Posted in Scripting | No Comments »

Conditional compilation does not combine well with javadoc

Posted by info on December 8th, 2009

It took me a while to debug errors in javascript and found out that I had two external javascript files and in one javascript file the programmer used /*@cc_on!@*/ notation ( conditional compilation that works in IE). and in the other file the programmer used javadoc notation @param inside the comments. When the file with javadoc notation is loaded before the one with conditional compilation inside comments it works fine. But when I switch the loading sequence I get javascript errors.. So removing the comments or using a different loading sequence helped with solving the error.

Posted in Scripting | No Comments »

nested floats

Posted by info on October 26th, 2009

When nesting a right floated box inside a left floated element. A right floating element will expand the containing left floating element to the width of the parent of the left floated element in IE6. According to W3C the left floating element should base its width on the width of the containing children.
In FF and SF (W3C) the total width will be the width of the containing children. A right floating element does not expand the left floating element to the width of the containing box of the left floated element.


Picture 11
FF

Picture 10 SF

Picture 12 IE

For testing purposes this example uses also attribute selectors.
IE6 ignores the attribute selector while Safari up till 4.0.3 ignores the :not() pseudo attribute syntax.
FF recognize both the [ attr ] and :not([attr]) syntax.
See
testattribute

Posted in Scripting | No Comments »

Multicolumn in firefox and safari

Posted by info on October 24th, 2009

For the developers who like to use the extra CSS draft 3 possibilities and don’t want to wait until internet explorer supports this. You can use the multi column properties :column-width, :column-gap and :column-rule. Coloring the selected text is an other example in draft3 css property
Example:
multicolumn

<style type="text/css">
div {
	column-width: 18em;
	column-gap: 2em;   /* shown in yellow */
	column-rule: 4px solid green;
	padding: 5px;      /* shown in blue */
	-moz-column-count:2;
	-moz-column-width:18em;
	-moz-column-gap:2em;
	-moz-column-rule: 4px solid green;
	-webkit-column-count:2;
	-webkit-column-width:18em;
	-webkit-column-gap:2em;
	-webkit-column-rule: 4px solid green;
}

/* draw any selected text yellow on red background */

::selection {color: gold; background: red;}
::-moz-selection {color: gold; background: red;}
::-webkit-selection { color: gold; background: red;}

/* draw selected text in a paragraph white on black */
p::-moz-selection { color: white; background: black;}
p::selection { color: white; background: black;}
p::-webkit-selection { color: white; background: black; }
</style>

Example: Multi column draft3

See for documentation:

http://www.w3.org/TR/css3-multicol/

https://developer.mozilla.org/en/CSS_Reference/Mozilla_Extensions#section_1

Posted in Scripting | No Comments »

Finding the default stylesheets

Posted by info on October 23rd, 2009

Sometimes you want to know what the default values are for properties of the styling of elements inside your browser: I don’t know yet were to find the default stylesheet for IE but for Firefox you can look in:

C:\Program Files\Mozilla Firefox\res or type resource://gre/res/ in your address bar. There you find the following stylesheets:

1. EditorOverride.css
2. forms.css
3. html.css
4. mathml.css
5. quirk.css
6. svg.css
7. ua.css
8. viewsource.css

For the setting of the current Safari you can look at: http://trac.webkit.org/browser/trunk/WebCore/css/html.css

Look for explanation of this stylesheet on:

http://developer.apple.com/mac/library/documentation/AppleApplications/Reference/SafariCSSRef/Introduction.html

For Opera you can look in the templates folder inside the package(on mac) or in the folder(on windows)

Posted in Scripting | No Comments »

Width error calculations in IE

Posted by info on October 19th, 2009

I have found an error in ie6 where the margin (left/right) gets calculated wrong when you put the table inside an other table and use a quirksmode doctype.

See doctypeerror ( add with developer toolbar a margin-left of 0.5% on one of the elements)

See doctypenoerror where you don’t get the error.

When using a quirksmode doctype ( none or half) the content gets a really absurd width when you apply a margin-width in percentage on an element inside a tablecell where the table itself is inside an other table. Here is the example and some screencaptures what I mean. 

Adding a margin-right  on a span inside a not nested table is correctly calculated
marketdata_016

Adding a margin on a span inside a nested table is correctly wrong and gets an absurd width (57276px).
marketdata_020

Posted in Scripting | No Comments »

Three ways for clearing floats

Posted by info on October 18th, 2009

For now I know three ways of clearing the floats:

  1. using extra markup after floating element with div element and style=”clear:both”
  2. using the :after syntax of a container with floating objects where you create a hidden content and clear the float using the syntax:
    .clearfix:after {
        content: ".";
        display: block;
        height: 0;
        clear: both;
        visibility: hidden;
    }

  3. using the overflow:auto on the container with a property that triggers “haslayout” mostly width:100% what is basically what you want when clearing both.

The last one is supposed to be used as the best option according to quirksmode: http://www.quirksmode.org/css/clearing.html.
I think that using the  three options can all have there benefits.. In development a container for floating elements is not always possible and then you have to resort to the clearer div. The overflow:auto is not always possible when un-wrappable content is inside the container and you get the scrollbars. So my opinion: use version 3 where possible and it is logical to combine the inner divs for grouping the elements. For creating a layout the clearer div can sometimes be of better help. The second one is depending on the IE bug where content will grow the box even if the box does have a smaller height and you need the extra zoom:1 or height:1px inside a conditional commented stylesheet.
So better use the third one whenever possible. see clearingfloats

Posted in Scripting | No Comments »

IE and FF calculating width

Posted by info on October 18th, 2009

Be aware that firefox calculates the width of percentage in reals and rounds the result to 3 digits after the comma while IE and safari calculates results in integer.

In IE the calculations get really stuck if you have different paddings on the tablecells. In SF and FF if one cell of a row or column (depending of left/right or bottom/top padding) has a padding than every cell in that row or column gets the same top/bottom padding.. In IE that is not the case depending of the rounded calculation a cell can have a padding and the other cell does not. Sometime two cells in the same column can have different widths so you get a broken column line when using borders on cells.

Also because IE and SF rounds the results (45.5 will result in 45 instead of 46 ) there can be a difference in total pixels when rounding the result. When using two complementary widths in percentages than the result can be more or less than 100%. But the rounding will be different for all calculations so if you have a width of 74.5% of an element or have a width of 74% and a 0.5% margin-left than you get twice the rounded result and the total can have a bigger total width. Like in this table width comparison example .

I have also seen in IE6 that using a percentage of 0.5% margin results in a huge sized margin.. don’t know yet why.. by removing the 0.5 margin the span got its right size back again.

IE6resizing
testtable

Posted in Scripting | No Comments »

Optimization checklist

Posted by info on October 18th, 2009

Here is a checklist I use for optimizing a website:

Optimization checklist:

  • optimize markup
    • use external stylesheets
    • use external javascript
    • specify doctype strict (renders quicker)
    • minimize http requests (example: create image sprites (group images for hover effects together inside one image))
    • consolidate markup
    • structural markup
    • avoid tables for presentation
    • remove excess whitespace (space, tabs, returns)
    • minimize comments ( no “———”)
    • avoid redundant elements and attributes
      • <div class=”a”><ul class=”b”><li class=”c”><span class=”d”><span class=”e”><a class=”f”>
    • include height and width and alt text when using images
    • minimize url
      • use relative for internal use where possible
      • streamline links.. remove directory default filename
      • remove www when possible
    • ensure template markup is semantic, structural, and valid
  • optimize CSS
    • minimize css comments
    • use separate stylesheet for maintenance and different media
    • remove redundant whitespace
    • group selectors with same declaration
    • use shorthand notation
      • shorthand selectors
        • font: weight style variant size/line-height family
        • background: color image repeat attachment position
        • margin | padding | border-style/width/color: top right bottom left
        • border | border-top/right/bottom/left: width style color
        • list-style:type position image
      • shorthand color values (#FF0 instead of yellow or #FFFF00)
    • shorten id and classNames
    • use highest level parent where possible using inheritance
    • assign multiple css classes to a single element example <span>
    • validate css
  • optimize javascript
    • use JS to enhance rather than to create user experience
      • use css’s hover possibility where possible
    • separate files to javascript objects or libraries
    • use defer for IE where no markup is produced by javascript to load after the content
    • encapsulate code into functions
      • window.onload = init()
    • load externals conditionally where possible
    • rework code to make it simpler
    • group functions in objects – prevent creating unnecessary variables
    • prevent recalculations
  • optimize server
    • include trailing slashes on the urls
    • use html compression (gzip)
    • optimize images, multimedia, alternative format files
    • for larger images provide thumbnail versions
    • use html for caption inside pictures
    • remove obsolete files like images

Posted in Scripting | No Comments »

Truncate text with ellipsis example with xslt

Posted by info on August 2nd, 2009

This is an example I made for truncating text of an introduction text to a specified amount of characters. A new node variable is created and this node can be processed with the general xslt that processes the individual nodes inside this new created node.

see also http://p2p.wrox.com/xslt/75076-truncate-text-including-tags.html

Description:
        This template truncates the text of the introductie node until a maximum characters are reached. When the text is truncated
        an ellipsis is added to the truncated text. When the text is smaller than the maximum no ellipsis is added
        at the end of the introductie text a link will be added
       
        Parameters:
        * limit (optional) number of characters to limit by. Default 250 characters
        * suffix (optional) the suffix character string to use when the text is truncated. Default ‘…’
        * url (compulsary) the url on the ‘more’ link
        Example:
        <xsl:apply-templates select=”path/to/your/introductie” mode=”truncate”/>

<xsl:template match=“art:introductie” mode=“truncateTree”>
       
<xsl:param name=“limit” select=“250″/>
       
<xsl:param name=“suffix” select=“‘…’”/>
       
<xsl:param name=“url”/>
       
       
<!– copy introduction node to redesign the content and later process this copy–>
       
<xsl:variable name=“truncatedNode”>
           
<xsl:copy-of select=“*”/>
       
</xsl:variable>
       

       
<!– create new truncated node –>
       
<xsl:variable name=“truncatedNodeTree”>
           
<xsl:apply-templates mode=“truncate” select=“$truncatedNode/*”>
               
<xsl:with-param name=“limit” select=“$limit”/>
               
<xsl:with-param name=“suffix” select=“$suffix”/>
               
<xsl:with-param name=“url” select=“$url”/>
           
</xsl:apply-templates>
           
       
</xsl:variable>
       
       
<!–process new created truncated introduction tree with the general xslt–>
       
<xsl:apply-templates select=“$truncatedNodeTree/*”/>
       
   
</xsl:template>
   
   
<!– process each node –>
   
<xsl:template match=“*” mode=“truncate”>
       
<xsl:param name=“limit”/>
       
<xsl:param name=“suffix”/>
       
<xsl:param name=“url”/>
      
       
<xsl:variable name=“preceding-strings”>
           
<xsl:copy-of select=“preceding::text()”/>
       
</xsl:variable>
       
       
<!– precedingchar: number of characters up to the current node –>
       
<xsl:variable name=“precedingchar” select=“string-length(normalize-space($preceding-strings))”/>
       
       
<xsl:if test=“$precedingchar &lt; $limit”>
           
<xsl:element name=“{name()}”>
               
<xsl:copy-of select=“@*”/>
               
<xsl:apply-templates mode=“truncate”>
                   
<xsl:with-param name=“limit” select=“$limit”/>
                   
<xsl:with-param name=“suffix” select=“$suffix”/>
               
</xsl:apply-templates>
               
<!– only add link at end of first element this is the first node inside introductie–>
               
<xsl:if test=“position()=1″>
                   
<xsl:text> </xsl:text><link class=“actionLink” xlink:href=“{$url}” xlink:title=“More”>More</link>
               
</xsl:if>
           
</xsl:element>
       
</xsl:if>
   
</xsl:template>
   
   
<!– process each text node –>
   
<xsl:template match=“text()” mode=“truncate”>
       
<xsl:param name=“limit”/>
       
<xsl:param name=“suffix”/>
       
<xsl:variable name=“preceding-strings”>
           
<xsl:copy-of select=“preceding::text()”/>
       
</xsl:variable>
       
       
<!– precedingchar: number of characters up to the current node –>
       
<xsl:variable name=“precedingchar” select=“string-length(normalize-space($preceding-strings))”/>
       
       
<xsl:if test=“$precedingchar &lt; $limit”>
          
<!– totalchar: number of characters including current node –>
          
<xsl:variable name=“totalchar” select=“$precedingchar + string-length(.)”/>
          
          
<xsl:choose>
              
<xsl:when test=“$totalchar &gt; $limit “>
                  
<!– truncate until limit reached –>
                  
<xsl:value-of select=“substring(., 1, ($limit – $precedingchar))”/>
                  
<xsl:value-of select=“$suffix”/>
                  
<xsl:text> </xsl:text>
              
</xsl:when>
              
<xsl:otherwise>
                  
<!– dont have to truncate text –>
                  
<xsl:value-of select=“.”/>
              
</xsl:otherwise>
          
</xsl:choose>
       
</xsl:if>
       
   
</xsl:template> 

Posted in Scripting | 1 Comment »