Building With Gulp

gulpI came across with an very interesting post in Smashing magazine that coverts a lot of topics related with Gulp. Kudos to for this great article!!.

Hope you find this information useful!!

JSHint: detect errors and potential problems in your JavaScript code

JavaScriptIn the last two year I have been coding in JavaScript more than I expected, but in all this time I haven´t used a tool for detect errors in my JavaScript code until a friend told me about JSHint, that is a community-driven tool to detect errors and potential problems in JavaScript code and to enforce coding conventions. Two of the nice features that caught my attention is that enforce coding conventions and It is very flexible so you can easily adjust it to your particular coding guidelines and the environment you expect your code to execute in.

The core project consists of a library itself as well as a CLI program distributed as a Node modules. Also has plugins for text editors and IDEs like

  • Sublime Text
  • Eclipse
  • Notepad++
  • etc..

I have used it in an internal project and I like it, easily help me to detect some coding conventions that we forget to follow in one of the functions, great!!

You can test it directly on your browser to see how it works: http://www.jshint.com/

Hope you find this information useful!!

jQuery Coding Standards & Best Practices

jQueryYup, for those that are always looking to improve their jQuery skills: jQuery Coding Standards & Best Practices. Thanks to my friend Alex Arriaga for sharing me this link.

Hope you find this information useful!!

How to prevent bootstrap carousel to autorun

bootstrapA little tip: sometimes you wants to prevent bootstrap carousel from automatically cycling through items when clicking on prev/next buttons and instead, be controlled manually all the time.

 

 

Bootstrap version 2.3.2 documentation says:

$('your-carousel').carousel('pause');

Stops the carousel from cycling through items.

Bootstrap documentation is not correct at all, luckily Google came to our rescue, the correct way to prevent from automatically cycling through items when clicking on prev/next buttons is:

$('your-carousel').carousel({
pause: true,
interval: false
});

Hope you find this information useful!!

How to extend Dust filters using jQuery

JavaScriptDust is a JavaScript templating engine designed to provide a clean separation between presentation and logic without sacrificing ease of use. It is particularly well-suited for asynchronous and streaming applications.

Inside its core, Dust offer a set of filters that can be used in specific scenarios like to force HTML escaping, but does not offer filters for all the possible scenarios.

So If you want to see how how you can easily extend Dust filters using jQuery, read How to extend Dust filters using jQuery in the Base22 Knowledge Wiki.

Note: Dust documentation makes the following assertion when you use filters: “all output values are escaped to avoid Cross Site Scripting (XSS) unless you use filters.”, but only applies to the default filters that brings Dust. If you create your own filters, they are still protected against XSS unless used in conjunction with the default Dust filters.

Hope you find this information useful!!

How to trace JavaScript Performance using Navigation Timing API

JavaScriptFast websites, an universal demand, but not always achieved. If you are a web developer, is desired that you expend a couple of your time to care about this point.

This post complement my previous post: How to use Console Timing to Trace JavaScript Performance, and works as an introduction to use Navigation Timing API.

“The Navigation Timing API provides data that can be used to measure the performance of a website. Unlike other JavaScript-based mechanisms that have been for the same purpose this API can provide end-to-end latency data that can be more useful and accurate”.

The following graph illustrates the timing attributes defined by the PerformanceTiming interface and the PerformanceNavigation interface with or without redirect, respectively. Attributes underlined may not be available in navigation involving documents from different origins. User agents may perform internal processing in between timings, which allow for non-normative intervals between timings.

timing-overview-large_mini

For example, if you want to measure the user-perceived page loading time of a page you can use the next JavaScript code:

<html>
<head>
<script type="text/javascript">
// Add load event listener.
window.addEventListener("load", loadTime, false);
function loadTime() {
  // Get current time.
  var now = new Date().getTime();
  // Calculate page load time.
  var page_load_time = now - performance.timing.navigationStart;
  if (window.console) console.log("User-perceived page loading time" + page_load_time);
}

</head>
<body>
<!- More HTML here. -->
</body>
</html>

As definition:

  • navigationStart: Time after the previous document begins unload.

