<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>DOM &#8211; stoimen&#039;s web log</title>
	<atom:link href="/tag/dom/feed/" rel="self" type="application/rss+xml" />
	<link></link>
	<description>on web development</description>
	<lastBuildDate>Tue, 13 Feb 2018 08:18:15 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>https://wordpress.org/?v=5.0.3</generator>
	<item>
		<title>Computer Algorithms: Finding the Lowest Common Ancestor</title>
		<link>/2012/08/24/computer-algorithms-finding-the-lowest-common-ancestor/</link>
		<comments>/2012/08/24/computer-algorithms-finding-the-lowest-common-ancestor/#comments</comments>
		<pubDate>Fri, 24 Aug 2012 12:54:54 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[data structures]]></category>
		<category><![CDATA[B-tree]]></category>
		<category><![CDATA[Binary search tree]]></category>
		<category><![CDATA[binary search trees]]></category>
		<category><![CDATA[Binary trees]]></category>
		<category><![CDATA[DOM]]></category>
		<category><![CDATA[Graph theory]]></category>
		<category><![CDATA[html]]></category>
		<category><![CDATA[Lowest common ancestor]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[proper solution]]></category>
		<category><![CDATA[Rope]]></category>
		<category><![CDATA[Ternary tree]]></category>
		<category><![CDATA[Tree]]></category>
		<category><![CDATA[two algorithms]]></category>

		<guid isPermaLink="false">/?p=3314</guid>
		<description><![CDATA[Introduction Here’s one task related to the tree data structure. Given two nodes, can you find their lowest common ancestor? In a matter of fact this task always has a proper solution, because at least the root node is a common ancestor of all pairs of nodes. However here the task is to find the &#8230; <a href="/2012/08/24/computer-algorithms-finding-the-lowest-common-ancestor/" class="more-link">Continue reading <span class="screen-reader-text">Computer Algorithms: Finding the Lowest Common Ancestor</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2012/07/03/computer-algorithms-balancing-a-binary-search-tree/" rel="bookmark" title="Computer Algorithms: Balancing a Binary Search Tree">Computer Algorithms: Balancing a Binary Search Tree </a></li>
<li><a href="/2012/06/22/computer-algorithms-binary-search-tree-data-structure/" rel="bookmark" title="Computer Algorithms: Binary Search Tree">Computer Algorithms: Binary Search Tree </a></li>
<li><a href="/2012/08/07/computer-algorithms-heap-and-heapsort-data-structure/" rel="bookmark" title="Computer Algorithms: Heap and Heapsort">Computer Algorithms: Heap and Heapsort </a></li>
<li><a href="/2010/09/29/construct-a-sorted-php-linked-list/" rel="bookmark" title="Construct a Sorted PHP Linked List">Construct a Sorted PHP Linked List </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>Introduction</h2>
<p>Here’s one task related to the tree data structure. Given two nodes, can you find their lowest common ancestor? </p>
<p>In a matter of fact this task always has a proper solution, because at least the root node is a common ancestor of all pairs of nodes. However here the task is to find the lowest one, which can be quite far from the root. </p>
<figure id="attachment_3315" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/08/1.-Finding-the-Lowest-Common-Ancestor.png"><img src="/wp-content/uploads/2012/08/1.-Finding-the-Lowest-Common-Ancestor.png" alt="Finding the Lowest Common Ancestor" title="Finding the Lowest Common Ancestor" width="620" height="362" class="size-full wp-image-3315" srcset="/wp-content/uploads/2012/08/1.-Finding-the-Lowest-Common-Ancestor.png 620w, /wp-content/uploads/2012/08/1.-Finding-the-Lowest-Common-Ancestor-300x175.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">Finding the Lowest Common Ancestor</figcaption></figure>
<p>We don’t care what kind of trees we have. However the solution, as we will see, can be very different depending on the tree type. Indeed finding the lowest common ancestor can have linear complexity for binary search trees, which isn’t true for ordinary trees.<span id="more-3314"></span></p>
<h2>Overview</h2>
<p>Let’s say we have a tree (not binary!) and two nodes from this tree. The task is to find their lowest common ancestor. The thing is that we don’t know much about where they appear to be in the tree. </p>
<p>We can think of this tree as a DOM tree of any single HTML page online. It is not binary or balanced and can’t be sure where these nodes are. </p>
<figure id="attachment_3317" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/08/2.-Lowest-Common-Ancestor.png"><img src="/wp-content/uploads/2012/08/2.-Lowest-Common-Ancestor.png" alt="Lowest Common Ancestor" title="Lowest Common Ancestor" width="620" height="399" class="size-full wp-image-3317" srcset="/wp-content/uploads/2012/08/2.-Lowest-Common-Ancestor.png 620w, /wp-content/uploads/2012/08/2.-Lowest-Common-Ancestor-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">&nbsp;</figcaption></figure>
<p>First we must find both paths from the root to each one of the target nodes. Note that this requires additional memory! Then, in linear time we can pass through these “paths” and scan them from the root down to the nodes. We expect these to arrays to be equal at least in their first element (the root).  Using this scenario the lowest common ancestor is the last equal element in both arrays. </p>
<figure id="attachment_3318" style="width: 621px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/08/3.-Lowest-Common-Ancestor.png"><img src="/wp-content/uploads/2012/08/3.-Lowest-Common-Ancestor.png" alt="Lowest Common Ancestor Paths" title="Lowest Common Ancestor Paths" width="621" height="338" class="size-full wp-image-3318" srcset="/wp-content/uploads/2012/08/3.-Lowest-Common-Ancestor.png 621w, /wp-content/uploads/2012/08/3.-Lowest-Common-Ancestor-300x163.png 300w" sizes="(max-width: 621px) 100vw, 621px" /></a><figcaption class="wp-caption-text">Once we know the paths from the root down to the nodes, we can compare them in order to find the lowest common ancestor!</figcaption></figure>
<p>To see how this algorithm can be dramatically changed depending on the data structure, let’s see another example. Now let’s say we have a binary search tree (BST). We know that in a BST all the elements in the left sub-tree are smaller than the root and all the items on the right sub-tree are greater than the root. This is true also for the left and the right sub-trees.</p>
<p>Now because we’re searching the lowest common ancestor, we don’t need to collect the paths from the root to the nodes in two arrays. We just know that the greater items are on the right, while the smaller items are on the left. This can help us find the lowest ancestor starting directly from the root.</p>
<figure id="attachment_3319" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/08/4.-Lowest-Common-in-a-BST.png"><img src="/wp-content/uploads/2012/08/4.-Lowest-Common-in-a-BST.png" alt="Lowest Common in a BST" title="Lowest Common in a BST" width="620" height="399" class="size-full wp-image-3319" srcset="/wp-content/uploads/2012/08/4.-Lowest-Common-in-a-BST.png 620w, /wp-content/uploads/2012/08/4.-Lowest-Common-in-a-BST-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">In a BST we compare both values with a given node (starting from the root). In case the node&#8217;s value is in between them &#8211; this is the lowest common ancestor. If not &#8211; we go either on the left or on the right!</figcaption></figure>
<p>What we do is to compare the two keys of the target nodes with the root key. If one of the keys are smaller, and the other is greater than the root&#8217;s key, then obviously the root is the lowest common ancestor. This is true because one of the items will be somewhere in the left sub-tree, while the other will be in the right sub-tree. </p>
<p>In case both values are greater (or smaller) than the root, we can move to the right (or to the left) sub-tree and try again with the same procedure. Thus the first node which key is in between the two target values will be the lowest common ancestor.</p>
<h2>Code</h2>
<p>Here’s a very simple PHP implementation showing us these two algorithms.</p>
<pre lang="PHP">
class Tree
{
    public $node = null;
    public $id = null;
    public $parent = null;
    public $children = array();
    
    public function __construct($node, $id = null)
    {
        $this->node = $node;
        $this->id = $id;
    }
    
    public function addChild(Node &$n)
    {
        $n->parent = $this;
        $this->children[] = $n;
    }
    
    /**
     * Returns an element by its id
     * 
     * @param mixed $id
     * @return Node 
     */
    public function search($id)
    {
        if ($this->id == $id) {
            return $this;
        }

        $a = false;
        
        // search all the children starting from the left-most
        foreach ($this->children as $child) {
            $a = $child->search($id);
        }
        
        return $a;
    }
    
    /**
     * Finds a path from the root to the 
     * item and returns it as a list
     * 
     * @param mixed $id 
     * @return array
     */
    public function find_path($id, &$path)
    {
        array_push($path, $this->id);
        
        if ($this->id == $id) {
            return 1;
        }
        
        foreach ($this->children as $child)  {
            if (1 == $child->find_path($id, $path)) return 1;
            array_pop($path);
        }
    }
    
    public function __toString()
    {
        return $this->node . ' ' . $this->id . "\n";
    }
}

$dom = new Tree('DOM', 'ROOT');

$body = new Tree('BODY', 1);
$div1 = new Tree('DIV', 'div-1');
$div2 = new Tree('DIV', 'my-id');

$a = new Tree("A", 'some-link');

$dom->addChild($body);
$body->addChild($div1);
$body->addChild($div2);
$div2->addChild($a);

$path1 = $path2 = array();
$dom->find_path('div-1', $path1);
$dom->find_path('some-link', $path2);
</pre>
<h3>Finding Lowest Common Ancestor in a BST</h3>
<pre lang="PHP">
class Tree
{
    public $key;
    
    public $parent  = null;
    public $left    = null;
    public $right   = null;
    
    public function __construct($key) 
    {
        $this->key = $key;
    }
    
    public function insert(Tree $n) 
    {
        if ($this->key < $n->key) {
            if ($this->right == null) {
                // insert
                $this->right = $n;
                $n->parent = $this;
            } else {
                $this->right->insert($n);
            }
        }
        if ($this->key > $n->key) {
            if ($this->left == null) {
                // insert
                $this->left = $n;
                $n->parent = $this;
            } else {
                $this->left->insert($n);
            }
        }
    }
}

$t = new Tree(10);

$n1 = new Tree(20);
$n2 = new Tree(5);
$n3 = new Tree(7);
$n4 = new Tree(13);

$t->insert($n1);
$t->insert($n2);
$t->insert($n3);

function find_common($node1, $node2, $tree) 
{
    if ($node1->key < $tree->key && $node2->key > $tree->key) {
        return $tree;
    } else if ($node1->key < $tree->key && $node2->key < $tree->key) {
        find_common($node1, $node2, $tree->left);
    } else if ($node1->key > $tree->key && $node2->key > $tree->key) {
        find_common($node1, $node2, $tree->right);
    }
}

$node = find_common($n3, $n4, $t);
</pre>
<h2>Application</h2>
<p>A typical use-case of this algorithm is finding the lowest common ancestor of two nodes in a DOM tree. Sometimes we just need to attach an event listener to both items (even before they are attached to the DOM!). Although attaching this event to the “document” will work just fine, all the elements from the nodes up to the root will be “capturing” these events due to event bubbling. Thus attaching the event to the lowest common ancestor is a better solution.</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2012/07/03/computer-algorithms-balancing-a-binary-search-tree/" rel="bookmark" title="Computer Algorithms: Balancing a Binary Search Tree">Computer Algorithms: Balancing a Binary Search Tree </a></li>
<li><a href="/2012/06/22/computer-algorithms-binary-search-tree-data-structure/" rel="bookmark" title="Computer Algorithms: Binary Search Tree">Computer Algorithms: Binary Search Tree </a></li>
<li><a href="/2012/08/07/computer-algorithms-heap-and-heapsort-data-structure/" rel="bookmark" title="Computer Algorithms: Heap and Heapsort">Computer Algorithms: Heap and Heapsort </a></li>
<li><a href="/2010/09/29/construct-a-sorted-php-linked-list/" rel="bookmark" title="Construct a Sorted PHP Linked List">Construct a Sorted PHP Linked List </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2012/08/24/computer-algorithms-finding-the-lowest-common-ancestor/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Computer Algorithms: Bubble Sort</title>
		<link>/2012/02/20/computer-algorithms-bubble-sort/</link>
		<comments>/2012/02/20/computer-algorithms-bubble-sort/#comments</comments>
		<pubDate>Mon, 20 Feb 2012 13:33:08 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[Bubble sort]]></category>
		<category><![CDATA[Discrete mathematics]]></category>
		<category><![CDATA[DOM]]></category>
		<category><![CDATA[famous sorting algorithm]]></category>
		<category><![CDATA[Heapsort]]></category>
		<category><![CDATA[ineffective algorithm]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[Merge sort]]></category>
		<category><![CDATA[Order theory]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Quicksort]]></category>
		<category><![CDATA[Selection sort]]></category>
		<category><![CDATA[slow ineffective algorithm]]></category>
		<category><![CDATA[Sort]]></category>
		<category><![CDATA[Sorting]]></category>
		<category><![CDATA[Sorting algorithms]]></category>
		<category><![CDATA[well known sorting algorithm]]></category>

		<guid isPermaLink="false">/?p=2729</guid>
		<description><![CDATA[Overview It&#8217;s weird that bubble sort is the most famous sorting algorithm in practice since it is one of the worst approaches for data sorting. Why is bubble sort so famous? Perhaps because of its exotic name or because it is so easy to implement. First let&#8217;s take a look on its nature. Bubble sort &#8230; <a href="/2012/02/20/computer-algorithms-bubble-sort/" class="more-link">Continue reading <span class="screen-reader-text">Computer Algorithms: Bubble Sort</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2010/07/09/friday-algorithms-javascript-bubble-sort/" rel="bookmark" title="Friday Algorithms: JavaScript Bubble Sort">Friday Algorithms: JavaScript Bubble Sort </a></li>
<li><a href="/2012/02/27/computer-algorithms-shell-sort/" rel="bookmark" title="Computer Algorithms: Shell Sort">Computer Algorithms: Shell Sort </a></li>
<li><a href="/2012/02/13/computer-algorithms-insertion-sort/" rel="bookmark" title="Computer Algorithms: Insertion Sort">Computer Algorithms: Insertion Sort </a></li>
<li><a href="/2012/03/19/computer-algorithms-radix-sort/" rel="bookmark" title="Computer Algorithms: Radix Sort">Computer Algorithms: Radix Sort </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>Overview</h2>
<p>It&#8217;s weird that bubble sort is the most famous sorting algorithm in practice since it is one of the worst approaches for data sorting. Why is bubble sort so famous? Perhaps because of its exotic name or because it is so easy to implement. First let&#8217;s take a look on its nature.</p>
<p>Bubble sort consists of comparing each pair of adjacent items. Then one of those two items is considered smaller (lighter) and if the lighter element is on the right side of its neighbour, they swap places. Thus the lightest element bubbles to the surface and at the end of each iteration it appears on the top. I&#8217;ll try to explain this simple principle with some pictures.</p>
<h3>1. Each two adjacent elements are compared</h3>
<figure id="attachment_2736" style="width: 962px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/02/BubbleSortStep1CompareTwoElements1.png"><img src="/wp-content/uploads/2012/02/BubbleSortStep1CompareTwoElements1.png" alt="In bubble sort we've to compare each two adjacent elements" title="BubbleSortStep1CompareTwoElements" width="962" height="250" class="size-full wp-image-2736" srcset="/wp-content/uploads/2012/02/BubbleSortStep1CompareTwoElements1.png 962w, /wp-content/uploads/2012/02/BubbleSortStep1CompareTwoElements1-300x77.png 300w" sizes="(max-width: 962px) 100vw, 962px" /></a><figcaption class="wp-caption-text">In bubble sort we've to compare each two adjacent elements</figcaption></figure>
<p>Here &#8220;2&#8221; appears to be less than &#8220;4&#8221;, so it is considered lighter and it continues to bubble to the surface (the front of the array).<br />
<span id="more-2729"></span></p>
<h3>2. Swap with heavier elements</h3>
<figure id="attachment_2738" style="width: 962px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/02/BubbleSortStep2AnElementStartstoBubble.png"><img src="/wp-content/uploads/2012/02/BubbleSortStep2AnElementStartstoBubble.png" alt="If heavier elements appear on the way we should swap them" title="BubbleSortStep2AnElementStartstoBubble" width="962" height="241" class="size-full wp-image-2738" srcset="/wp-content/uploads/2012/02/BubbleSortStep2AnElementStartstoBubble.png 962w, /wp-content/uploads/2012/02/BubbleSortStep2AnElementStartstoBubble-300x75.png 300w" sizes="(max-width: 962px) 100vw, 962px" /></a><figcaption class="wp-caption-text">If heavier elements appear on the way we should swap them</figcaption></figure>
<p>On his way to the surface the currently lightest item meets a heavier element. Then they swap places.</p>
<h3>3. Move forward and swap with each heavier item</h3>
<figure id="attachment_2740" style="width: 963px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/02/BubbleSortStep3ALighterElementStartstoBubble.png"><img src="/wp-content/uploads/2012/02/BubbleSortStep3ALighterElementStartstoBubble.png" alt="Swapping is slow and that is the main reason not to use bubble sort" title="BubbleSortStep3ALighterElementStartstoBubble" width="963" height="377" class="size-full wp-image-2740" srcset="/wp-content/uploads/2012/02/BubbleSortStep3ALighterElementStartstoBubble.png 963w, /wp-content/uploads/2012/02/BubbleSortStep3ALighterElementStartstoBubble-300x117.png 300w" sizes="(max-width: 963px) 100vw, 963px" /></a><figcaption class="wp-caption-text">Swapping is slow and that is the main reason not to use bubble sort</figcaption></figure>
<p>The problem with bubble sort is that you may have to swap a lot of elements.</p>
<h3>4. If there is a lighter element, then this item begins to bubble to the surface</h3>
<figure id="attachment_2741" style="width: 959px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/02/BubbleSortStep4ALighterElementStartstoBubble.png"><img src="/wp-content/uploads/2012/02/BubbleSortStep4ALighterElementStartstoBubble.png" alt="We can be sure that on each step the algorithm bubbles the lightest element so far" title="BubbleSortStep4ALighterElementStartstoBubble" width="959" height="180" class="size-full wp-image-2741" srcset="/wp-content/uploads/2012/02/BubbleSortStep4ALighterElementStartstoBubble.png 959w, /wp-content/uploads/2012/02/BubbleSortStep4ALighterElementStartstoBubble-300x56.png 300w" sizes="(max-width: 959px) 100vw, 959px" /></a><figcaption class="wp-caption-text">We can be sure that on each step the algorithm bubbles the lightest element so far</figcaption></figure>
<p>If the currently lightest element meets another item that is lighter, then the newest currently lightest element starts to bubble to the top.</p>
<h3>5. Finally the lightest element is on its place</h3>
<figure id="attachment_2742" style="width: 959px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/02/BubbleSortStep5Themostlightelementisonitsplace.png"><img src="/wp-content/uploads/2012/02/BubbleSortStep5Themostlightelementisonitsplace.png" alt="Finally the list begins to look sorted" title="BubbleSortStep5Themostlightelementisonitsplace" width="959" height="180" class="size-full wp-image-2742" srcset="/wp-content/uploads/2012/02/BubbleSortStep5Themostlightelementisonitsplace.png 959w, /wp-content/uploads/2012/02/BubbleSortStep5Themostlightelementisonitsplace-300x56.png 300w" sizes="(max-width: 959px) 100vw, 959px" /></a><figcaption class="wp-caption-text">Finally the list begins to look sorted</figcaption></figure>
<p>At the end of each iteration we can be sure that the lightest element is on the right place &#8211; at the beginning of the list.</p>
<p>The problem is that this algorithm needs a tremendous number of comaprisons and as we know already this can be slow.</p>
<p><iframe src="https://docs.google.com/present/embed?id=dc7ft52d_9cgbm35fh&#038;autoStart=true&#038;loop=true&#038;size=m" frameborder="0" width="525" height="420"></iframe></p>
<p>We can easily see how ineffective bubble sort is. Now the question remains &#8211; why is it so famous? Maybe indeed the answer lies in the simplicity of its implementation. Let&#8217;s see how to implement bubble sort.</p>
<h2>Implementation</h2>
<p>Implementing bubble sort is easy. The question is how easy? Well, obviously after understanding the principles of this algorithm every developer, even a beginner, can implement it. Here&#8217;s a PHP implementation of bubble sort.</p>
<pre lang="PHP">
$input = array(6, 5, 3, 1, 8, 7, 2, 4);

function bubble_sort($arr)
{
	$length = count($arr);
	
	for ($i = 0; $i < $length; $i++) {
		for ($j = $length-1; $j > $i; $j--) {
			if ($arr[$j] < $arr[$j-1]) {
				$t = $arr[$j];
				$arr[$j] = $arr[$j-1];
				$arr[$j-1] = $t;
			}
		}
	}
	
	return $arr;
}

// 1, 2, 3, 4, 5, 6, 7, 8
$output = bubble_sort($input);
</pre>
<p>Clearly the implementation consists of few lines of code and two nested loops.</p>
<h2>Complexity: Where's Bubble Sort Compared to Other Sorting Algorithms</h2>
<p>Compared to other sorting algorithm, bubble sort is really slow. Indeed the complexity of this algoritm is O(n<sup>2</sup>) which can't be worse. It's weird that the most well known sorting algorithm is the slowest one.</p>
<figure id="attachment_2758" style="width: 600px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/02/BubbleSortComparedToOthers.png"><img src="/wp-content/uploads/2012/02/BubbleSortComparedToOthers.png" alt="Bubble sort compared to quicksort, merge sort and heapsort in the average case" title="BubbleSortComparedToOthers" width="600" height="371" class="size-full wp-image-2758" srcset="/wp-content/uploads/2012/02/BubbleSortComparedToOthers.png 600w, /wp-content/uploads/2012/02/BubbleSortComparedToOthers-300x185.png 300w" sizes="(max-width: 600px) 100vw, 600px" /></a><figcaption class="wp-caption-text">Bubble sort compared to quicksort, merge sort and heapsort in the average case</figcaption></figure>
<p>Even for small values of n, the number of comparisons and swaps can be tremendous.</p>
<figure id="attachment_2751" style="width: 1082px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/02/BubbleSortStats-2.png"><img src="/wp-content/uploads/2012/02/BubbleSortStats-2.png" alt="stats" title="Bubble sort is three times slower than quicksort even for n = 100, but it's easier to impelemnt" width="1082" height="654" class="size-full wp-image-2751" srcset="/wp-content/uploads/2012/02/BubbleSortStats-2.png 1082w, /wp-content/uploads/2012/02/BubbleSortStats-2-300x181.png 300w, /wp-content/uploads/2012/02/BubbleSortStats-2-1024x618.png 1024w" sizes="(max-width: 1082px) 100vw, 1082px" /></a><figcaption class="wp-caption-text">Bubble sort is three times slower than quicksort even for n = 100, but it's easier to impelemnt</figcaption></figure>
<p>Another problem is that most of the languages (libraries) have built-in sorting functions, that they don't make use of bubble sort and are faster for sure. So why a developer should implement bubble sort at all?</p>
<h2>Application: 3 Cool Reasons To Use Bubble Sort</h2>
<p>We saw that bubble sort is slow and ineffective, yet it is used in practice. Why? Is there any reason to use this slow, ineffective algorithm with weird name? Yes and here are some of them that might be helpful for any developer.</p>
<h3>1. It is easy to implement</h3>
<p>Definitely bubble sort is easier to implement than other "complex" sorting algorithms as quicksort. Bubble sort is easy to remember and easy to code and that's great instead of learning and remembering tons of code.</p>
<h3>2. Because the library can't help</h3>
<p>Let's say you work with JavaScript. Great, there you get array.sort() which can help for this: [3, 1, 2].sort(). But what would happen if you'd rather like to sort more "complex" structures like ... some DOM nodes. Here we have three LI nodes and we want to sort them in some order. Obviously you can't compare them with the "<" operator, so we've to come up with some custom solution.



<pre lang="html4strict">
<a href="#">Click here to sort the list</a>

<li>node 3</li>
<li>node 1</li>
<li>node 2</li>
</pre>
<p>Here sort() can&#8217;t help us and we&#8217;ve to code our own function. However we have only few elements (three in our case). Why not using bubble sort?</p>
<h3>3. The list is almost sorted</h3>
<p>One of the problems with bubble sort is that it consists of too much swapping, but what if we know that the list is almost sorted?  </p>
<pre lang="javascript">
// almost sorted
[1, 2, 4, 3, 5]
</pre>
<p>We have to swap only 3 with 4. </p>
<p>Note that in the best case bubble sort&#8217;s complexity is O(n) &#8211; faster than quicksort&#8217;s best case!</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2010/07/09/friday-algorithms-javascript-bubble-sort/" rel="bookmark" title="Friday Algorithms: JavaScript Bubble Sort">Friday Algorithms: JavaScript Bubble Sort </a></li>
<li><a href="/2012/02/27/computer-algorithms-shell-sort/" rel="bookmark" title="Computer Algorithms: Shell Sort">Computer Algorithms: Shell Sort </a></li>
<li><a href="/2012/02/13/computer-algorithms-insertion-sort/" rel="bookmark" title="Computer Algorithms: Insertion Sort">Computer Algorithms: Insertion Sort </a></li>
<li><a href="/2012/03/19/computer-algorithms-radix-sort/" rel="bookmark" title="Computer Algorithms: Radix Sort">Computer Algorithms: Radix Sort </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2012/02/20/computer-algorithms-bubble-sort/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>jQuery: Setting Up a Vector Path Fill Color</title>
		<link>/2010/09/27/jquery-setting-up-a-vector-path-fill-color/</link>
		<comments>/2010/09/27/jquery-setting-up-a-vector-path-fill-color/#respond</comments>
		<pubDate>Mon, 27 Sep 2010 17:37:24 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[micro tutorial]]></category>
		<category><![CDATA[Attribute]]></category>
		<category><![CDATA[Computer file formats]]></category>
		<category><![CDATA[Computing]]></category>
		<category><![CDATA[DOM]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[Markup languages]]></category>
		<category><![CDATA[Open formats]]></category>
		<category><![CDATA[path]]></category>
		<category><![CDATA[Scalable Vector Graphics]]></category>
		<category><![CDATA[svg]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[vector path]]></category>

		<guid isPermaLink="false">/?p=1997</guid>
		<description><![CDATA[It&#8217;s quite unusual to think of the jQuery&#8217;s attr() method as a generic method that can only change basic attributes as value, style, etc. However attr() can change whatever DOM element attribute. In this case you may know that the SVG path element can have a fill attribute, so you can simply setup a: $('path').attr('fill', &#8230; <a href="/2010/09/27/jquery-setting-up-a-vector-path-fill-color/" class="more-link">Continue reading <span class="screen-reader-text">jQuery: Setting Up a Vector Path Fill Color</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2010/09/13/looping-animation-with-javascript-and-raphael/" rel="bookmark" title="Looping Animation with JavaScript and Raphaël">Looping Animation with JavaScript and Raphaël </a></li>
<li><a href="/2010/04/06/jquery-what-about-this-title/" rel="bookmark" title="jQuery: what about this.title?">jQuery: what about this.title? </a></li>
<li><a href="/2010/03/31/jquery-get-the-id-of-the-current-element/" rel="bookmark" title="jQuery Get the Id of the Current Element">jQuery Get the Id of the Current Element </a></li>
<li><a href="/2010/06/22/jquery-get-the-selected-option-text/" rel="bookmark" title="jQuery: Get the Selected Option Text">jQuery: Get the Selected Option Text </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<p>It&#8217;s quite unusual to think of the jQuery&#8217;s attr() method as a generic method that can only change basic attributes as value, style, etc. However attr() can change whatever DOM element attribute. In this case you may know that the SVG path element can have a fill attribute, so you can simply setup a:</p>
<pre lang="javascript">
$('path').attr('fill', '#ccc');
</pre>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2010/09/13/looping-animation-with-javascript-and-raphael/" rel="bookmark" title="Looping Animation with JavaScript and Raphaël">Looping Animation with JavaScript and Raphaël </a></li>
<li><a href="/2010/04/06/jquery-what-about-this-title/" rel="bookmark" title="jQuery: what about this.title?">jQuery: what about this.title? </a></li>
<li><a href="/2010/03/31/jquery-get-the-id-of-the-current-element/" rel="bookmark" title="jQuery Get the Id of the Current Element">jQuery Get the Id of the Current Element </a></li>
<li><a href="/2010/06/22/jquery-get-the-selected-option-text/" rel="bookmark" title="jQuery: Get the Selected Option Text">jQuery: Get the Selected Option Text </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2010/09/27/jquery-setting-up-a-vector-path-fill-color/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>2xjQuery: Select a Selector</title>
		<link>/2010/09/24/2xjquery-select-a-selector/</link>
		<comments>/2010/09/24/2xjquery-select-a-selector/#comments</comments>
		<pubDate>Fri, 24 Sep 2010 08:23:58 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[javascript]]></category>
		<category><![CDATA[micro tutorial]]></category>
		<category><![CDATA[ajax]]></category>
		<category><![CDATA[Comparison of JavaScript frameworks]]></category>
		<category><![CDATA[Computing]]></category>
		<category><![CDATA[DOM]]></category>
		<category><![CDATA[Ext]]></category>
		<category><![CDATA[how-to]]></category>
		<category><![CDATA[html]]></category>
		<category><![CDATA[JavaScript programming language]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[jquery javascript library]]></category>
		<category><![CDATA[jquery selectors]]></category>
		<category><![CDATA[Markup languages]]></category>
		<category><![CDATA[openlayers]]></category>
		<category><![CDATA[openlayers library]]></category>
		<category><![CDATA[Span and div]]></category>
		<category><![CDATA[Technology/Internet]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[World Wide Web]]></category>

		<guid isPermaLink="false">/?p=1989</guid>
		<description><![CDATA[Selectors in jQuery If you&#8217;re familiar with jQuery you should already know what are selectors and how they work. However we&#8217;re used to get some DOM element with a specific selector, but actually sometimes you cannot select directly what you need. This is especially true when mixing more than one JavaScript libraries. In my case &#8230; <a href="/2010/09/24/2xjquery-select-a-selector/" class="more-link">Continue reading <span class="screen-reader-text">2xjQuery: Select a Selector</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2010/01/08/jquery-vs-pure-javascript/" rel="bookmark" title="jQuery vs. pure JavaScript">jQuery vs. pure JavaScript </a></li>
<li><a href="/2009/07/29/cancel-bubbling-on-element-click-with-jquery/" rel="bookmark" title="cancel bubbling on element click with jQuery">cancel bubbling on element click with jQuery </a></li>
<li><a href="/2009/11/02/ajax-in-jquery/" rel="bookmark" title="$.ajax in jQuery">$.ajax in jQuery </a></li>
<li><a href="/2009/04/01/jquery-accessing-a-child-element/" rel="bookmark" title="jQuery &#8211; accessing a child element">jQuery &#8211; accessing a child element </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>Selectors in jQuery</h2>
<p><a href="/wp-content/uploads/2010/09/jquery.png"><img class="alignleft size-full wp-image-1999" title="jquery" src="/wp-content/uploads/2010/09/jquery.png" alt="jQuery JavaScript Library" width="259" height="65" /></a></p>
<p>If you&#8217;re familiar with <a title="jQuery" href="http://jquery.com/" target="_blank">jQuery</a> you should already know what are selectors and how they work. However we&#8217;re used to get some DOM element with a specific selector, but actually sometimes you cannot select directly what you need. This is especially true when mixing more than one JavaScript libraries. In my case <a title="OpenLayers" href="http://openlayers.org/" target="_blank">OpenLayers</a> generated a vector layer and jQuery was supposed to change the vectors fill-color property.</p>
<p><a href="/wp-content/uploads/2010/09/openlayers.png"><img class="alignleft size-full wp-image-2000" title="openlayers" src="/wp-content/uploads/2010/09/openlayers.png" alt="OpenLayers" width="195" height="37" /></a></p>
<p>With the simple $(&#8216;path&#8217;) I easily got all vectors in the current document, but the problem was that I took them as text. Thus it came to me to use nested jQuery &#8211; $($(&#8216;selector&#8217;));</p>
<p>To describe what actually happened in my case, let me show you a breve example.</p>
<h2>Example</h2>
<p>Here&#8217;s a short HTML markup:</p>
<pre lang="html4strict">
<div><span>text text</span></div>

</pre>
<p>With jQuery I can select both the DIV and SPAN with the simple $(&#8216;div&#8217;) and $(&#8216;span&#8217;), but just for the example lets assume I&#8217;ve only the inner text of the DIV tag:</p>
<pre lang="javascript">$('div').html();
</pre>
<p>That was the case in the OpenLayers/jQuery problem. Now I can easily use another jQuery selector:</p>
<pre lang="javascript">$($('div').html());
</pre>
<p>This will return the same as $(&#8216;span&#8217;) &#8211; a jQuery object.</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2010/01/08/jquery-vs-pure-javascript/" rel="bookmark" title="jQuery vs. pure JavaScript">jQuery vs. pure JavaScript </a></li>
<li><a href="/2009/07/29/cancel-bubbling-on-element-click-with-jquery/" rel="bookmark" title="cancel bubbling on element click with jQuery">cancel bubbling on element click with jQuery </a></li>
<li><a href="/2009/11/02/ajax-in-jquery/" rel="bookmark" title="$.ajax in jQuery">$.ajax in jQuery </a></li>
<li><a href="/2009/04/01/jquery-accessing-a-child-element/" rel="bookmark" title="jQuery &#8211; accessing a child element">jQuery &#8211; accessing a child element </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2010/09/24/2xjquery-select-a-selector/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>OpenLayers Can Be Faster!</title>
		<link>/2010/03/19/openlayers-can-be-faster/</link>
		<comments>/2010/03/19/openlayers-can-be-faster/#comments</comments>
		<pubDate>Fri, 19 Mar 2010 09:22:35 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[javascript]]></category>
		<category><![CDATA[micro tutorial]]></category>
		<category><![CDATA[Computing]]></category>
		<category><![CDATA[DOM]]></category>
		<category><![CDATA[Geography]]></category>
		<category><![CDATA[Keyhole Markup Language]]></category>
		<category><![CDATA[openlayers]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[Web 2.0]]></category>
		<category><![CDATA[Web mapping]]></category>

		<guid isPermaLink="false">/?p=1364</guid>
		<description><![CDATA[Put All The Markers at Once! The way OpenLayers puts markers on the stage is fine when they are not so much, but once you need more than 100, the library&#8217;s solution is not good. The question is is there a way to put all the markers faster than the built in method. Yes, There &#8230; <a href="/2010/03/19/openlayers-can-be-faster/" class="more-link">Continue reading <span class="screen-reader-text">OpenLayers Can Be Faster!</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2010/02/08/openlayers-extreme-optimization-cut-compress-and-deploy/" rel="bookmark" title="OpenLayers extreme optimization. Cut, compress and deploy!">OpenLayers extreme optimization. Cut, compress and deploy! </a></li>
<li><a href="/2010/02/09/optimizing-openlayers-speed-up-markers-load-time/" rel="bookmark" title="Optimizing OpenLayers. Speed up markers load time!">Optimizing OpenLayers. Speed up markers load time! </a></li>
<li><a href="/2010/01/14/optimizing-openlayers-make-it-smaller-and-faster/" rel="bookmark" title="Optimizing OpenLayers. Make it smaller and faster!">Optimizing OpenLayers. Make it smaller and faster! </a></li>
<li><a href="/2009/06/20/openlayers-disable-mouse-wheel-on-zoom/" rel="bookmark" title="OpenLayers disable mouse wheel on zoom">OpenLayers disable mouse wheel on zoom </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>Put All The Markers at Once!</h2>
<p>The way OpenLayers puts markers on the stage is fine when they are not so much, but once you need more than 100, the library&#8217;s solution is not good. The question is is there a way to put all the markers faster than the built in method.</p>
<h2>Yes, There is a Way to Speed Up Markers Load</h2>
<p>I once wrote about how to speed up markers on <a title="OpenLayers" href="http://openlayers.org/" target="_blank">OpenLayers</a>, it is clear that my decision was to concatenate the DOM elements like a string after I&#8217;ve generated all the markers as markup with innerHTML as it&#8217;s faster than appendChild. The only question left is how to convert Longitude/Latitude pair in pixels.</p>
<h2>The Answer&#8217;s Given by OpenLayers</h2>
<p>There is a method called <strong>getLayerPxFromLonLat()</strong> which do the job. Let me show you a snippet:</p>
<pre lang="javascript">ll = map.getLayerPxFromLonLat(new OpenLayers.LonLat(lon,lat));
console.log(ll);</pre>
<p>You can see what&#8217;s inside the ll object. You can now reference the pixel as ll.y and ll.x.</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2010/02/08/openlayers-extreme-optimization-cut-compress-and-deploy/" rel="bookmark" title="OpenLayers extreme optimization. Cut, compress and deploy!">OpenLayers extreme optimization. Cut, compress and deploy! </a></li>
<li><a href="/2010/02/09/optimizing-openlayers-speed-up-markers-load-time/" rel="bookmark" title="Optimizing OpenLayers. Speed up markers load time!">Optimizing OpenLayers. Speed up markers load time! </a></li>
<li><a href="/2010/01/14/optimizing-openlayers-make-it-smaller-and-faster/" rel="bookmark" title="Optimizing OpenLayers. Make it smaller and faster!">Optimizing OpenLayers. Make it smaller and faster! </a></li>
<li><a href="/2009/06/20/openlayers-disable-mouse-wheel-on-zoom/" rel="bookmark" title="OpenLayers disable mouse wheel on zoom">OpenLayers disable mouse wheel on zoom </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2010/03/19/openlayers-can-be-faster/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>jQuery tips &#8211; storing data</title>
		<link>/2010/02/19/jquery-tips-storing-data/</link>
		<comments>/2010/02/19/jquery-tips-storing-data/#respond</comments>
		<pubDate>Fri, 19 Feb 2010 08:55:51 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[javascript]]></category>
		<category><![CDATA[web development]]></category>
		<category><![CDATA[author]]></category>
		<category><![CDATA[Computing]]></category>
		<category><![CDATA[DOM]]></category>
		<category><![CDATA[Form]]></category>
		<category><![CDATA[html]]></category>
		<category><![CDATA[Technology/Internet]]></category>
		<category><![CDATA[Variable]]></category>
		<category><![CDATA[World Wide Web]]></category>

		<guid isPermaLink="false">/?p=1125</guid>
		<description><![CDATA[Storing data? I was reading an article where the author says it is not a good practice to store data in the DOM. Indeed this is a bad practice and you should avoid it. After that he gives an example with using the DOM with the ALT attribute: $('selector').attr('alt', 'data being stored'); // later the &#8230; <a href="/2010/02/19/jquery-tips-storing-data/" class="more-link">Continue reading <span class="screen-reader-text">jQuery tips &#8211; storing data</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2010/03/31/jquery-get-the-id-of-the-current-element/" rel="bookmark" title="jQuery Get the Id of the Current Element">jQuery Get the Id of the Current Element </a></li>
<li><a href="/2010/02/24/storing-javascript-objects-in-html5-localstorage/" rel="bookmark" title="Storing JavaScript objects in html5 localStorage">Storing JavaScript objects in html5 localStorage </a></li>
<li><a href="/2010/09/27/jquery-setting-up-a-vector-path-fill-color/" rel="bookmark" title="jQuery: Setting Up a Vector Path Fill Color">jQuery: Setting Up a Vector Path Fill Color </a></li>
<li><a href="/2010/07/16/friday-algorithms-a-data-structure-javascript-stack/" rel="bookmark" title="Friday Algorithms: A Data Structure: JavaScript Stack">Friday Algorithms: A Data Structure: JavaScript Stack </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>Storing data?</h2>
<p>I was reading an <a href="http://www.tripwiremagazine.com/2009/10/jquery-and-general-javascript-tips-to-improve-your-code.html" target="_blank">article</a> where the author says it is not a good practice to store data in the DOM. Indeed this is a bad practice and you should avoid it. After that he gives an example with using the DOM with the ALT attribute:</p>
<blockquote>
<pre>$('selector').attr('alt', 'data being stored');
// later the data can be retrieved using:
$('selector').attr('alt');</pre>
</blockquote>
<p>and after that the more clean:</p>
<blockquote>
<pre>$('selector').data('paramtername', 'data being stored');
// then later getting the data with
$('selector').data('paramtername');</pre>
</blockquote>
<p>OK, is more clean. But however it is bad practice to use such a &#8220;heavy&#8221; construction to store local data. It is obvious you can prefer to store it in a local variable. Thus you avoid the extra performance.</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2010/03/31/jquery-get-the-id-of-the-current-element/" rel="bookmark" title="jQuery Get the Id of the Current Element">jQuery Get the Id of the Current Element </a></li>
<li><a href="/2010/02/24/storing-javascript-objects-in-html5-localstorage/" rel="bookmark" title="Storing JavaScript objects in html5 localStorage">Storing JavaScript objects in html5 localStorage </a></li>
<li><a href="/2010/09/27/jquery-setting-up-a-vector-path-fill-color/" rel="bookmark" title="jQuery: Setting Up a Vector Path Fill Color">jQuery: Setting Up a Vector Path Fill Color </a></li>
<li><a href="/2010/07/16/friday-algorithms-a-data-structure-javascript-stack/" rel="bookmark" title="Friday Algorithms: A Data Structure: JavaScript Stack">Friday Algorithms: A Data Structure: JavaScript Stack </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2010/02/19/jquery-tips-storing-data/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>CSS sprites. Go beyond the limits with base64!</title>
		<link>/2010/02/05/css-sprites-go-beyond-the-limits-with-base64/</link>
		<comments>/2010/02/05/css-sprites-go-beyond-the-limits-with-base64/#comments</comments>
		<pubDate>Fri, 05 Feb 2010 08:10:29 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[css]]></category>
		<category><![CDATA[micro tutorial]]></category>
		<category><![CDATA[base64]]></category>
		<category><![CDATA[Cascading Style Sheets]]></category>
		<category><![CDATA[communication]]></category>
		<category><![CDATA[Computing]]></category>
		<category><![CDATA[Data URI scheme]]></category>
		<category><![CDATA[DOM]]></category>
		<category><![CDATA[html]]></category>
		<category><![CDATA[http]]></category>
		<category><![CDATA[Minification]]></category>
		<category><![CDATA[sprite]]></category>
		<category><![CDATA[Stoyan Stefanov]]></category>
		<category><![CDATA[Technology/Internet]]></category>
		<category><![CDATA[URI scheme]]></category>
		<category><![CDATA[Web design]]></category>
		<category><![CDATA[Web page]]></category>
		<category><![CDATA[web projects]]></category>
		<category><![CDATA[web server]]></category>
		<category><![CDATA[World Wide Web]]></category>

		<guid isPermaLink="false">/?p=1055</guid>
		<description><![CDATA[Why should I optimize CSS? In fact how and why should I optimize CSS is the right question. Actually CSS is simply one ore more files loaded from the server to the client, usually a browser, with CSS specific rules that must be applied by the browser to the web page you&#8217;re seeing. That&#8217;s in &#8230; <a href="/2010/02/05/css-sprites-go-beyond-the-limits-with-base64/" class="more-link">Continue reading <span class="screen-reader-text">CSS sprites. Go beyond the limits with base64!</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2009/04/23/when-you-should-use-base64-for-images/" rel="bookmark" title="When you should use base64 for images">When you should use base64 for images </a></li>
<li><a href="/2010/01/30/optimizing-css-five-simple-steps/" rel="bookmark" title="Optimizing CSS. Five simple steps!">Optimizing CSS. Five simple steps! </a></li>
<li><a href="/2010/01/13/optimizing-the-web-start-with-the-images/" rel="bookmark" title="Optimizing the web. Start with the images!">Optimizing the web. Start with the images! </a></li>
<li><a href="/2011/01/07/more-on-css-optimization/" rel="bookmark" title="More on CSS Optimization">More on CSS Optimization </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>Why should I optimize CSS?</h2>
<p>In fact how and why should I optimize CSS is the right question. Actually CSS is simply one ore more files loaded from the server to the client, usually a browser, with CSS specific rules that must be applied by the browser to the web page you&#8217;re seeing. That&#8217;s in general. Of course there are exceptions when CSS can be inline or added directly to the HTML tags, which is bad practice because thus the HTML markup becomes larger and even worse the browser cannot cache it and than load it quickly. In fact that&#8217;s why usually the CSS of a web page is put in one single file. Primary because that makes only one request to the server and in second hand because it can be cached by the browser.</p>
<p>Just because the nature of the CSS is that firstly it&#8217;s loaded and than executed one of the primary techniques of optimizing it is to make it smaller and therefore load faster. There are several methods of doing so. Enabling GZIP support of the web server and minifying the file are the most common ones. But one of the tricks you cannot optimizing just for second is using the so called CSS sprites.</p>
<h2>CSS sprites</h2>
<p>What are these? To answer this question I&#8217;ll simply try to give you an example. Let&#8217;s assume there are three CSS classes each one with its own background image. This makes four requests to the server. One for the CSS file and one per every background image. But what we&#8217;d like to achieve is to make less requests as we can. Than one of the things we can do is to make one single image and to change only the background-position CSS property to position it on the right place and to make it appear correctly.</p>
<p>Be careful! When you join all of the images into one single CSS sprite you may add one class with that background-image and every other class with only background-position property. Than every DOM element with that background must have both class names. Only than you can be sure the server will make two requests. One for the CSS file and one for the sprite.</p>
<h2>base64 to encode images</h2>
<p>In other hand most of the web projects are pretty big, and unfortunately it&#8217;s too difficult to make only one single sprite just because it&#8217;s too difficult to manage it after the project has become very large. That&#8217;s why mostly in the practice there are several sprites for the main components. But the problem is that again there are more HTTP requests.</p>
<h3>Is there any way to make only one request?</h3>
<p>Yes there is. Simply by converting your CSS sprite into a base64 encoded image. In breve base64 is an encoding where you can practically make any data into a string. Thus the image can be represented by a string containing the same information as the image. Hopefully most of the browser, except of course MSIE, does read the so called data urls, or:</p>
<blockquote>
<pre>&lt;img src="data:image/png;base64,..... " /&gt;</pre>
</blockquote>
<p>and that&#8217;s enough to get started with base64 and the single request. The sprite has become a string!</p>
<h2>CSS and base64</h2>
<p>The natural question is now how to merge all this? You now have one CSS file with one or more sprites. Than you can convert them into a base64 encoded strings and put them all into the CSS.</p>
<p>There is a problem, of course, what happens with MSIE. As I said before MSIE doesn&#8217;t read base64 encoded images. Hopefully there is a solution described very well by <a href="http://phpied.com/" target="_blank">Stoyan Stefanov</a> in his <a href="http://www.phpied.com/data-uris-mhtml-ie7-win7-vista-blues/" target="_blank">blog post here</a>.</p>
<h2>Finally &#8230;</h2>
<p>now there is only one request and everything works pretty fine. This technique can be really helpful to someone who&#8217;s trying to optimize the CSS performance to the limits.</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2009/04/23/when-you-should-use-base64-for-images/" rel="bookmark" title="When you should use base64 for images">When you should use base64 for images </a></li>
<li><a href="/2010/01/30/optimizing-css-five-simple-steps/" rel="bookmark" title="Optimizing CSS. Five simple steps!">Optimizing CSS. Five simple steps! </a></li>
<li><a href="/2010/01/13/optimizing-the-web-start-with-the-images/" rel="bookmark" title="Optimizing the web. Start with the images!">Optimizing the web. Start with the images! </a></li>
<li><a href="/2011/01/07/more-on-css-optimization/" rel="bookmark" title="More on CSS Optimization">More on CSS Optimization </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2010/02/05/css-sprites-go-beyond-the-limits-with-base64/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Optimizing CSS. Five simple steps!</title>
		<link>/2010/01/30/optimizing-css-five-simple-steps/</link>
		<comments>/2010/01/30/optimizing-css-five-simple-steps/#respond</comments>
		<pubDate>Sat, 30 Jan 2010 07:04:40 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[css]]></category>
		<category><![CDATA[micro tutorial]]></category>
		<category><![CDATA[Cascading Style Sheets]]></category>
		<category><![CDATA[Computing]]></category>
		<category><![CDATA[DOM]]></category>
		<category><![CDATA[Google Inc.]]></category>
		<category><![CDATA[http]]></category>
		<category><![CDATA[Minification]]></category>
		<category><![CDATA[Software engineering]]></category>
		<category><![CDATA[software minifies]]></category>
		<category><![CDATA[sprite]]></category>
		<category><![CDATA[Steve Souders]]></category>
		<category><![CDATA[Style sheet]]></category>
		<category><![CDATA[Technology/Internet]]></category>
		<category><![CDATA[Web design]]></category>

		<guid isPermaLink="false">/?p=872</guid>
		<description><![CDATA[In the spirit of the optimization wave this post is about CSS optimization. There are some simple rules that you can apply. I’m pretty sure most of us have already been familiar with that list, but you never know. 1. Minify As the JavaScript the CSS also can be minified. This only strips every character &#8230; <a href="/2010/01/30/optimizing-css-five-simple-steps/" class="more-link">Continue reading <span class="screen-reader-text">Optimizing CSS. Five simple steps!</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2010/01/18/what-if-your-site-doesnt-use-all-of-the-css-selectors/" rel="bookmark" title="What if your site doesn&#8217;t use all of the CSS selectors?">What if your site doesn&#8217;t use all of the CSS selectors? </a></li>
<li><a href="/2011/01/07/more-on-css-optimization/" rel="bookmark" title="More on CSS Optimization">More on CSS Optimization </a></li>
<li><a href="/2010/02/15/css-selectors-new-look-over-them/" rel="bookmark" title="CSS selectors &#8211; new look over them">CSS selectors &#8211; new look over them </a></li>
<li><a href="/2010/02/05/css-sprites-go-beyond-the-limits-with-base64/" rel="bookmark" title="CSS sprites. Go beyond the limits with base64!">CSS sprites. Go beyond the limits with base64! </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<p>In the spirit of the optimization wave this post is about CSS optimization. There are some simple rules that you can apply. I’m pretty sure most of us have already been familiar with that list, but you never know.</p>
<h3>1. Minify</h3>
<p>As the JavaScript the CSS also can be minified. This only strips every character that makes the traffic bigger. As you know a well constructed and pretty looking CSS file consists of many new lines, tabs and spaces. Almost every software minifies the CSS by simply removing them. Some of the programs go even further with replacements of different parts of the code considered to be not efficient.</p>
<h3>2. Use effective selectors</h3>
<p>Some CSS selectors aren’t really efficient. Imagine something like: body div a just to describe only one specific link. That’s really bad. Better practice is to replace that line with something like a.my-class and to replace the a tag into the DOM with that class name. That will be far more effective. Actually if you’re wondering how to find such bad selectors, there’s a tool by Google called Page Speed that’s a Firebug’s plugin and can extract a list of all bad selectors.</p>
<h3>3. Inheritance</h3>
<p>CSS is really powerful when dealing with inheritance. That’s something that is not some clear but however really powerful. This technique is in the basics of the next rule.</p>
<h3>4. Sprites</h3>
<p>I’ve written already about CSS sprites. This is nothing new, but be careful when making a new site’s layout. CSS sprites spend you HTTP request and that’s rule number one according to Steve Souders’ list of optimization.</p>
<h3>5. Separate logic</h3>
<p>Sometimes developers put the site logic in only one file that become to large. Be aware of that. This is hard to maintain and you load things that you don’t need.</p>
<p>That’s a really short list of what you can do with CSS to speed the site up. I hope that can help someone when dealing with cascading style sheets.</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2010/01/18/what-if-your-site-doesnt-use-all-of-the-css-selectors/" rel="bookmark" title="What if your site doesn&#8217;t use all of the CSS selectors?">What if your site doesn&#8217;t use all of the CSS selectors? </a></li>
<li><a href="/2011/01/07/more-on-css-optimization/" rel="bookmark" title="More on CSS Optimization">More on CSS Optimization </a></li>
<li><a href="/2010/02/15/css-selectors-new-look-over-them/" rel="bookmark" title="CSS selectors &#8211; new look over them">CSS selectors &#8211; new look over them </a></li>
<li><a href="/2010/02/05/css-sprites-go-beyond-the-limits-with-base64/" rel="bookmark" title="CSS sprites. Go beyond the limits with base64!">CSS sprites. Go beyond the limits with base64! </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2010/01/30/optimizing-css-five-simple-steps/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>CSS default position value</title>
		<link>/2010/01/24/css-default-position-value/</link>
		<comments>/2010/01/24/css-default-position-value/#respond</comments>
		<pubDate>Sun, 24 Jan 2010 06:40:11 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[css]]></category>
		<category><![CDATA[Cascading Style Sheets]]></category>
		<category><![CDATA[DOM]]></category>
		<category><![CDATA[Web design]]></category>

		<guid isPermaLink="false">/?p=945</guid>
		<description><![CDATA[position:absolute? Recently I was working on a problem where some DOM elements inherited the absolute position from their ancestors. Well this is pretty rare, but however it happens from time to time. If you’re wandering, as I was, how to disable this and to call the default property value just stop hesitating. The default property &#8230; <a href="/2010/01/24/css-default-position-value/" class="more-link">Continue reading <span class="screen-reader-text">CSS default position value</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2011/03/29/scroll-an-iframe-content-to-a-predefined-position/" rel="bookmark" title="Scroll an IFRAME Content to a Predefined Position">Scroll an IFRAME Content to a Predefined Position </a></li>
<li><a href="/2010/02/05/css-sprites-go-beyond-the-limits-with-base64/" rel="bookmark" title="CSS sprites. Go beyond the limits with base64!">CSS sprites. Go beyond the limits with base64! </a></li>
<li><a href="/2009/11/04/jquery-css-selectors-change-one-or-more-css-properties/" rel="bookmark" title="jQuery CSS selectors. Change one or more CSS properties!">jQuery CSS selectors. Change one or more CSS properties! </a></li>
<li><a href="/2010/03/08/css-right-to-left-direction-floating-elements/" rel="bookmark" title="CSS right to left direction &#038; floating elements">CSS right to left direction &#038; floating elements </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>position:absolute?</h2>
<p>Recently I was working on a problem where some DOM elements inherited the absolute position from their ancestors. Well this is pretty rare, but however it happens from time to time. If you’re wandering, as I was, how to disable this and to call the default property value just stop hesitating. The default property is static. So you can simply write:</p>
<blockquote>
<pre>#element_id {
   position:static;
}</pre>
</blockquote>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2011/03/29/scroll-an-iframe-content-to-a-predefined-position/" rel="bookmark" title="Scroll an IFRAME Content to a Predefined Position">Scroll an IFRAME Content to a Predefined Position </a></li>
<li><a href="/2010/02/05/css-sprites-go-beyond-the-limits-with-base64/" rel="bookmark" title="CSS sprites. Go beyond the limits with base64!">CSS sprites. Go beyond the limits with base64! </a></li>
<li><a href="/2009/11/04/jquery-css-selectors-change-one-or-more-css-properties/" rel="bookmark" title="jQuery CSS selectors. Change one or more CSS properties!">jQuery CSS selectors. Change one or more CSS properties! </a></li>
<li><a href="/2010/03/08/css-right-to-left-direction-floating-elements/" rel="bookmark" title="CSS right to left direction &#038; floating elements">CSS right to left direction &#038; floating elements </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2010/01/24/css-default-position-value/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>jQuery live() vs bind() performance</title>
		<link>/2009/12/30/jquery-live-vs-bind-performance/</link>
		<comments>/2009/12/30/jquery-live-vs-bind-performance/#respond</comments>
		<pubDate>Wed, 30 Dec 2009 15:27:06 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[javascript]]></category>
		<category><![CDATA[micro tutorial]]></category>
		<category><![CDATA[ajax]]></category>
		<category><![CDATA[Application programming interfaces]]></category>
		<category><![CDATA[Document Object Model]]></category>
		<category><![CDATA[DOM]]></category>
		<category><![CDATA[events]]></category>
		<category><![CDATA[html]]></category>
		<category><![CDATA[HTML element]]></category>
		<category><![CDATA[JavaScript programming language]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[Span and div]]></category>

		<guid isPermaLink="false">/?p=841</guid>
		<description><![CDATA[1. What is event delegation in JavaScript? To start with some example let&#8217;s assume that there is one DIV element with 100 A tags inside. If you assign event to every A tag that as you may know slowes down your browser. That&#8217;s a problem because sometimes that can happen, even with more than one &#8230; <a href="/2009/12/30/jquery-live-vs-bind-performance/" class="more-link">Continue reading <span class="screen-reader-text">jQuery live() vs bind() performance</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2009/10/08/jquery-the-difference-between-mouseout-and-mouseleave/" rel="bookmark" title="jQuery: the difference between mouseout and mouseleave">jQuery: the difference between mouseout and mouseleave </a></li>
<li><a href="/2009/07/29/cancel-bubbling-on-element-click-with-jquery/" rel="bookmark" title="cancel bubbling on element click with jQuery">cancel bubbling on element click with jQuery </a></li>
<li><a href="/2009/05/25/remove-dom-element-with-jquery/" rel="bookmark" title="Remove DOM Element with JQuery">Remove DOM Element with JQuery </a></li>
<li><a href="/2009/04/01/jquery-accessing-a-child-element/" rel="bookmark" title="jQuery &#8211; accessing a child element">jQuery &#8211; accessing a child element </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>1. What is event delegation in JavaScript?</h2>
<p>To start with some example let&#8217;s assume that there is one DIV element with 100 A tags inside. If you assign event to every A tag that as you may know slowes down your browser. That&#8217;s a problem because sometimes that can happen, even with more than one hundred A tags. Imagine you&#8217;ve a map with one thousand markers, which are A tags. Attaching events slowes down the browser, because every of these A tags bubbles the event that has been fired. And that makes your CPU to make thousands of calculations. Of course you can avoid this problem with a simple technique. Just attach one single event on the container DIV element. Thus you can check if some child of the DIV element has been the target of the event. This makes the browser to breath.<span id="more-841"></span></p>
<h2>2. How event delegation is implemented in jQuery &#8211; $.live()</h2>
<p>In jQuery the so called event delegation is done by the $.live() method. As you may see in the doc pages of jQuery thus you can attach events on a selected element even before that element exists into the DOM. Just because the attached event is on the parent element, and once there are more and more elements attached to it as children, thay behave the same way as those attached before.</p>
<blockquote>
<pre>Example:
$('div &gt; a').live('click', doSomething);</pre>
</blockquote>
<h2>3. bind with $.bind() or $.click, $.mousemove &#8230;</h2>
<p>More common use in jQuery is to attach elements with $.bind or it&#8217;s shortcus $.click, $.mousemove &#8230; etc. The problem is that you have to call them again and again after you add more and more elements to the DOM, because this attach events to the matched elements. Normally when you add more elements they don&#8217;t have any event attached to.</p>
<blockquote>
<pre>Example:
$('div &gt; a').click(doSomething);
// this example does exactly the same thing as the one above,
// but applied on 1000 tags is much slower!</pre>
</blockquote>
<h2>4. Performance</h2>
<p>Of course the performance is better with $.live, but be carefull when playing around with those methods. See more performance results <a href="http://www.ravelrumba.com/blog/event-delegation-jquery-performance/" target="_blank">here</a>.</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2009/10/08/jquery-the-difference-between-mouseout-and-mouseleave/" rel="bookmark" title="jQuery: the difference between mouseout and mouseleave">jQuery: the difference between mouseout and mouseleave </a></li>
<li><a href="/2009/07/29/cancel-bubbling-on-element-click-with-jquery/" rel="bookmark" title="cancel bubbling on element click with jQuery">cancel bubbling on element click with jQuery </a></li>
<li><a href="/2009/05/25/remove-dom-element-with-jquery/" rel="bookmark" title="Remove DOM Element with JQuery">Remove DOM Element with JQuery </a></li>
<li><a href="/2009/04/01/jquery-accessing-a-child-element/" rel="bookmark" title="jQuery &#8211; accessing a child element">jQuery &#8211; accessing a child element </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2009/12/30/jquery-live-vs-bind-performance/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
