Archives For javascript

I was getting annoyed that my Emmet shortcuts were not working in Atom when I’m writing React/JSX files. None of the Emmet shorthands were expanding, until I found this bit of information.

Making Emmet shortcuts work for JSX files in Atom

  1. Open Atom menu -> Keymap…
  2. Add this line to the keymap file

    atom-text-editor[data-grammar=”source js jsx”]:not([mini])’: ‘tab’: ’emmet:expand-abbreviation-with-tab

This will expand .col-sm-8 to

<div className="col-sm-8"></div>

Scale Value with Javascript

I was looking for a quick and easy way to get a scale value of a css -webkit-transform with javascript.

The html and css:

<div id="transformed"></div>

#transform {
    -webkit-transform: scale(.8);
}

First, we need to get the property value of -webkit-transform. I’ll use jQuery.

var div = $('#transform').css('transform');

The transform property will return matrix(0.8, 0, 0, 0.8, 0, 0).

To get the scale from the matrix, we will need to turn the matrix into individual values, then we can do math:
var values = div.split(‘(‘)[1];
values = values.split(‘)’)[0];
values = values.split(‘,’);

var a = values[0];
var b = values[1];

var scale = Math.sqrt(a*a + b*b);
console.log(scale) // .80

Detect OSX or Windows with Javascript

We can easily detect whether client’s machine is PC or Mac with Javascript.
We can just analyze the value of navigator.appVersion or navigator.userAgent. Be careful, some clients will spoof the userAgent.

// Javascript code for OSX or Windows detection
var OSName="Unknown OS";
if (navigator.appVersion.indexOf("Win")!=-1) OSName="Windows";
if (navigator.appVersion.indexOf("Mac")!=-1) OSName="MacOS";

document.write('Your OS: '+OSName);

Regex Password Validation

I needed to find a regex pattern for validating a password for an Angular app.
The requirement were to have at least 1 lowercase character, 1 uppercase character, 1 number, and no repeating character more than 2. For the ng-pattern, I came up with is below

/^(?!.*([A-Za-z0-9])\1{2})(?=.*[a-z])(?=.*[A-Z])(?=.*\d).+$/

Breaking It Down

(?!.*([A-Za-z0-9])\1{2}) Make sure that no characters repeat more than twice

(?=.*[a-z]) requires at least one lowercase

(?=.*[A-Z]) requires at least one uppercase

(?=.*\d) requires at least one digit

Problem
In jQuery, getting a numeric property returns a string.
What if we want a css property value as an integer or float?

Solution

parseInt($('#elem').css('top'));
parseFloat($('#elem').css('top'));

In Part 1, we set up gulpjs and browser-sync to build a static site generator.
In this part, we will set up a template engine called Nunjucks and set up a base template.

Installing Plugins

Let’s start by installing the plugins in our project. In our command line, type the following.

$ npm install --save-dev gulp-nunjucks-render

About Nunjucks

Nunjucks allows us to break our html into smaller reusable pieces that we can use in other html files. We can even inject data to populate our html files. If you have used Flask, you’ll notice the markup is inspired by Jinja2.

Creating a Template

We’ll copy our app/index.html file to app/templates/base.html.
Then, we’ll make a pages directory and move the index.html to app/pages/index.html

$ cp app/index.html app/templates/base.html
$ mv app/index.html app/pages/index.html
  Folder Structure
├── app
│   └── templates
│       └── base.html
|   └── pages
│       └── index.html
├── gulpfile.js

We’ll change the markup for base.html to become a Nunjucks template.

<!-- base.html -->
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>
      {% block title %} {% endblock %} <!-- we'll change the title -->
    </title>

    <!-- Bootstrap -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
  </head>

  <body>

    <div class="container container-fluid">
      {% block content %} <!--- Our content will be here -->
      {% endblock %}
    </div>

    <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <!-- Include all compiled plugins (below), or include individual files as needed -->
    <!-- Latest compiled and minified JavaScript -->
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
  </body>
</html>

Let’s change the index.html to take advantage of our new base.html nunjucks template.

<!-- index.html -->
{% extends "base.html" %} <!-- we're extending the base template -->

{% block title %}This is the new title of our webpage{% endblock %}

{% block content %}
<h1>Hello<h1>
<p>
  We just extended the base template. Anything we put in the content blocks will
  be specific to the index.html page.
