Category: JavaScript

JSX preprocessor – A syntax sugar for ReactJS

The JSX preprocessor

JSX preprocessor it is a step that adds XML syntax to JavaScript. You can definitely use React without JSX but JSX makes React a lot more elegant.

When you start typing code, driving yourself into the amazing world of web programming sometimes you may feel overwhelmed when you have to select a tool, a library or a framework as your initial learning point. Out there are too many tools, each one with different features aiming the same goal in their own way. Eventually you realize that HTML and CSS are not enough, you need JavaScript. And now for react you are able to use
JSX preprocessor.

JSX preprocessor

At some point, vanilla JavaScript became too heavy and hard in order to achieve certain task, the most efficient way is to make use of a library or a framework.
This time is the turn for ReactJS, it is a JavaScript library, and specifically one of its many features: JSX. Now, we will assume you already know something about ReactJs and the ecosystem around it. Otherwise you should start here first and then move on to this topic.

ReactJS feature:
Basically JSX is an inline markup that looks like XML/HTML and gets transformed to JavaScript (sometimes it can remind you a template language). It is possible to use ReactJS without JSX but JSX makes ReactJS code more elegant. A JSX expression starts with an XML/HTML-like open tag, and ends with the corresponding closing tag, it also supports the XML syntax so you can optionally leave the closing tag off. See the follow example:

 
const hw = <p>Hello, world!</p>;

This code is just JSX syntax example but you also can do things like embed JavaScript expressions in JSX by wrapping it in curly braces:

 

function hello(text) {
  return text.firstWord + ' ' + text.secondWord + '!';
}

const text = {
  firstWord: 'Hello',
  secondWord: 'World'
};

const element = (
  <p>
    This is a, {hello(text)}!     // embed JavaScript expression 
  </p>
);

Even specify attributes like follow:
You may use quotes to specify string literals as attributes:

 
const element = <div z-index="1"></div>;

You may also use curly braces to embed a JavaScript expression in an attribute:

 

var style = { backgroundImage: 'url(picture.png)', height: 10, width: 15 };
return <div style={style}></div>;

Now let’s analyze an example combined with ReactJS.

ReactJS applying JSX

 
var test = (  
  <div className='test-example'>//notice the parameter className instead of class
    <img 
      src='image.png'
      className='test-example'
    />
  </div>)

ReactDOM.render(test, document.getElementById('myapp'))

As you can see, it is like write HTML/XML code inside JavaScript but at the end it is just JavaScript. The special consideration is that JSX makes you name the attributes in a different way form the standard, in the example above, the 'class' for CSS must be named 'className' instead of the html standard attribute 'class'.

Basically JSX produces React "elements" and according to the official documentation ‘JSX just provides syntactic sugar to React.createElement(…) function’, see below:

 

<MyButton color="green" shadowSize={10} >
  Go!
</MyButton>


 
compiles into:
React.createElement(
  MyButton,
  {color: 'green', shadowSize: 10},
  'Go!'
)

JSX preprocessor Pros:

Declarative syntax:
Provides a very easy way to import static HTML or migrate from JavaScript templates. Plus, its enforces good syntactical restrictions similar to XHTML that improves quality of codebase.
ReactJS Documentation priories JSX:
ReactJS documentation uses JSX everywhere so JSX is only going to become more powerful.
Very useful tools and resources:
Babel is a tool able to transpiles ES6, ES7(stage 1 flag), JSX altogether.

Integrations with other frameworks

JSX simple example with AngularJS:
You can integrate JSX preprocessor with Angularjs to write the templates in places that you use javascript, for example in the directives.
If you want to use JSX-style with AngularJS the way is through AngularJS directives. In order to achieve this goal, we have angular-jsx library to convert templates into strings that Angular can understand. Take a look to this example:

Input

 
angular.module("foo").directive("bar",
    function() {
        return {
             // it can be used in the template for the directives
            template: <div>This is a simple example.</div>
        };
    }
);

Output

 
angular.module("foo").directive("bar",
    function() {
        return {
            template: "<div>This is a simple example.</div>"
        };
    }
);

More information about it can be found here. If you want a deeper point of view about more technical aspects related to ReactJs and JSX maybe this article will do the trick for you.

Redux with React – First look

redux with react
This time I going to take the time to research and write about Redux in combination with React, one of the hottest libraries for front-end web development. It was created in 2015, influenced by Flux architecture and became popular very quickly because of it's simplicity, excellent documentation and size (2 KB). Also is very easy to use redux with react. Let’s start with the basics:

What is Redux?

According to the official site Redux is defined as a predictable state container for JavaScript apps. Basically Redux maintains the state of an entire application in a single immutable state tree (object). This object can’t be changed directly. When something changes, a new object is created (using actions and reducers). The main goal of Redux is to facilitate the task of connect sources of different environments like for example APIs and sockets.

Redux with React.

Redux is kind of 'created' to work with React.js but also can be used with Angular.js, Backbone.js or just vanilla JS.

How to install it?

To install the stable release (through npm as package manager with a module builder like Webpack or Browserify to use modules of CommonJS):
npm i -S redux
Also you may want to install the connection to React and the developer tools.
npm i -S react-redux
npm i -D redux-devtools

Core concepts of Redux

1 – Actions.
The actions, summarized actions are events. The action task is to send data from the application (user interactions, internal events such as API calls, and form submissions) to the store. The only way to pass information to the store is through actions. The actions are POJO (Plain Old JavaScript Objects) with at least one property that indicates the action type and, if necessary, others properties indicating any other necessary data to do the action. Normally they use the format defined in FSA.

An action example:

 
{
    type: 'TODO_APP',
    payload: {
        text: 'How to learn Redux,
    },
}

