WebRTC

I am working on a project at Hack Reactor that is giving me an introduction to the WebRTC framework. For those not yet in the know, WebRTC is a tool released by Google a few years ago that allows users to communicate in real-time via the browser (RTC = Real-Time Communication). One of the simplest tasks that can be accomplished with this technology is a browser-based chat application, but the advantages truly shine through with use cases involving audio and video communication.

WebRTC has built-in functionality to access a user’s camera and microphone through the browser. It also provides peer-to-peer connection functionality and audio+video calling. By going through the provided examples, my team was able to easily implement a basic video chat application for two individuals to communicate through the browser. No plugins were necessary, and all the user had to do was to “allow” their camera to be used when prompted by the browser.

In order to connect using WebRTC, two peers need to know one another’s information about their network connections, or ICE (Interactive Connectivity Establishment) candidates. This is how the peers know how to communicate, which will take place over a STUN (Session Traversal Utilities for NAT) or TURN (Traversal Using Relays around NAT) server. More information about this process can be found here.

Advertisements

Limit characters displayed in text with Angular

Our goal is to limit the amount of characters shown in a block of text using angular. In the aim of brevity and simplicity, let’s assume that we have a large chunk of text in a model called ‘text’, and we only want to show 150 characters at a time, with the option to expand our view to see the entire block of text. If we were to include the text without any limit, it would look like this:

{{text}}

To display only the first 150 characters, the code changes as follows:

{{text | limitTo: 150}}

That’s simple enough. But, now we have no way to view the rest of our text. To do so, we are going to need to initialize a limit value in an outer element so that we can later modify it:

<div ng-init="limit = 150">
    {{text | limitTo: limit}}
</div>

If the length of the text is greater than the limit (meaning we have cut off some text), we want to add an option to show more text:

<div ng-init="limit = 150; moreShown = false">
    {{text | limitTo: limit}}
    <a ng-show="text.length > limit"
       href ng-click="limit=text.length; moreShown = true">  More
    </a>
</div>

Here, we are also initializing a variable that will track whether or not our full block of text is displayed. If the length of the text is over the limit, ng-show will active and the href displaying a clickable “More” will appear. On click, the limit will be set to the length of the text so that the entire block is displayed, and moreShown will correctly track the change to say that all the text is displayed.

Now, maybe we would like an option to shorten our text once again. We can use a similar sort of logic to add a “Less” href- just add the following code to the above:

<a ng-show="moreShown" href ng-click="limit=150; moreShown = false"> Less </a>

The ng-show will trigger if we have the full amount of text displayed, and on click, the text limit will go back down to 150, with moreShown getting set back to false.

Finally, we can throw in some logic to add an ellipses for concatenated text; our final code will look as follows:

<div ng-init="limit = 150; moreShown = false">
    {{text | limitTo: limit}}{{text.length > limit ? '...' : ''}}
    <a ng-show="text.length > limit"
      href ng-click="limit=text.length; moreShown = true">  More
    </a>
    <a ng-show="moreShown" href ng-click="limit=150; moreShown =    false"> Less </a>
</div>

Basic HTML Tricks: Inline Text Elements, Artificial Line Breaks, and Buttons

I have encountered a handful of instances while programming where I need to create some HTML for a page, but it does not need to be a finished product. I am not yet concerned with obtaining a polished look using CSS or various libraries (or perhaps I will never be concerned about this). We are a beginner web developers just looking to get something functional on the page, to be improved later. For some quick and dirty HTML edits, look no further than the following:

One of the questions that would once plague me was: How can I make my text appear on the same line as this other text/link/element? The <p>, <h1>, <div> are all tags that I can insert text into, but each of these will put my text element on a separate line. The solution is the <span> tag, which can be used to quickly add an inline text element. Sure enough, <div>Hello </div><div>World</div> shows up differently than <span>Hello </span><span>World</span>.

Another simple HTML trick has the opposite effect: the <br> tag. Simply throw this tag into your HTML to create a line break. Later on, you’ll probably be using margins and padding to alter your spacing, but for now, a quick little <br> tag should make your primitive HTML page easier on the eyes. Try altering our <span> setup from above for a nice visual example: <span>Hello </span><br><br><span>World</span>.

Finally, a very useful HTML element is the button. Even if this button won’t make it into the final iteration of your product, it can be very useful for testing some sort of user input functionality to be added later. Here is a quick example: <button id=”hello”>Hello World</button>. Here, the text within the button is “Hello World”. I’ve also included an id; this is generally a good idea so that your button can be specifically referred to by id later, particularly if there are more buttons that will be added.

Start using Angular

You may have heard of AngularJS, which is a framework put forth by Google that is geared toward single-page web applications. Getting started with a new framework is always a daunting task, so if you are looking for a kicking-off point, here it is: we will create the simplest possible web app using AngularJS.

First, we want to include the Angular library in our code. Start by creating a basic index.html file for a blank webpage. From there, you can either download angular so that you can work offline, or simply source the following URL in your HTML:
https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js
This will pull the necessary scripts straight from the Google CDN (content delivery network), so you don’t need to install anything.

Next, we want to create a JavaScript file where we will keep our logic; let’s call it app.js. Then, go ahead and source the app.js file in the HTML. So far, the HTML page should look something like this:

<!doctype html>
<html ng-app="sampleApp">
   <head>
     <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
     <script src="app.js"></script>
   </head>
   <body>
   </body>
</html>

In order to get some functionality for our app, we will need to create a controller; in Angular, controllers are housed within modules (which will also house various other parts of a more complicated app). So, let us instantiate our module and add a controller in the app.js file:

angular.module('sampleApp', [])
   .controller('sampleController', function($scope) {
     $scope.words = "Hello world!";
   });