Or, in other words, tells us when the user initiated the page load, either by clicking a link, or entering it into their browser’s URL bar.

Now you have more tools, at least at client-side, to measure the performance of your pages.

More information:

Note: don’t forget to clean all console calls in your production code, also, check the browser compatibility (Mozilla MDN) since is not supported in all browsers.

Hope you find this information useful!

How to create a dynamic getSortData function for Isotope jQuery plugin

JavaScriptIn a previous post I shared  How to combine Isotope Sort and Filter in a real example. At the end of my post I mentioned that should be nice if Isotopo could create dynamically all the sorts/filters within getSorData.

In this post I will share how I achieve that, if you don’t know about Isotope and what is its purpose I invite you to first read my previous post about Isotope.

getSortData option:

“This option accepts an object, whose values are the functions to extract the data. Each function receives one argument, which represents a jQuery object for each item element. With that argument, the function needs to return the data point.”

So, the data extracted can be anything accessible in the item element via jQuery. You can use a text element, numerical data ( using parseInt( ) or parseFloat( ) ), a data attribute or a property like the width of each item element.

Your getSortData functions could looks like the follow:

getSortData: {
    sort1: function($elem) {
        return parseInt($elem.attr('data-category-sort1'), 10);
    },
    bywidth: function($elem) {
        return $elem.width();
    },
    byname: function($elem) {
        return $elem.find('.name').text();
    }
    // more...
}

The problem with this approach is that if you needs a new sorting, well, you will need to add manually that new function inside getSortdata. I have created a function that create these sorting functions dynamically, the function doesn’t cover all the scenarios but is possible to add more easily:

function createSort(){
    var sorts = {};
    var $source = jQuery('source'); //from where I will read data
    $source.each(function() {
        var $element = jQuery(this),
        findBy = $element.children('a').data('sort-type'), //element, numerical data, data attribute or a property
	key = $element.children('a').data('option-value'); //the name of the element, numerical data, data attribute or a property
	//if the sort is based on a css class (an element)
        if(findBy === "class"){
            sortData[key] = function($elem){return $elem.find('.'+ key).text();};
        }
	//if the sort is based on a data attribute (in my scenario is a numerical attribute)
	if(findBy === "attr"){
	    sortData[key] = function($elem){return parseInt($elem.attr('data-category-' + key), 10);};
        }
    });
    return sortData;
}

//then I call the function and pass the result to getSortData
var sort_data = createSort(),
$container.isotope({
    //more code.
    getSortData:sort_data
});

And where is the jQuery(‘source’) that is used inside createSort()?. In my case all the functions are created based on a list of options created with a “ul” and each “li” element correspond to a type of sorting that will be read by my function createSort():

<ul class="sort-by option-set" id="sort-by" data-option-key="sortBy">
	<li><a href="#sortBy=title" data-option-value="title" data-sort-type="class">By Title</a></li>
	<li><a href="#sortBy=sports" data-option-value="sports" data-sort-type="attr">sports</a></li>
	<li><a href="#sortBy=technics" data-option-value="technics" data-sort-type="attr">technics</a></li>
</ul>

And is done!!.. hope you find this information useful.

How to use Console Timing to Trace JavaScript Performance

JavaScriptFast websites, an universal demand, but not always achieved. If you are a web developer, is desired that you expend a couple of your time to care about this point.

Firebug, the Webkit Inspector, Opera Dragonfly and IE11 all support the console.time( ) and console.timeStamp( ), very powerful methods that, used correctly, can help you to trace JavaScript performance very well.

Console.time( )

Creates a new timer under the given name. Call console.timeEnd(name) with the same name to stop the timer and print the time elapsed..

Example:

   console.time("fromHtmlTable");
   jQuery(this.data.source).children('tbody').children('tr').each(function() {
     // more code here...
   });
   console.timeEnd("fromHtmlTable");

And in the Firebug console you should get something similar to the next image:

console.time

And, the other output?, I’m using console.timeStamp( ) too!

console.timeStamp( )

Creates a time stamp, which can be used together with HTTP traffic timing to measure when a certain piece of code was executed.