Actions are created with action creators. They are just functions that return actions.

 
function myAction(someText) {

return {
	type: TODO_APP,
	payload: someText
}
}

To call an action anywhere in our app must be through dispatch method, like this:

 
// to send an action to the Store (The concept of Store will be seen ahead).
Store.dispatch (myAction(someText)); 

2 – Reducers.

While the actions describe that ‘something’ happen they don’t specify how our app reacts to that ‘something’. In Redux, reducers are functions (pure, I will explain what a pure function is later) that take the current state of the application and an action and then return a new state.
(prevState, action) => nextState
Here is a very simple reducer that takes the current state and an action as arguments and then returns the next state:

 

function handleAuth(state, action) {
	return _.assign({}, state, {
		auth: action.payload
	});
}

Some things you should never do in a reducer:
Modify the arguments directly (the right way is to create a copy first.)
Do actions with secondary effects like API calls or change a route.

The name we put to the reducer is used as property of ‘store’ we created and is where will be saved the state returned from the reducer.

3 – Store
Store is the object that holds the application state and provides a few helper methods to access the state, dispatch actions and register listeners. The entire state is represented by a single store. Any action returns a new state via reducers.
The store has four main responsibilities:
Store the global state of the app.
Give access to the state through store.getState()
Allow the update of the state through store.dispatch()
Register listeners through store.subscribe(listener)
Take this as example:

 

import { createStore } from 'redux';

	let store = createStore(rootReducer);
	let authInfo = {username: 'alex', password: '123456'};
	store.dispatch(authUser(authInfo));

This image illustrates the work flow of Redux.

redux dataflow
Redux data flow (Image: Tanya Bachuk)

The three principles of Redux.

- Single data source: The app state stores in one objet tree inside a unique STORE.
- The state is read only: The only way of change the state is through ACTIONS.
- Changes are made with pure functions: To specify how the state tree is transformed by actions, you write pure reducers.

Where can Redux be used?

Contrary of what you may be thinking, the only use of Redux isn't with React. It can be integrated with any other library/framework like for example Vue.js, Polymer, Ember, Backbone.js or Meteor, but Redux plus React, though, is still the most common combination.

Integrating Redux with React: Installing react-redux

The connection of Redux with React isn´t included directly inside Redux, in order to achieve this, we need to download react-redux:
npm i -S react react-dom react-redux redux

Encapsulating the app.

First we need to encapsulate our app with the component Provider that comes with react-redux. This component receives a unique parameter called store which one is the instance of the STORE we are using. See the follow example.

 
import { render } from 'react-dom';
import { Provider } from 'react-redux';
import React from 'react';
import store from './store';
import App from './components/App';

render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('app')
);

This component Provider defines in the global context of React our instance of store.

Accessing the store.

Now is time to define what components are going to Access our Store, because not all of them will need to. In order to do that we need to connect our Redux components to Redux, this can be achieved with a decorator that came with react-redux called connect.

 
// Importing the decorator @connect of react-redux

import { connect } from 'react-redux';
import React from 'react';
import UserItem from './UserItem';

// Aplying the decorator @connect to our component.

@connect()
class UserList extends React.Component {
  render() {
    // Rendering the user list we receive from Store  .  
    return (
      <section>
        {
          this.props.users
            .map(user => <UserItem {...user} key={user.id} />)
        }
      </section>    
    );
  }
}
export default UserList;

This way our component UserList will have inside it props all the data of the Store. With this we can render our app using the data stored in the Redux Store.

Pure functions vs Impure functions:

Pure Functions
A function is considered pure if:
a) It always returns the same value when given the same arguments.
b) It does not modify anything (arguments, state, database, I/O, ..).

Examples of Pure Functions (in JavaScript):

 
function add(x, y) {
return x+y;
}
 
function getLength(array) {
return array.length;
}

Impure Functions

A function is considered impure if it is not pure, typically because:
a) it makes use of an external or random value. (It stops being entirely contained and predictable.)
b) It performs an external operation, in other words it causes side effects.

 
var x = 5;
function addToX(a) {
return a+x; / Use of an external variable
}

Example: A complete reducer with tests (can use a library for this like Expect.js).

You might be interested in:

First look to javascript unit test framework – ExpectJs

 

const counter = (state = 0, action) => {

  switch (action.type) {
    case 'INCREMENT':
      return state + 1;
      
    case 'DECREMENT':
      return state - 1;
      
    default:
      return state;
  }
}

expect(
  counter(0, {type: 'INCREMENT'})
).toEqual(1);

expect(
  counter(1, {type: 'INCREMENT'})
).toEqual(2);

expect(
  counter(2, {type: 'DECREMENT'})
).toEqual(1);

expect(
  counter(1, {type: 'DECREMENT'})
).toEqual(0);

expect(
  counter(1, {type: 'DECREMENT Else'})
).toEqual(1);


expect(
  counter(undefined, {})
).toEqual(0);

console.log('Tests passed!');

Why would I need to use Redux? (extracted from this article)

Predictability of outcome:
There is always one source of truth, the store, with no confusion about how to sync the current state with actions and other parts of the application.
Maintainability:
Having a predictable outcome and strict structure makes the code easier to maintain.
Organization:
Redux is stricter about how code should be organized, which makes code more consistent and easier for a team to work with.
Server rendering:
This is very useful, especially for the initial render, making for a better user experience or search engine optimization. Just pass the store created on the server to the client side.
Developer tools:
Developers can track everything going on in the app in real time, from actions to state changes.
Community and ecosystem:
This is a huge plus whenever you’re learning or using any library or framework. Having a community behind Redux makes it even more appealing to use.
Ease of testing:
The first rule of writing testable code is to write small functions that do only one thing and that are independent. Redux’s code is mostly functions that are just that: small, pure and isolated.
Pure functions:
return a new value based on arguments passed to them. They don’t modify existing objects; instead, they return a new one. These functions don’t rely on the state they’re called from, and they return only one and the same result for any provided argument. For this reason, they are very predictable.
Because pure functions don’t modify any values, they don’t have any impact on the scope or any observable side effects, and that means a developer can focus only on the values that the pure function returns.