Here, the first argument to ‘module’ is ‘sampleApp’, which is what we will call our app. The second argument is an array of models that this model is dependent on; in this case, there are none as of yet. We create our controller, dubbed ‘sampleController’, as a method of the ‘sampleApp’ module. Each controller in Angular comes with its own scope, which is delineated by the $scope keyword. When we set $scope.words, we can reference ‘words’ by itself as long as we are within the scope in question. The syntax we use for this is a double curly-brace, so that we can add the following to the HTML:

<div ng-controller='sampleController'>
   <h1>{{words}}</h1>
 </div>

And that’s it! Your webpage should display the words “Hello World!” in nice large letters (thanks to the ‘<h1>’ header tag). You are ready for your Angular app to blossom into something remarkable. The documentation is good, so with this jumping-off point and a bit of experimentation, you’ll be amazed at the functionality you can accomplish in relatively few lines of code.

Basic JavaScript recursion resource

One of the most intimidating parts of programming is the concept of recursion– that is, calling a function within itself. The function calls itself until it reaches a “base case” where something is returned (the base case is similar to what you might see between the parentheses at the beginning of a while loop). A resource I found useful as an introduction to recursion was Codecademy’s “Recursion in Javascript” lesson set:

http://www.codecademy.com/courses/javascript-lesson-205

While recursion is a difficult concept, Codecademy interactively walks the user through a set of lessons that start with the most basic of loops and end with some practical examples of recursion implementation. As someone who has been using recursive algorithms regularly over the past three weeks (Hack Reactor’s curriculum definitely does not shy away from the concept), I wish I had come across this resource sooner. However, it was still an excellent review for me, and I plan to take my strengthened comprehension of recursion and apply it to some of the more difficult recursive problems, such as those involving permutations.

For those having trouble following a function through multiple levels of recursion and determining the order of calculations, you are far from alone. Coming up with a visual representation of the problem can help, and walking through each step methodically and predicting what the program will do at each point is also a good idea. Good luck!

Create a draggable SVG image using Javascript’s D3

I was introduced to Javascript’s D3 library last week during a 2-day coding “sprint” at Hack Reactor. Learning to use D3 to interact with SVG elements was a difficult process that included quite a bit of trial and error, along with a great amount of research. I am hoping to add to the resources available to my fellow D3 scripters with this post.

We will not assume any added elements to the HTML file aside from sourcing the d3.js library. We will, however, assume that the desired image is added to the project’s folder under the name “myimage.png”.

Our first step will be to add the SVG element that we will eventually be putting our image into. In this example, the element has the dimension 500×300:

d3.select('body').append('svg')
  .attr("width", 500)
  .attr("height", 300)

Next, we will add our image to the SVG element; in this example, the image will be sized at 50x50px and positioned at (150, 100). The “xlink:href” tells us where we are pulling the image from:

d3.select('body').select('svg').append("image")
  .attr("x", 150)
  .attr("y", 100)
  .attr("height", "50px")
  .attr("width", "50px")
  .attr("xlink:href", "myimage.png")

In order to add the dragging functionality, we need to include a function that is called when the mouse is currently dragging our image. This function sets the midpoint of our image (calculated using one-half of the image’s width and height) to the location of our mouse pointer:

function mover () {
  d3.select('image')
    .attr("x", d3.event.x - parseInt(d3.select('image').attr("width")) / 2)
    .attr("y", d3.event.y - parseInt(d3.select('image').attr("height")) / 2);
}

Fortunately, the D3 library has a built-in function that can be called when the mouse is dragging an element. This function will call our mover function when the image is dragged:

var drag = d3.behavior.drag()
    .on("drag", mover);

Finally, we add a call to our drag function to the image element:

d3.select('body').select('svg').select("image")
  .call(drag);

Note that if we had defined our drag variable first, we could have added the call to drag in our second piece of code where we first added the image. However, I believe the presented order is more intuitive and reads a little easier.

Chatbuilder

Welcome to my first blog post! As of right now, I am in my first week of an accelerated programming school (coding bootcamp) known as Hack Reactor. There are many things that I have learned and experienced this past week that I could speak to, but I thought instead I would look back to a Hack Reactor project I completed before I was even accepted into the program. After venturing a few steps in to the Hack Reactor application, I was greeted with a difficult project whose completion was not required, but recommended before entry into the program. I would encourage anyone who is thinking of applying to the program (or anyone simply looking for a coding challenge) to complete Chatbuilder as both a learning experience and indicator of future success.

Chatbuilder can best be described as a simplified version of a twitter feed, whose implementation requires some knowledge of DevTools, JavaScript, jQuery, and HTML. I was new to most of these concepts coming in to the project, but by the time I was finished, I felt much more comfortable with all of them thanks to this valuable exposure. To illustrate this effect, I’ll provide an example of a very short function from my project:


function addMsg (msg) {
  $(".messages").append("<li>" + msg + "</li>");
}

In order to reach a point where I had the ability to write such a function, I first had to gain some level of understanding of jQuery (represented by the “$” symbol) and its interaction with HTML DOM elements (referenced with “.messages” and “li”). The function itself is in JavaScript, which I had some experience with from various lessons and coding challenges. This particular function is meant to be called whenever a message should be displayed (either through timed computer-generation or user input). The function takes a string as input and adds it to the DOM as an “li” element, which is then displayed as a line on the page.

My intention in writing this post is to recommend an avenue for learning about some web developing technologies and preparing oneself for the intense curriculum offered at Hack Reactor. The Chatbuilder project has enough instruction such that I was prevented from becoming overly lost or off-track, but the learning curve was still relatively steep as I was made to figure out most of what I needed for myself. Good luck, gentle reader!