Insert Text at Caret Position in Summernote Editor for Bootstrap

Problem

Using the very useful Summernote Editor component for Bootstrap, you would like to insert some text at the current caret position programmatically.

Solution

The Summernote API does not provide any dedicated methods for inserting text. However, that’s not a problem since we can use the JQuery/native DOM API to insert text into the editor. Thankfully, the content of the Summernote editor is nothing but vanilla HTML/DOM elements. Thus, we can insert text at the current cursor position as follows (if the Summernote editor is focused):

To Insert at the End of the Current Paragraph

$(document.getSelection().anchorNode.parentNode).append(“appended!”);

To Insert at the Current Cursor Position

var selection = document.getSelection();
var cursorPos = selection.anchorOffset;
var oldContent = selection.anchorNode.nodeValue;
var toInsert = "InsertMe!";
var newContent = oldContent.substring(0, cursorPos) + toInsert + oldContent.substring(cursorPos);
selection.anchorNode.nodeValue = newContent;

Note: You probably will have to work some magic with the document.getSelection() call. The problem is that once you would click a button or trigger the action in some other way, the selection would change. Thus, I save a reference to the document.getSelection() upon every focus and key press event on the editor.

Insert at Current Position (Alternative)

As suggested by Dexter in the comments below, you can also insert text as follows:

$(‘#summernote’).summernote('editor.saveRange');

// Editor loses selected range (e.g after blur)

$(‘#summernote’).summernote('editor.restoreRange');
$(‘#summernote’).summernote('editor.focus');
$(‘#summernote’).summernote('editor.insertText', 'This text should appear at the cursor');

References

MDN – Selection.anchorNode

Stackoverflow – Get caret position in contentEditable div

Stackoverflow – Inserting Text at Cursor Position using JS/JQuery

Stackoverflow – JQuery Plugin for Inserting Text at Caret

CoffeeScript Fat Arrow (=>) explained

Anyone who has worked with JavaScript for anything but a very short time will have come across the problem that the meaning of ‘this’ is often ambiguous at best. CoffeeScript attempts to mitigate this problem somewhat by introducing the Fat Arrow operator (=>). This operator can be used as a replacement for the thin arrow operator (->) used extensively in CoffeeScript for defining functions.

Unfortunately, it is not easy to understand what the fat arrow operator does.I hope the following rules provide some guidance on how to use this operator in CoffeeScript:

Rule 1: You Don’t Need the Fat Arrow If You Don’t Use: class, this, and @

If you are a beginner in JavaScript and/or CoffeeScript, I would recommend keeping your hands of the language constructs ‘this’, ‘class’ and ‘@’. You can implement any application you like without having to use these constructs and it will make your applications more robust and bug free.

Rule 2: Use the Fat Arrow when You Use @ in a Callback Definition in a Method

If you use classes in your code and you want to create a new anonymous function to be passed as a callback (such as to listen to an onclick event or to defined setTimeout function), define this function with the fat arrow operator. This will assure that you still have access to the methods and properties of the class you are working with.

The fat arrow will ‘override’ the default meaning of the @ operator as follows, to assure that ‘this’ refers to what we would expect it:

CoffeeScript

delayedAction = =>  
  alert(@messsage)

setTimeout(delayedAction, 100);

JavaScript

delayedAction = (function(_this) {
  return function() {
    return alert(_this.messsage);
  };
})(this);

setTimeout(delayedAction, 100);

Rule 3: Don’t Use Methods as Callbacks and Avoid the Fat Arrow Operator in All Other Circumstances

There is one more use case for the Fat Arrow operator, which is that it has a special meaning when used for the definition of class methods. This is useful when the methods of a class are to be passed as a callback. I personally don’t think that’s a very useful feature and it’s better to define an anonymous function to handle a callback and then call a method of your class/object from within this callback. Following this rule enables us not having to worry about whether to define a method with a thin or fat arrow – which is otherwise tricky since the right choice here is external to the class we are writing.

More Reading

Karl Seguin – Ten Features I Like About CoffeeScript

Michael Kramer – The Simplified Fat Arrow Guide for CoffeeScript

Azat Mardanov – Understanding Fat Arrows (=>) in CoffeeScript

Giang Nguyen – Coffeescript: Fat arrow vs thin arrow

Embed HTML Code in JavaScript File

Problem

You would like to include HTML code as a String in a JavaScript file.

Solution

Firstly, load the HTML code into a JavaScript variable (e.g. by using jQuery.ajax()).

$.ajax({url: 'http://mydomain.com/htmlfile.html'})

.done(function(html) {

Then apply the following two simple regular expressions on the html code to generate valid JavaScript code.

var safeHtml = html

.replace(/\n/g, "\\n")

.replace(/\"/g, "\\\"")

You can use this String now to build a JavaScript file:

var myScript = 'var html="'+safeHtml+'";';

 

JavaScript and JSON Essentials (Packt) Review

JavaScript and JSON Essentials‘ by Packt publishing is a hands-on guide to developing JavaScript/PHP based web applications while using the JSON data format. This review of the book contains a quick summary of the contents as well as points to consider if you think of purchasing the book.

Overall, this as an easy to read book suited for novices in web development, packed with examples and easy to follow step-by-step instructions. However, advanced JavaScript developers will be familiar with most of the concepts covered in the book.

Contents

Chapter 1: JavaScript Basics

Explains the very basics of JavaScript, such as how to embed a script in a webpage, simple expressions (3+4), arrays and objects.

Chapter 2: Getting Started with JSON

Goes through the fundamental rules of JSON documents and how to access the data they contain in JavaScript applications.

Chapter 3: Working with Real-time JSON

Goes through an example of processing a complex JSON document, a collection of employees with their personal and employment details. Specifically, to query data from the document such as retrieving the positions of employees and to modify data.

Chapter 4: AJAX Calls with JSON Data

Shows how to set up a simple web server under a Linux (LAMP) and Windows (ASP.NET) environment. Then, how to host a simple PHP script dynamically rendering JSON data and using XMLHttpRequest to access the data from this script from a JavaScript application.

Chapter 5: Cross-domain Asynchronous Requests

This chapter firstly expands the PHP script and JavaScript application developed in the previous chapter. Specifically, by allowing to pass query parameters to the PHP script. Then, an example is shown how to load a JSON document through JSONP from the site reddit.

Chapter 6: Building the Carousel Application

Shows how to develop a small example application in which student records are retrieved from a server and displayed in a web browser.

Chapter 7: Alternate Implementations of JSON

Portrays numerous ways in which JSON data is used such as in PHP Composer and for Node.js package manager NPM. Briefly compares JSON with the data definition format YAML.

Chapter 8: Debugging JSON

Introduces numerous tools that can aid in developing JavaScript applications such as Firebug and tools to validate (only syntax) and format JSON documents.

The Good

  • Provides a good introduction to developing simple applications with JavaScript and PHP which utilize JSON data.
  • The book is overall well organized and it is easily understandable what is covered in the chapters.
  • There are plenty of examples and step-by-step instructions
  • The PDF version of the book is easy to navigate, with helpful bookmarks, which allow to browse the table of contents and hyperlinks throughout the document.

Caveat Emptor

  • Don’t expect to become a grandmaster of JavaScript after reading the JavaScript intro of the book. It’s around 14 pages and only meant to give a brief idea of JavaScript. If you are new to JavaScript, consider a complementary book such as Object-Oriented JavaScript or JavaScript The Good Parts.
  • This book, as its title specifies covers the ‘Essentials’ of JavaScript and JSON. Thus it’s a good starting point to become familiar with these technologies but does not contain more advanced or nuanced discussions, such as good design practices for JSON documents, performance issues or tradeoffs in using JSON.

Disclaimer: Thanks to Packt Publishing for providing a free review copy of this book!

Render HTML from Object with CoffeeKup

CoffeeKup allows to render HTML from multiple sources:

  • A String containing valid CoffeeScript code
  • A JavaScript/CoffeeScript object arranged according to CoffeeKup rules

To render HTML from a String is quite straightforward and documented on the CoffeeeScript reference: you can use the methods .compile and .render as documented there.

However, to render HTML from a JavaScript/CoffeeScript object can also come in handy, to create a tight link between your logic and markup. The .render method is not only able to process a String but is also able to process a certain kind of Object as well.

Here find two examples of how to render JavaScript and CoffeeScript objects into HTML:

JavaScript Object

CoffeeKup.render(function() {

  return div({ class: 'mydiv' }, 'Hello World');

});

which results in:

"<div class='mydiv'>Hello World</div>"

CoffeeScript Object

CoffeeKup.render(div 'mydiv', ->'Hello World'<span style="line-height: 1.5em;">);

resulting in the same HTML as above.

Touch and Click in jQuery (without jQuery Mobile)

Problem

One of the most common things I do with JQuery is to attach click event listeners to buttons, links and other elements as follows:

$(“.class”).click(function(evt) {});

Unfortunately, I found that, while this approach works well for Desktop browsers, the user interaction on touch-enabled devices feels very awkward and sluggish.

Solution

Since this problem is of relevance for every mobile web application, numerous solutions have been proposed. All mobile UI JavaScript frameworks I know of provide built in support for ‘tab’ events, as opposed to ‘click’ events.

However, often we would just like to support being able to interact with simple buttons on our page regardless of whether a user accesses the site through a desktop or mobile browser; ideally, without adding another more or less ‘heavy’ framework to our site.

Luckily, jQuery Mobile is built in a very modular way and we can extract the particular component of the framework to support good support for tabs and clicks. Head to http://jquerymobile.com/download-builder/ and only check the ‘Touch’ component under Events.

Then, let the jQuery Mobile site build your download and add it to your page. For a quick test, you can also use the script provided below.

Next, we can rewire all calls to $(…).click() using the following snippet:


<script src="http://u1.linnk.it/qc8sbw/usr/apps/textsync/upload/jquery-mobile-touch.value.js " ></script>

<script>

$.fn.click = function(listener) {

    return this.each(function() {

       var $this = $( this );

       $this.on(‘vclick’, listener);

    });

};

</script>

Now, when you register an event listener in your app using $(…).click(), the respective element should be pleasant to use for both desktop and mobile users.

References

The Current State of (Touch) Events

Tap vs. Click: Death by Ignorance

Looking Inside ‘Discover Meteor’

Do you want to see the future of book publishing?

Discover Meteor‘ is an interactive book recently released by Tom Coleman and Sacha Greif about the Meteor JavaScript framework. And it’s a book as dynamic as the framework it describes.

In this post, I provide a few impressions of this book in form of screenshots and hope these give you a good idea of what to expect when purchasing Discover Meteor.

There is a brief conclusion at the end of this post as well.

Impressions

Impression 1: The main entry point to the book is a web page, which shows the table of contents of the book. Clicking on any of the links will open the respective chapter as a web page.

Impression 2: Apart from browsing the book online, you can also download HTML, PDF, epub and Kindle versions.

Impression 3: The web version of the book is nicely formatted and easy to read. Each chapter starts with a quick summary.

Impression 4: The chapters look very similar in the rendered PDF version.

Impression 5: There are plenty of source code examples. Each example offers a link to a git tag and a live instance of a Meteor application using the example.

Impression 6: Below the linked page of git and the associated live instance from the example above.

Impression 7: Each chapter has an associated discussion thread. Many threads are quite lively and the authors provide help if needed.

A Quick Conclusion

Discover Meteor seems like a great resource to get started using Meteor. The book is very applied. Every two or three paragraphs there will be a source code example, which drives the development of the example application pursued throughout the book (‘Microscope’) forward.

This is a book about solving problems with code. So, don’t expect philosophical discussions of issues, which might arise while building a Meteor application. Nonetheless, ‘Discover Meteor’ will surely allow you to discover Meteor and learn to solve many common problems effectively and quickly by following the example solutions provided in the book.

Most impressive for me was the presentation of this book. This is not your usual reading experience, this is web reading. The book is made to be opened alongside your development tools and provides an interactive experience for working your way through the examples. On the downside, this is not a book to be enjoyed as part of a poolside techbook session. But that’s not too bad, I think – more time to play with the kids instead.

Disclaimer: Thanks to Sasha for access to the book.

Getting Started with Meteor.js (Review)

Overall

The book Getting Started with Meteor.js JavaScript Framework by Isaac Strack provides a valuable resource to complement the online documentation for the Meteor.js framework. It features plenty of examples and integrates these into one comprehensive scenario; the implementation of a simple lending library. I would have loved to see some more background and advice on how to build large applications with Meteor and some patterns/solutions for common architectural level problems. But, hey, it’s not like there are hundreds of books out there on Meteor.js so these issues might be something for a sequel!

Background

Meteor.js is an emerging JavaScript framework which aims to simplify communication between application servers and JavaScript clients.

Traditionally, we would deploy some form of RESTful service (or SOAP, for the brave) on the server, which is then consumed through AJAX calls from the JavaScript application. Thus, we end up with two idiosyncratic applications: one for the server and one for the client. Often, these two applications would be implemented using different languages; such as Java or C# on the server-side and, naturally, JavaScript for the client side. As a more recent development, node.js is employed to remedy some of the difficulties arising from this arrangement by allowing both the client and the server to be implemented using one language: JavaScript.

Meteor, building on node.js, goes one step further than the common node.js application and allows JavaScript clients direct access to the application database (a MongoDB database, to be precise). Since JavaScript clients should sensibly not be given full authorization to the database, privileged database operations can be performed by JavaScript scripts applications running on the server. Meteor allows to write both client-code and privileged code in one JavaScript file and takes care that only appropriate code is available to the client.

Meteor is thus quite different to the traditional way of building web applications. As such, some problems which we came used to expect cease to be of relevance, while new and different problems might come to the fore. Thus, when reading the book Getting Started with Meteor.js JavaScript Framework by Isaac Strack, my prime interest was in the following two points:

  • Does the book serve as useful manual for navigating the basics of Meteor.js? and
  • Does the book point to possible medium-term to long-term problems and provides pattern/solutions of dealing with these.

Navigating the Basics of Meteor.js

The book definitely gives a good foundation to start using Meteor.js and overcoming various roadblocks one might encounter. This ranges from the very basics covered in chapter 1 ‘Setup and Installation’ (note, the book covers only setup and installation for Linux and Mac and not the new deployment for windows) to more elaborate questions discussed for instance in chapters 4 ‘Templates’ and chapter 7 ‘Packaging and Deploying’. Everything is explained clearly and concisely with lots of practical advice, links pointing to further resources, plenty of code examples and additional background explanations.

I especially like that the chapters 2 to 7 explore an exhaustive example of building a Meteor application, a simple lending library:

Using Meteor, we’re going to build a Lending Library. We’ll keep track of all our stuff, and who we lent it to, so that the next time we can’t remember where we put our linear compression wrench, we can simply look up who we last lent it to, and go get it back from them.

This application is brought up to a fairly sophisticated level, adding database persistence and support for multiple users including login screen etc!

Problems, Patterns and Solutions

The book does a very good job at explaining the motivation and benefits of the Meteor platform in chapter 3 accordingly named ‘Why Meteor Rocks!’. This chapter in particular explores the benefits of the MVVM (Model View View-Model) enabled by Meteor. However, there is little information on what kind of medium-term or long-term issues might arise in developing an application for Meteor.js and how these could be mitigated, for instance in form of design pattern. But, then, the very title of the book focusses on ‘Getting Started with Meteor.js’ so I guess it’s fair enough if these more abstract and complex issues are omitted.

Overall

See above!

Disclaimer: I’ve created Appjangle, which some might say is similar to Meteor.js. However, I would disagree, since Appjangle is more of a cloud platform and focusses on supporting Java and JavaScript, while Meteor is a more of a framework with a strong focus on JavaScript. In any case, I think Meteor is great and thus consider my judgment unblemished J. Further, thanks to Packt Publishing for a free copy of this book!

Tutorial: Upload from Java, Download from JavaScript

This tutorial.describes how a simple unit of data, the text ‘Hello, Java!’ can be uploaded from a Java application and retrieved with a JavaScript application. 

Upload from Java

This section lists all steps required to create a small application that store the text ‘Hello, World’ in the Appjangle cloud database.

Step 1: Download Client Libraries

First download the latest version of the Appjangle client libraries from this page.
Chose the ‘Appjangle Client with Nextweb API’. The Nextweb API is more declarative in nature than the more low-level onedb API and therefore allows in most cases to write more concise code.
If you use Maven in your project, you can also use the provided Maven dependencies to link the library to your project.

Step 2: Link Client Libraries

Create a new project in your favorite IDE. This example will make use of eclipse.
Copy the downloaded .jar file into a your project directory (e.g. ‘lib’) and add the library to the classpath/ build path.

Step 3: Write App to Upload Data

Create a new class with the name ‘Upload’. Add a Java main method to the class as follows:
import io.nextweb.Query;
import io.nextweb.Session;
import io.nextweb.jre.Nextweb;

public class Upload {

    public static void main(String[] args) {
        Session session = Nextweb.createSession();

        Query hello = session.seed().append("Hello, Java!");

        System.out.println("Created:\n"+hello.get());

        session.close().get();
    }

}
Running this application should result in an output such as the following:
Created:
node("http://slicnet.com/seed1/seed1/2/1/2/h/sd/Hello__1", 
  class java.lang.String)
You can now access the created node using the reported URI. For instance, by opening http://slicnet.com/seed1/seed1/2/1/2/h/sd/Hello__1 
in a web browser.

Download from JavaScript

This section lists all steps required to create a small application that store the text ‘Hello, World’ in the Appjangle cloud database using JavaScript.

Step 1: Download and Extract Appjangle Bootstrap

Head over to github to download the Appjangle Bootstrap project or, even better, fork it if you are familiar with github.
Extract the project and open app.html in your faverioute HTML/JS editor.

Step 2: Write App to Download Data

Replace the text // Your JavaScript here with the following application:
<body>
    <script
        src="http://appjangle.com/js/v01/appjangle/appjangle.nocache.js">
    </script>

    <script>
        window.onNextwebOnedb = function() {
            var session = Nextweb.createSession();
            var hello = session
                    .node("http://slicnet.com/seed1/seed1/2/1/2/h/sd/Hello__1");
            hello.get(function(node) {
                document.body
                        .appendChild(document.createTextNode(node.value()));
            });
        }
    </script>
</body>
Save app.html and close your editor.

Step 3: Upload App to Appjangle

Open the TextSync JAR file in the appjangle-bootstrap directory (for instance, by double clicking on the file if supported by your OS).
Drag and drop the file app.html onto the files list in the TextSync App and click [Synchronize].
Note: You will need to get an Appjangle account in order to use the TextSync App. All your uploaded applications will be stored under this account.

Step 4: Open Application

Open app.html again. In the beginning of the file, copy the URL to the right of one.upload .
Past the URL into your web browser. Add to the end of the URL .value.html and replace https with http at the beginning of the URL.
Loading the page should result in the output (also see an example deployed app here):

Hello, Java

It’s not ‘Hello, JavaScript’ since here we are loading the node created by the Java Hello, World application described above. Check out the Nextweb.io API docs to find out how to change the text stored in the Appjangle cloud to a more fitting ‘Hello, JavaScript’.
This tutorial is also published on the Appjangle blog.

Converting youtube video link to embed link with JavaScript

Videos on youtube usually have a URI such as the following:

http://www.youtube.com/watch?v=nCgQDjiotG0

These URIs cannot be used to embed the video in an iframe such as the following:

In order to work as part of an embedded iframe, youtube video links must be in the following format:

http://www.youtube.com/embed/nCgQDjiotG0

Luckily, given any ‘normal’ youtube link, it is very easy to generate such an embed link. In JavaScript, this can be done with the following function:

function createYouTubeEmbedLink (link) {
 return link.replace("http://www.youtube.com/watch?v=", "http://www.youtube.com/embed/");
 }