CONCLUSION

Redux has a growing popularity and is even bigger every day. Companies like Uber and Twitter and projects like WordPress are using it successfully in production. Redux isn’t a perfect fit for everything but we recommend to check it out. If you are up to it you can deep your knowledge over here, a tutorial from the Redux creator and see this example contains source code of Todo List app using Redux with React.

How to copy to clipboard using JavaScript

It is amazing how modern browsers had evolved, and how powerful they became we got to a point where we don't need flash anymore.
A time ago the only way to copy to browser’s clipboard was from a button in the app using Flash, but with modern browsers we can achieve copy to clipboard using javascript, without using any plugin. First, let’s set the ground of what the clipboard is...

copy to clipboard using JavaScript

The clipboard is basically a place for storing and retrieving a single piece of cloned data, by data means from a simple string to a whole directory. There can be more than one clipboard present, for example, the “operative system clipboard”, it would be less difficult if all the applications were able/created to use the operative system clipboard, but unfortunately this is not always the case. For example, virtual machines, unless you explicitly turn on a clipboard integration option.
Following the same behavior are the web apps. Web applications runs in a sandbox environment, it restricts access to file system and the system clipboard, for security reasons. This article expose why the system clipboard is a restricted resource.
Fortunately, there ways to bypass those restrictions and gain access to system clipboard using JavaScript. This is post is about show several ways to do it.

Copy to clipboard using JavaScript

Example 1 (vanilla JavaScript):

This solution is a simple one but has some drawback because you must add an <input> or <textarea> element with the text to be copied to the DOM. The command used 'execCommand' allows us to execute other commands like cut, copy or paste.

The input or textarea to receive text you want to copy:

 
<input name="exampleClipboard" placeholder="Insert the text you want to copy" value="Example text" tabindex="1" autocomplete="off" maxlength="240" style="width:200px" type="text">
<p>
  <button id="copy">
    Copy text
  </button>
</p>
<p>
Right click paste or Ctr + v after click Copytext button <br/>
<textarea></textarea>
</p>

The function to call:

 

<script>
function copyToClipboard() {
document.querySelector('input').select();
document.execCommand('copy');}
</script>

The button:

 
<button id="howToCopyClipboard" onclick="copyToClipboard()">Copy</button

*You can change the input label for a textarea if you want. Keep in mind that this solution forces you to keep a maybe non desire input or textarea element in your page.

 
Try yourself

Example 2 (vanilla JavaScript):

This is a more elaborated solution where we validate compatibility with browsers. For this solution lets create a function that copies a string to the clipboard, this function must be called from within an event handler such as click. More reference to this method can be found here you can see a practical example here.

 

function copyToClipboard(text) {

if (window.clipboardData && window.clipboardData.setData) {
 // IE specific code path to prevent textarea being shown while dialog is visible.

return clipboardData.setData("Text", text); 

} 

else if (document.queryCommandSupported && document.queryCommandSupported("copy")) {
        var textarea = document.createElement("textarea");
        textarea.textContent = text;
        textarea.style.position = "fixed";  // Prevent scrolling to bottom of page in MS Edge.
        document.body.appendChild(textarea);
        textarea.select();
        try {
            return document.execCommand("copy"); // Security exception may be thrown by some browsers.
        } catch (ex) {
            console.warn("Copy to clipboard failed.", ex);
            return false;
        } finally {
            document.body.removeChild(textarea);
        }
    }
}

Example 3 (with a library): Clipboard js

It would be overwhelm to have to write validations for browser compatibility, etc, so Lets avoid reinvent the wheel and use a library that manages all this for you. ClipboardJs is very easy to use, here is an example:

 
<!-- Target -->

<input id="textToCopy" value="Any text you want to copy">

 

 

<!-- Trigger -->

<button class="btn" data-clipboard-target="#textToCopy">Copy to clipboard
</button>

Notice that

 data-clipboard-target 

do the job here. Let’s see another feature but this time is to cut instead of copy.
The only change needed is to add

 data-clipboard-action="cut"> 

like this:

  
<textarea id="textToCopy">Another feature … </textarea>
  
<!-- Trigger -->
<button class="btn" data-clipboard-action="cut" data-clipboard-target="#textToCopy">
    Cut to clipboard
</button>

More reference about this useful library can be found here.

Try yourself

At the end there isn’t universal solution to this task, out there are a lot of solutions in many different ways with just JavaScript (or JavaScript libraries without involving Flash), feel free to use the most suited for you.

First look to javascript unit test framework – ExpectJs

Today I going to write about javascript unit test frameworks, to be more specific, about Expectjs.
Sometimes web developers ignores the action of testing their code, automated, just because it works in
some random manual attempts. Just a reduced number of developers really like the activity of write unit test because of the security and the mind peace it brings to any development process.
This time let’s take a look at ExpectJS, a minimalistic BDD assertion toolkit based on should.js that
provides very useful features to developers in order to test their codes through unit test. But how it
works exactly? In this post I’d like to expose the main features and APIs of this amassing library.
 
javascript unit test framework

Two definitions before go to the main topic: Assertions + Unit Testing with ExpectJs