</p>
{% endblock %}

Integrating Gulpjs and Nunjucks

Now that we have our template and pages file ready.
We’ll import the plugin and write a gulp task for it

// gulpfile.js
var gulp              = require('gulp');
var browserSync       = require('browser-sync');
var nunjucksRender 		= require('gulp-nunjucks-render'); // importing the plugin

gulp.task('serve', function() {
    console.log('running server');
    browserSync({
        server: {
            baseDir: 'app'
        }
    });
});

// writing up the gulp nunjucks task
gulp.task('nunjucks', function() {
  console.log('nunjucking');

  // configuring the templates folder for nunjucks
  nunjucksRender.nunjucks.configure(['app/templates/']);

  // get the pages files
  return gulp.src('app/pages/**/*.+(html)')
    .pipe(nunjucksRender())
    .pipe(gulp.dest('app'))
});

//default task to be run with gulp
gulp.task('default', ['serve']);

Running Nunjucks

Now, we can run the nunjucks task and then the serve task to see our changes.

$ gulp nunjucks
$ gulp serve

Results

Nunjucks took our base template and index file and turned it into a fully compiled html page.
We can make as many pages files as we want and the nunjucks task will compile them into static files.
We can combine the nunjucks and serve commands as another task, but we’ll save it for another tutorial.
You can check out our changes on Github.

I wanted to create a static site without having to copy and paste the header/footer and other common snippets.
There’s lots of tools that would do this including Jekyll (ruby) or Pelican (python), but I wanted something fast and easy to work with.
I figured I could use gulp.js with plugins to create the same type of static site generator as the above two.
Let’s start by installing gulp and browser-sync and creating an index page to display.

Installing Plugins

Let’s start by installing the plugins in our project. In our command line, type the following.

$ npm init
$ npm install gulp browser-sync --save-dev

Folder Structure

Let’s create two folders in our project folder called app/ and a file, gulpfile.js
Our Folder Structure

├── app
├── gulpfile.js

Browser Reloading

We are installing a tool called browser-sync which watches our files and automatically reloads the server, so that we do not need to constantly refresh the page. Let’s edit our gulpfile.js to look like the file below.

// gulpfile.js
var gulp        = require('gulp');
var browserSync = require('browser-sync');

gulp.task('serve', function() {
    browserSync({
        server: {
            baseDir: 'app' // Change this to your web root dir
        }
    });
});

// Default task to be run with `gulp`
gulp.task('default', ['serve']);

The first two ‘var’ lines are importing our plugins. The ‘gulp.task’ functions are running our gulp tasks. One which includes running browser-sync, and the other will default to the first task without any additional command line parameters.

Let’s set up our index page in the app folder. I grabbed the default bootstrap demo site.

<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
    <title>Bootstrap 101 Template</title>

    <!-- Bootstrap -->
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">

    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
      <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
  </head>
  <body>
    <h1>Hello, world!</h1>

    <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <!-- Include all compiled plugins (below), or include individual files as needed -->
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
  </body>
</html>
  Folder Structure
├── app
|    ├── index.html
├── gulpfile.js

Running Commands

In the terminal, run the command ‘gulp’ or ‘gulp serve’ and it should open a browser window with the index.html page shown.
If you leave gulp running and change the index.html page, it will automatically reload and show you your edits.

You can see what we currently have on Github.

Check out Part 2 on building a static site generator with gulp.

Easy orientation change detection for Ionic Apps or mobile web apps.

window.addEventListener("orientationchange", 
    function() {
        if (window.orientation == 90 || window.orientation == -90) {
            alert('landscape mode');
        } else {
            alert('portrait mode;);
        }
    }, false);
function linkify(text) {
    var exp = /(\b((?:https?:\/\/|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’])))/ig;
    var linkedText = text.replace(exp,'<a href="$1" target="_blank">$1</a>');
    // when user puts in 'www' replace it with 'http://www'
    return linkedText.replace('="www.','="http://www.');
}

Sources:
StackOverflow
John Grubber’s RegEx for URL

Three different ways to check if an element exists using a selector in jQuery.

if ($("#mydiv").length > 0){
  // do something here
}

if ($("#mydiv").length){
  // do something here
}

if ($("#mydiv")[0]) {
  // do something
}