Example:

   console.timeStamp("START: function fromHtmlTable");
   console.time("fromHtmlTable");
   jQuery(this.data.source).children('tbody').children('tr').each(function() {
     // more code here...
   });
   console.timeEnd("fromHtmlTable");
   console.timeStamp("END: function fromHtmlTable");

With these two functions I can track the time elapsed of my functions and also track when they where executed, and now is more easy for me identify if my JavaScript code needs to be optimized.

But wait a minute, numbers doesn’t match at all!! right??, of course, I expected that, but they are very close to the reality, so, be careful how to use these info, but you can trust in the output if you have added correctly the functions in your code.

Note: don’t forget to clean all console calls in your production code!!

I really hope you find this information useful.

Using JavaScript Event Delegation with JQuery

JavaScriptRecently I have been helping one of our clients to improve the performance of a particular section of their portal that shows in a set of tabs a huge list of items grouped by a set of categories, each item shows in a tool-tip a summary of it’s meaning/purpose… yes, jQuery is involved, and yes!, mouseenter/mouseleave or mouseover/mouseout is Involved too.. and yes… hold on.. JavaScript Event Delegation was involved??… event what??, ok, here we go.

The page looks like the next image:

items

One of the aspects I wanted to improve was the JavaScript code used to show the tool-tip on each of the items, why?, let’s take a look at the code:

$("my-path a[title]").live("mouseover",function(){
	// calling the plugin to show the tool-tip
});

Apparently, nothing wrong right?, a normal but old way to bind a mouseover event to an element, in this case to all links that match the jQuery selector  –> $(“my-path a[title]”), wait a minute, to all links??…  ooh no, you mean to all the 500+ links multiplied by 6 tabs, that is 3000+ items!! that is insane!!.

After a moment of shock I was determined to find a better way to handle that JavaScript code. I knew I needed a way to avoid listening to all the items (links) and instead listening only the parent  and when the parent detected a mouseenter/mouseleave event, then be able to determine if the user was in a link and then show up the tooltip; my teammates Iván Santiesteban and José (Pepe) Martínez point me in the right direction, they told me: use JavaScript Event Delegation.

I really recommend to read How JavaScript Event Delegation Works Written by David Walsh, in resume:

“Event delegation allows you to avoid adding event listeners to specific nodes;  instead, the event listener is added to one parent.”

In jQuery you can use .on() or .delegate(), all depends of your jQuery version, I had to use .delegate() since we use jQuery 1.6.x with that client, so, my new code looks like:

$j("#parent").delegate("a", "mouseenter", function(event) {
// more code here...
});
$j("#parent").delegate("a", "mouseleave", function() {
// more code here...
});

Now, I just have two listeners instead of 3000+!!. In my code I’m using mouseenter/mouseleave, you can use mouseover/mouseleave also, but be careful! all depends of your HTML and/or of the behavior you expected.

From jQuery .mouseenter() documentation:

“mouseover fires when the pointer moves into the child element as well, while mouseenter fires only when the pointer moves into the bound element.”

The performance of the page was increased dramatically in FF and response much better in IE7/8, still IE 7/8 sucks!.

I really hope you find this information useful.

What is a client-side template?

options_0This post is an introduction to learn about client-side templates and It’s not always good to reinvent the wheel, and that applies to this article too.

I have found a very good article that explain what I wanted to write here, is called From The Server To The ClientClient-Side Templating. I truly recommend to read this article in detail if you want learn how to deliver dynamic content via client-side and maximize code reusability and maintainability using JavaScript/jQuery, HTML, CSS, Ajax, JSON and of course, client-side templates.

Also, my teammate, Osvaldo Flores, has wrote about the same topic, he focused on Trimpath that is still our current JavaScript Templating engine here on Base22, but as all has to evolve, we are currently working on a new version of our assets using dust as our new engine, but that is another topic.

If you want to see a live demo of this client-side development technique, please visit our website Base22.com, there we use our xWidgets assets to show dynamic content that live in IBM WCM v8.

Future readings:

Hope you find this information useful!!