Basically an assertion is a statement where a Boolean-valued function is expected to be true at that
point in the code. If the assertion evaluates to false in some point of the execution, it will throw an
assertion exception. For example:

 
function assert(condition, message) {
    if (!condition) {
        throw message || "Assertion failed";
    }
}
 

In the other hand, a unit test checks blocks of code to ensure that they all run as expected. Simple JavaScript unit test will take a function, monitor output and return its behavior, and assertions are used in the process. Sometimes this task is not so easy with vanilla JavaScript.

Other javascript unit test frameworks

There are other options. Out there are plenty of javascript unit test frameworks like QUnit, Sinon, Mocha or Jasmin, all of them are able to integrate assertions libraries like ExpectJS.

Let's get starting with ExpectJS

How to install it.
 
Node
Install it with NPM or add it to your package.json:
$npm install expect.js
Then you can use the following code:

var expect = require('expect.js');

Browser

<!-- download the file to your local -->
<script src="expect.js"></script>

<!-- from a CDN -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/expect.js/0.2.0/expect.js">
</script>

 

Main features

- Cross-browser: works on IE6+, Firefox, Safari, Chrome, Opera.
- Compatible with all test frameworks.
- Node.JS ready (require('expect.js')).
- Standalone. Single global with no prototype extensions or shims.

Our first test

Let’s say we want to test the following add function:

function add(a, b) {
return a – b; 
};

expect(add).to.be.a('function');  // this assertion passes
expect(add(1, 3)).to.equal(4);  // this assertion fail
expect(add(5, 2)).to.be.lessThan(8); // this assertion passes

Now, notice that if we execute this code, and we check the console of the browser you'll see an error for the assertion that failed (the second one).

 
Try it yourself

The previous approache is not too intuitive, so lets wrap it up with a framework that offers a more visual result, lets use MochaJs:

Comparing with other assertion test frameworks

Differences with should.js
- No need for static shouldjs methods like should.strictEqual(). For example, expect(obj).to.be(undefined) works well. More intuitive now!
- Some API simplifications/changes.
- API changes related to browser compatibility.

Let’s see how intuitive the ExpectJS API’s can be.

Example 1: a/an: asserts typeof with support for array type and instanceof (used with mocha testing framework)

describe("Example 1", function() {

 var n;
 var cars;

it("number check", function() {
    n = 'good';
    expect(n).to.be.a('number');
  });


  it("array and object check", function() {
    cars =['Mercedes', 'Toyota', '4x4'];
  
   expect(cars).to.be.an('array'); // it works
   expect(cars).to.be.an('object'); // it Works too since it supports typeof
  });
});

Example 2: match: asserts String regular expression match. We can use useful regular expressions like this:

describe("Regular expressions check", function() {
 var version;
it("version check", function() {
    n = '4.8.2';
    expect(version).to.match(/[0-8]+\.[0-8]+\.[0-8]+/);
  });
});

Try it yourself

Other resources the API provides:

ok: asserts that the value is truthy or not.

expect(1).to.be.ok();

eql: asserts loose equality that works with objects.

expect({ a: 'b' }).to.eql({ a: 'b' });

contain: asserts indexOf for an array or string.

expect([1, 2]).to.contain(1);

length: asserts array .length.

expect([]).to.have.length(0);

empty: asserts that an array is empty or not.

expect([]).to.be.empty();

property: asserts presence of an own property (and value optionally).

expect(window).to.have.property('expect')

key/keys: asserts the presence of a key. Supports the only modifier.

expect({ a: 'b' }).to.have.key('a');

throw/throwException/throwError: asserts that the Function throws or not when called.

expect(fn).to.throw(); // synonym of throwException.

withArgs: creates anonymous function to call fn with arguments.

expect(fn).withArgs(invalid, arg).to.throwException();

within: asserts a number within a range.

expect(1).to.be.within(0, 100);

greaterThan/above: asserts.

expect(3).to.be.above(0);

lessThan/below: asserts.

expect(0).to.be.below(3);

fail: explicitly forces failure. (This is very helpful sometimes).

expect().fail()

How to use it with spies.

A way to verify the function behavior in unit test is through the use of spies. A spy allows you to monitor a function exposing options to track invocation counts, arguments and return values. The main principle here is that it replaces a particular function where you want to control its behavior in a test, and record how that function is used during the execution of that test (similar to how actors are replaced with stunt doubles for dangerous action scenes in Hollywood movies).

Let’s see how it works: (Other examples can be found here)

spyOn(foo, 'bar');  // Here the spyOn method takes an object and a method to be spied upon.
foo.bar(1);         // Call the function
 
expect(foo.bar).toHaveBeenCalled(); // Run assertions with ExpectJS.
expect(foo.bar).toHaveBeenCalledWith(1);

Final considerations.

ExpectJS is a very useful assertion library and combined with other javascript unit test frameworks can be very visual and can save a lot of time while provide security to your code. Other libraries similar are Chai, should.js, and better-assert. One of the advantages is that it is Standalone and can be integrated with any javascript unit test frameworks.

References:

https://github.com/Automattic/expect.js/blob/master/README.md
https://abdulapopoola.com/2016/04/11/how-function-spies-work-in-javascript/
https://designmodo.com/test-javascript-unit/

TinyMCE Validating length AngularJs

 
 

I'm creating this "how to..." tutorial based on my experience working with TinyMCE Validating length with Angularjs, and the answers I found in the internet community Stack overflow and github.

What is TinyMce:

It is an opensource WYSIWYG (What You See Is What You Get) HTML editor designed to simplify website content creation. In other words it is a rich text web editor. This is the official website https://www.tinymce.com/

TinyMCE Validating length

TinyMCE Validating length using AngularJs

For the first example I used TinyMCE v4.3.3 with angular-ui-tinymce v0.0.12 plugin and AngularJS v1.4.6.

In the AngularJs controller we have to set the config options, and in the view we use a textarea with the parameter ui-tinymce="tinymceOptions"


angular.module('myApp', ['ui.tinymce'])
.controller('myCtrl', ['$scope', function($scope) {
    
//set the config options
 $scope.tinymceOptions = {
                    plugins: 'code',
                    toolbar: 'undo redo | bold italic | styleselect | code',
                    menubar: false,
                    forced_root_block: false
                };
// ...
}]);

 
 

<textarea ui-tinymce="tinymceOptions" ng-maxlength="100" 
name="editor" ng-model="vm.editor">
</textarea>
<span ng-show="form.editor.$error.maxlength" class="error">
    100 character limit reached!
</span>

 
 
The code above will not work as it is, because of a known bug https://github.com/angular-ui/ui-tinymce/issues/145

Work around

Took from StackOverflow
One work around can be to disable SCE mode with this code .config(['$sceProvider', function($sceProvider) {
$sceProvider.enabled(false);
}])
but...

Beware of security vulnerabilities!

Strict Contextual Escaping (SCE) is a mode in which AngularJS requires bindings in certain contexts to result in a value that is marked as safe to use for that context. With SCE disabled, an AngularJS application allows to render arbitrary HTML into the div, and rendering user controlled input creates security vulnerabilities.

 
 

angular.module('myApp', ['ui.tinymce'])
.config(['$sceProvider', function($sceProvider) {
    $sceProvider.enabled(false);
}])
.controller('myCtrl', ['$scope', function($scope) {
    
//set the config options
 $scope.tinymceOptions = {
                    plugins: 'code',
                    toolbar: 'undo redo | bold italic | styleselect | code',
                    menubar: false,
                    forced_root_block: false
                };
// ...
}]);

 
 
Here is the JsFiddle https://jsfiddle.net/naXa/zsnLupvd/

Another work arround

This is a directive written by @andresmatasuares for TinyMCE Validating length with AngularJs.

app.directive('plainTextMaxLength', function($filter) {
    return {
      restrict: 'A',
      require: 'ngModel',
      link: function(scope, element, attributes, ngModel) {
        var maxLength, validPlainTextLength;
        validPlainTextLength = function(v) {
          if (!v) {
            return true;
          }
          return stripHtmlTags(v).length <= maxLength;
        };
        maxLength = void 0;
        scope.$watch(attributes.plainTextMaxLength, function(newValue, oldValue) {
          if (maxLength !== newValue) {
            maxLength = newValue;
            return ngModel.$validate();
          }
        });
        return ngModel.$validators['plainTextMaxLength'] = function(modelValue, viewValue) {
          if (viewValue.$$unwrapTrustedValue) {
            return validPlainTextLength(viewValue.$$unwrapTrustedValue());
          } else {
            return validPlainTextLength(viewValue);
          }
        };
        
      }
    };
  });

 
Here you can find the plunker code http://plnkr.co/edit/oAZcHZAmCXYOTckJCPcs?p=preview

Styling External Links in your site with CSS

Are you looking for an easy way to style and denote external links in your web site or blog, it is always good for the user to know when they are going to navigate away from your page, enriching the user experience. Perhaps most of the sites out there achieve this by placing code on the Back End. Here I going to share with you what I found on this topic, and how to do it just using CSS.

Clicking on external links, navigating away..

denote external links

We are going to use CSS selector to apply styles to all the "a" (anchors) except for internal links. This is translated into code like this:

a[href*="//"]:not([href*="mywebsite.com"]) {
    /* css code here  */
}

 

Notice that we combined the selector with some regular expression, the * mean select all elements, for a full list of selectors, you can visit:
http://www.w3schools.com/cssref/css_selectors.asp

Now, you can combine this selector with the ::after of the <a> element to include for example an icon that might looks like the externals links on Wikipedia.
(from http://www.w3schools.com/)
after browser suport

Although Wikipedia doesn't use this approach, they use a class instead to insert the icon at the end of the external links, this should be done manually. With the method exposed here all the externals links will be styled automatically when the page loads.
external links wikipedia

 

book

Book Tip

CSS Mastery
Fully updated to the latest CSS modules, make the journey to CSS mastery as simple and painless as possible. This book dives into advanced aspects of CSS-based design, such as responsive design, modular CSS, and CSS typography. Through a series of easy-to-follow tutorials, you will learn practical CSS techniques you can immediately start using in your daily work.
Amazon

 

Here is a working example of how all the external links are decorated with the Wikipedia's external link icon

a[href*="//"]:not([href*="example.com"]):after {
    margin-left: 3px;
    content: url(data:image/svg+xml,%3C%3Fxml%20version%3D%221.0%22%20encoding%3D%22UTF-8%22%20standalone%3D%22no%22%3F%3E%3Csvg%20xmlns%3D%22
http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2212%22%20height%3D%2212%22%3E%3Cpath%20fill%3D%22%23fff%22%20stroke%3D%22%2306c%22%20d%3D%22M1.5
%204.518h5.982V10.5H1.5z%22%2F%3E%3Cpath%20d%3D%22M5.765%201H11v5.39L9.427%207.937l-1.31-1.31L5.393%209.35l-2.69-2.688%202.81-2.808L4.2%202.544z%22
%20fill%3D%22%2306f%22%2F%3E%3Cpath%20d%3D%22M9.995%202.004l.022%204.885L8.2%205.07%205.32%207.95%204.09%206.723l2.882-2.88-1.85-1.852z%22%20fill%3D
%22%23fff%22%2F%3E%3C%2Fsvg%3E)
    }

Also you can denotate all the links that navigate away from your page even internal links that get open in another tab or windows:

:not compatibility

One last thing to keep in mind when you use this approach is the browser compatibility with the :not css selector, for example Internet Explorer starting supporting it from version 9:
(from http://www.w3schools.com)
not css selector browser compatibility

Ultimately, for the no compatible browsers you can detect the browser version with JavaScript or Jquery and then select all the external links and apply the style using JavaScript code:
Jquery Example:

$(function() {
  $('a').each(function(i, e) {
    if ($(e).attr("href") && ($(e).attr("href").indexOf("http://") > -1 || $(e).attr("href").indexOf("https://") > -1)) {
      $(e).css({
        "background-image": "linear-gradient(transparent,transparent),url(data:image/svg+xml,%3C%3Fxml%20version%3D%221.0%22%20encoding%3D%22UTF-8%22%20standalone%3D%22no%22%3F%3E%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2212%22%20height%3D%2212%22%3E%3Cpath%20fill%3D%22%23fff%22%20stroke%3D%22%2306c%22%20d%3D%22M1.5%204.518h5.982V10.5H1.5z%22%2F%3E%3Cpath%20d%3D%22M5.765%201H11v5.39L9.427%207.937l-1.31-1.31L5.393%209.35l-2.69-2.688%202.81-2.808L4.2%202.544z%22%20fill%3D%22%2306f%22%2F%3E%3Cpath%20d%3D%22M9.995%202.004l.022%204.885L8.2%205.07%205.32%207.95%204.09%206.723l2.882-2.88-1.85-1.852z%22%20fill%3D%22%23fff%22%2F%3E%3C%2Fsvg%3E)",
        "background-repeat": "no-repeat",
        "padding-right": "13px"
      });
    }
  });
});

 

Working example:

CSS Tooltip, without JavaScript or Jquery

In this article I'm going to explore how to Create css tooltip, without using JavaScript or JQuery plugins.

css tooltip

Tooltips

Tooltips are great artifact to complement/enrich the user experience providing hint and more information to the user. There are a lots of JavaScript plugins that provides this functionality, but if you don’t feel like adding that weight to your site, adding more files and more JavaScript code, we can take care of it just using plain CSS.
As an alternative we can use the HTML title attribute to effectively accomplish the same solution, but you can’t style the tooltip to your liking.
Sometimes I prefer to use CSS alternatives to common JavaScript interactions when I’m developing specially when I'm developing prototypes. There are some projects where downloading a plugin or creating a new file for a few lines of code seems like overkill.

Here is a working example:

Hover over this

 

Creating a Css Tooltip

To create our tooltip just using css, we are going to take advantage of the ::before and ::after selector, we are going to use the ::before for the tooltip body and the ::after for the littler arrow. We are going to set the Tooltip content with data-tooltip parameter of the html element.

 <span class="tooltip-toggle" data-tooltip="Sample text for your tooltip!">
     Hover over this
 </span>

 

book

Book Tip

CSS Mastery
Fully updated to the latest CSS modules, make the journey to CSS mastery as simple and painless as possible. This book dives into advanced aspects of CSS-based design, such as responsive design, modular CSS, and CSS typography.

Amazon

 

 

Definition and Usage.

::after selector inserts something after the content of each selected element(s).
You can use the content property to specify the content to insert. This property can be combined with the attr() attribute to get the text from an html atribute.
::before selector inserts something before the content.
Example:

.tooltip-toggle::before {
  position: absolute;
  top: -80px;
  left: -80px;
  background-color: green;
  border-radius: 5px;
  color: #fff;
  content: attr(data-tooltip);
  padding: 1rem;
  text-transform: none;
  -webkit-transition: all 0.5s ease;
  transition: all 0.5s ease;
  width: 160px;

.tooltip-toggle::after {
  position: absolute;
  top: -12px;
  left: 9px;
  border-left: 5px solid transparent;
  border-right: 5px solid transparent;
  border-top: 5px solid green;
  content: " ";
  font-size: 0;
  line-height: 0;
  margin-left: -5px;
  width: 0;
}
}

With the :hover we can show/hide the tooltip as a transition:

.tooltip-toggle:hover::before,
.tooltip-toggle:hover::after {
  opacity: 1;
  -webkit-transition: all 0.75s ease;
  transition: all 0.75s ease;
}

.tooltip-toggle::before,
.tooltip-toggle::after {
  color: #efefef;
  font-family: monospace;
  font-size: 16px;
  opacity: 0;
  pointer-events: none;
  text-align: center;
}

Here is the full code example of the css tooltip:

Interview Question

You can also use this article as reference to create css interview questions for a seasoned front-end developer, to validate the deep experience on using, formating the ::before and ::after elements.

Arrays as Multipurpose Data Structures in JavaScript

In JavaScript the Array object is a very powerful data structure with it you can "simulate" other data structures, like Queues, Stacks, List, etc.

There is a list with some of the most important methods of the array object in JavaScript, we going to use them to create/simulate our data structures, you can see example of these methods in action, below.

Array.push(value1, value2, value3,…) – Add one or more Elements to the end of the array. This method will return the new length of it. You can specify multiple comma separated values.
Array.pop() – Removes the last element from an array and returns it.
Array.unshift(value1, value2, value3,…) – Add one or more elements to the beginning of the array. This method will return the new array length. You can specify multiple comma separated values.
Array.shift() – Removes the first element from an array and returns it.
Array.splice(splice(start, deleteCount[, item1[, item2[, ...]]])) - The splice() method changes the content of an array by removing existing elements and/or adding new elements.

Data Structures array

Other useful methods.

We are not going to use this methods to create the data structures showed in this post, but it might be handy.

Array.reverse() – Reverses the order by position (the first element becomes the last and the last one becomes the first, etc).

var arr = ['a', 'b', 'c'];
arr.reverse();
console.log(arr); //this will display ["c", "b", "a"]

Array.sort([compareFunction]) – Allows you to sort an array by specifying a compare function which has access to each value in the array you want to sort.

var arr = ['d', 'e', 'b', 'c', 'a'];
arr.sort(function(a, b){
  if (a < b) { return -1; } if (a > b){ return 1; }
  // a must be equal to b
  return 0;
});
console.log(arr); //this will display ["a", "b", "c", "d", "e"]
//Note: for this simple sort you can do arr.sort(), an you'll obtain the same result.

Array.join(separator) – This method takes one or more items in the array and returns a string of values joined by their separator. If you don’t specify a separator, the default is a comma.

var arr = ['a', 'b', 'c'];
var str = arr.join('-');
console.log(str); //this will display "c-b-a"

Array.indexOf(value) – This method allows you to find the first occurrence of the specified value, or –1 if not found.

var arr = ['a', 'b', 'c'];
if(arr.indexOf("a") > -1)
console.log('found "a" in arr');

 

book

Book Tip

Speaking JavaScript: An In-Depth Guide for Programmers
Like it or not, JavaScript is everywhere these days—from browser to server to mobile—and now you, too, need to learn the language or dive deeper than you have. This concise book guides you into and through JavaScript, written by a veteran programmer who once found himself in the same position.

Amazon

 

 

Data Structures

  • Arrays used as Queue

  • Arrays used as Stack

  • Arrays used as List

 

Arrays as Queue:

A queue follows the First-In First-Out (FIFO) paradigm: the first item added will be the first item removed. An array can be turned into a queue by using the push() and shift() methods. push() inserts the passed argument at the end of the array, and shift() removes and returns the first item, consider the following example:

function Queue(length) {
    var ret = [];

    ret.enqueue = function(a) {
        if(ret.length == length){
             ret.shift();
        }
        return Array.prototype.push.apply(this, arguments);
    };
    ret.dequeue = function(){
        return Array.prototype.shift.apply(this);
    }
    return ret;
}

var aux = Queue(3);
aux.enqueue('cat');
aux.enqueue('dog');
aux.enqueue('duc');
aux.enqueue('worm');
console.log(aux); // should contain dog, duc, worm
aux.dequeue();
console.log(aux);

Arrays used as Stack.

A stack follows the Last-In First-Out (LIFO) paradigm: an item added last will be removed first. The Array class has 2 methods that provide stack functionality. they are push() and pop(). push() appends an item to the end of the array, and pop() removes and returns the last item in the array
push(data) adds data.

pop() removes the most recently added data.

function Stack() {
    var ret = [];

    ret.push = function(a) {
        return Array.prototype.push.apply(this, arguments);
    };
    
    ret.pop = function(){
        return Array.prototype.pop.apply(this);
    }

    return ret;
}

var stack= Stack();
stack.push("A");
stack.push("B");
stack.push("C");
console.log(stack);
stack.pop();
console.log(stack);

Arrays used as List.

A List a collection of unsorted elements, where you can add or remove elements.

function List() {
    var ret = [];
    ret.add = function(element) {
        return Array.prototype.push.apply(this, arguments);
    };
    ret.remove = function(element){
        return Array.prototype.slice.apply(this, ret.splice(ret.indexOf(element), 1));
    }
    return ret;
}

var aux = List();
aux.add('cat');
aux.add('dog');
aux.add('duc');
aux.add('worm');
console.log(aux); 
aux.remove('dog');
console.log(aux);

Wrapping up:

As you can see the those three data structures queue, stack and list are simple arrays wrapped in a function to rename the methods used to add or remove elements from the collections with more semantic names. If you have any enhancement or any subjection please don't hesitate to share with us.

References to learn more:

developer.mozilla.org - Arrays

Closure in JavaScript through examples

javascript closureWhat is Closure?

A Closure is a named or anonymous function defined within the context of an object or any other function, which preserves and access to the context where it was declared.

To understand closure, it requires you to be familiar with basic JavaScript concepts, such as scope of variables and functions.

A closure is a named or anonymous function:
javascript closure
This is not a closure:

//Named function
function greetings() { //this is not a closure function.
    return ‘Howdy’;
}

//anonimous function
var greetings2 = function () { //this is not a closure function.
    return ‘Hello’;
}

greetings(); //Shows Howdy.
greetings2(); //Shows Hello.

Basically a closure function is a function that can access to the variables declared in the outer context, including global variables.

 

book

Book Tip

Speaking JavaScript: An In-Depth Guide for Programmers
Like it or not, JavaScript is everywhere these days—from browser to server to mobile—and now you, too, need to learn the language or dive deeper than you have. This concise book guides you into and through JavaScript, written by a veteran programmer who once found himself in the same position.

Amazon

 

Closures in action.

Here is an example that will help you recognize when you need to use a Closure.

How to do it correctly.

Suppose you want to use a variable to count and want to create a function to increment the count variable.

var counter = 0;
function increase() {
    counter += 1;  // increment its current value.
    console.log(counter);
}

increase();
increase();
increase();

 // The counter is now equal to 3.

Here we have a solution, but has flaws; the counter variable is global, any script on the page would have access to it and could change it without calling the increase function .

We need to make sure that the counter variable is only modified by the increase function.

Therefore, move the definition of the variable inside the function, so no one can modify it without calling the function increase:

function increase() {
    var counter = 0;
    counter += 1; // increment its current value.
    console.log(counter);
}

increase();
increase();
increase();

// We expect the value of the count variable is 3, but it will be 1.

Now the counter variable is not accessible from the outside (now is protected), but this wong work properly because every time you call the function it will define the variable account.

We need to create an internal function to solve this:

var increase = (function() {
    var counter = 0;
    return function () {
        return counter += 1;
    }
 console.log(counter);
})(); //* IIFE Auto-invoked function.

increase();
increase();
increase();

// The counter is now equal to 3.

*IIFE Immediately Invoked Function Expression (see Encapsulation in JavaScript).

A common mistake

Here's an example of misuse of Closure function. Suppose we have the following code:

function count() {
     var i;
     for (i = 1; i <= 3; i ++) {
         setTimeout (function () {
             console.log ('The count value is '+ i);
         }, 1000); // 1000 milliseconds = 1 second
     }
}
count();

And this is how you can solve it:

function count() {
     var i;
     function display(j) {
         return function () {
             console.log ('The counter value is ' + j);
         }
     };

     for (i = 1; i <= 3; i ++) {
         setTimeout (display(i), 1000);
     }

}
count();

I'm not going to explain in detail how this is solved, I'll leave it to you, if you understand what happened then you understand JavaScript closure. 😉

Other references:

https://developer.mozilla.org/es/docs/Web/JavaScript/Closures
http://javascriptissexy.com/understand-javascript-closures-with-ease/
http://www.w3schools.com/js/js_function_closures.asp

Basics Browser Console Object API

Browser console API

This article will be focused in the console object API available in Google Chrome, Mozilla Firefox, and later versions of Internet Explorer browser. We are going to cover few of them in this article, for a full list of available commands go to the References section at the bottom of this article .

The Console object is available in two places: the code and the browser's JavaScript Console.
You probably already know of console.log in my opinion this is the most used command of the console object.

  • console.log

    – For basic logging, Use this to print in the browser's console general string messages about actions taking place within the code, also you can print Objects, Arrays, etc..
    e.g:

    console.log("simple text"); //simple text
    
    var str = 'World';
    console.log("Hello", str); //Hello World
    
    var arr = ['val1','val2','val3','val4'];
    console.log(arr); //["val1", "val2", "val3", "val4"]
    
    var userName = 'jomendez'
    console.log("Authenticating user '%s'", userName); //Authenticating user jomendez
    

 

  • console.error

    – For logging errors in your code. I use console.error within error callbacks on AJAX requests and anywhere else an error might be thrown like a try{}...catch{}. While similar to console.log, this method also includes a stack trace where the error was thrown.
    javascript browser console error

 

     

    book

    Book Tip

    Speaking JavaScript: An In-Depth Guide for Programmers
    Like it or not, JavaScript is everywhere these days—from browser to server to mobile—and now you, too, need to learn the language or dive deeper than you have. This concise book guides you into and through JavaScript, written by a veteran programmer who once found himself in the same position.

    Amazon

     

  • console.dir(object)

    – When you log a DOM element to the console it displays in an HTML format. To display the JavaScript representation you may  use the dir() method
    browser console dir

  • console.group(title)

    – This command is used to create a group of console logging commands it accepts an optional title parameter. To end the grouping just call grouEnd() see below.

    var userName = "jomendez", authenticated = false;
    console.group("Authentication phase");
    console.log("Authenticating user '%s'", userName);
    // place your authentication code here...
    if (!authenticated) {
      console.log("User '%s' is not authenticated.", userName)
    }
    console.groupEnd();
    

    browser console group

 

  • console.groupCollapsed()

    – Exactly the same as the above method, except for the fact the initial group is collapsed and not opened.

 

  • console.groupEnd()

    – This allows you to end the group defined above.

 

  • console.time(label)

    – The console.time() help you to measuring how long a portion of code can take to be excecuted, you must pass a string to the method to identify the time marker. When you want to end the measurement call console.timeEnd() and pass it the same string passed to the initializer. The console logs the label and time elapsed when the console.timeEnd() method fires.

    console.time("Measure Array");
        var array= new Array(1000000);
        for (var i = array.length - 1; i &gt;= 0; i--) {
            array[i] = new Object();
        };
    console.timeEnd("Measure Array");
    

    Result:
    Measure Array: 1923.457ms

 

  • console.timeEnd(label)

    –This allows you to stop the timer logging function and the elapsed time will be printed out,  see the code above.

 

  • console.table()

    - You can use console.table() to View structured data. With this you can view arrays objects, etc.

    function Person(firstName, lastName, age) {
      this.firstName = firstName;
      this.lastName = lastName;
      this.age = age;
    }
    
    var family = {};
    family.mother = new Person("Susan", "Doyle", 32);
    family.father = new Person("John", "Doyle", 33);
    family.daughter = new Person("Lily", "Doyle", 5);
    family.son = new Person("Mike", "Doyle", 8);
    
    console.table(family);
    

    browser console table

 

  •  console.clear()

    - You can use the console.clear() command to clear the browser console.

 

References:

You can find a full list for the console api for the most popular browsers, NodeJs and Firebug:
Chrome: http://developers.google.com/chrome-developer-tools/docs/console-api/
Firebug: http://getfirebug.com/wiki/index.php/Console_API
Firefox: http://developer.mozilla.org/en-US/docs/Web/API/console
Internet Explorer: http://msdn.microsoft.com/en-us/library/ie/hh772183.aspx
Node.js: https://nodejs.org/api/console.html
Safari: http://developer.apple.com/library/safari/documentation/AppleApplications/Conceptual/ Safari_Developer_Guide/Console/Console.html

Notes:

There is bug in Internet Explorer 9 where the console object is only defined if the developer tools were open at least once. That means that you get a Reference Error if you refer to console and the developer tools weren’t open before. As a work around, you can check if the console object exists before you call it.