Building interactive elements with HTML and javascript: Interact.js + drag-drop

{ Repost from my personal blog @ https://blog.codezero.xyz/building-interactive-elements-with-html-and-javascript-interact-js-drag-drop }

In a few of the past blog posts, we saw about implementing drag-drop andresizing with HTML and javascript. The functionality was pretty basic with a simple drag-and-drop and resizing. That is where, a javascript library called as interact.js comes in.

interact.js is a lightweight, standalone JavaScript module for handling single-pointer and multi-touch drags and gestures with powerful features including inertia and snapping.

With Interact.js, building interactive elements is like a eating a piece of your favorite cake – that easy !

Getting started with Interact.js

You have multiple option to include the library in your project.

  • You can use bower to install (bower install interact) (or)
  • npm (npm install interact.js) (or)
  • You could directly include the library from a CDN (https://cdnjs.cloudflare.com/ajax/libs/interact.js/1.2.6/interact.min.js).

Implementing a simple draggable

Let’s start with some basic markup. We’ll be using the draggable class to enable interact.js on this element.

<div id="box-one" class="draggable">  
  <p> I am the first Box </p>
</div>  
<div id="box-two" class="draggable">  
    <p> I am the second Box </p>
</div>

The first step in using interact.js is to create an interact instance. Which you can create by using interact('<the selector>'). Once the instance is created, you’ll have to call the draggable method on it to enable drag. Draggable accepts a javascript object with some configuration options and some pretty useful callbacks.

// target elements with the "draggable" class
interact('.draggable')  
  .draggable({
    // enable inertial throwing
    inertia: true,
    // keep the element within the area of it's parent
    restrict: {
      restriction: "parent",
      endOnly: true,
      elementRect: { top: 0, left: 0, bottom: 1, right: 1 }
    },
    // enable autoScroll
    autoScroll: true,
    // call this function on every dragmove event
    onmove: dragMoveListener,
  });

  function dragMoveListener (event) {
    var target = event.target,
        // keep the dragged position in the data-x/data-y attributes
        x = (parseFloat(target.getAttribute('data-x')) || 0) + event.dx,
        y = (parseFloat(target.getAttribute('data-y')) || 0) + event.dy;

    // translate the element
    target.style.webkitTransform =
    target.style.transform =
      'translate(' + x + 'px, ' + y + 'px)';

    // update the posiion attributes
    target.setAttribute('data-x', x);
    target.setAttribute('data-y', y);
  }

Here we use the onmove event to move the box according to the dx and dyprovided by interact when the element is dragged.

Implementing a simple drag-drop

Now to the above draggable, we’ll add a drop zone into which the two draggable boxes can be dropped.

<div id="dropzone" class="dropzone">You can drop the boxes here</div>

Similar to a draggable, we first create an interact instance. Then we call the dropzone method on to tell interact that, that div is to be considered as a dropzone. The dropzone method accepts a json object with configuration options and callbacks.

// enable draggables to be dropped into this
interact('.dropzone').dropzone({  
  // Require a 50% element overlap for a drop to be possible
  overlap: 0.50,

  // listen for drop related events:

  ondropactivate: function (event) {
    // add active dropzone feedback
    event.target.classList.add('drop-active');
  },
  ondragenter: function (event) {
    var draggableElement = event.relatedTarget,
        dropzoneElement = event.target;

    // feedback the possibility of a drop
    dropzoneElement.classList.add('drop-target');
  },
  ondragleave: function (event) {
    // remove the drop feedback style
    event.target.classList.remove('drop-target');
  },
  ondrop: function (event) {
    event.relatedTarget.textContent = 'Dropped';
  },
  ondropdeactivate: function (event) {
    // remove active dropzone feedback
    event.target.classList.remove('drop-active');
    event.target.classList.remove('drop-target');
  }
});

Each event provides two important properties. relatedTarget which gives us the DOM object of the draggable that is being dragged. And target which gives us the DOM object of the dropzone. We can use this to provide visual feedback for the user when he/she is dragging.

Demo:

https://jsfiddle.net/niranjan94/yqwc4hqz/2/

Continue ReadingBuilding interactive elements with HTML and javascript: Interact.js + drag-drop

Unit testing nodejs with Mocha and Chai

There are a lot of unit testing frameworks available for Javascript, Jasmine and Karma being some of the older and more popular ones.

Jasmine and Karma, though are, originally designed for browser-side JS, and hence, frameworks like NodeUnit and Mocha have become more popular with server-size JS.
We needed code coverage reports to work after the unit tests, and the Jasmine-Node reports were not sufficient, so we just moved to using Mocha.

When using Mocha, we can use some assert library (which is not necessary, but makes life a hell lot easier). We are using chai at the open-event-webapp..

First of all install mocha globally –

npm install -g mocha

And write your tests in the test/ folder that mocha by default considers as the folder containing your test specs. For example we have our tests here – https://github.com/fossasia/open-event-webapp/tree/master/test

Writing a simple mocha test is as easy as this –

var assert = require('chai').assert;
describe('Array', function() {
  describe('#indexOf()', function() {
    it('should return -1 when the value is not present', function() {
      assert.equal(-1, [1,2,3].indexOf(5));
      assert.equal(-1, [1,2,3].indexOf(0));
    });
  });
});

The first parameter inside describe() is just to show the tests in a aesthetic way in the console.

You can see our tests described in this file  – https://github.com/fossasia/open-event-webapp/blob/master/test/serverTest.js

And attached below is an screenshot of the terminal after I have run the command mocha in the root of my project

Screenshot from 2016-07-10 04-42-26

Continue ReadingUnit testing nodejs with Mocha and Chai

Uploading a file to a server via PHP

Uploading a file to a server via PHP

If you have been following my posts about my GSoC project, you would be knowing that we are making an app generator which will allow users to easily generate an android app for any event that they plan to host.

So, the next thing that we wanted in our app was to allow the users to upload a zip containing the json files (in case they don’t have an API, from where app can fetch data from) and then upload it to the server where we can use these files during the app compilation.

Steps below will tell you , how we achieved it :

Changes to HTML

First thing that we needed to do was add a file upload element to out HTML page that would allow only .zip files to be uploaded.
It was pretty simple one liner code which goes as follows

<tr>
<td valign=”top”>
<label for=”sessions”>Zip containing .json files</label>
</td>
<td valign=”top”>
<input accept=”.zip” type=”file” id=”uploadZip” name=”sessions”>
</td>
</tr>

PHP script to upload file on to the server

Next, we needed a server sided script (I used PHP) which would upload the zip provided by the user on to the server and store it to a unique location for each user.
The code for that was,

<?php
if ( 0 < $_FILES[‘file’][‘error’] ) {
echo ‘Error: ‘ . $_FILES[‘file’][‘error’] . ‘<br>’;
}
else {
move_uploaded_file($_FILES[‘file’][‘tmp_name’],“/var/www/html/uploads/upload.zip”);
}
?>

So what is happening here is basically the input arg. is first checked whether it is null or not null.
If it is null, and error is thrown back to the user, else the file is renamed and uploaded to the uploads folder in the server’s public directory.

Changes to the JavaScript

This was the part that needed most of the changes to be done, we first had to store the file that is to be uploaded in the form data, and then make and AJAX call to the php file located on the server.

var file_data = $(‘#uploadZip’).prop(‘files’)[0];
var form_data = new FormData();
form_data.append(‘file’, file_data);
$.ajax(
{ url: ‘/upload.php’, // point to server-side PHP script
cache: false,
contentType: false,
processData: false,
data: form_data,
type: ‘post’,
success: function(php_script_response){
ajaxCall1(); } //Chain up another AJAX call for further operations
});

So, that’s almost it!
Some server sided changes were also required like allowing the web user to execute the upload.php script and making the uploads directory writable by the web user.

Well, does it work?

Um, yeah it does.
There are a few issues with concurrent users which we are still debugging, but apart from that it works like a charm!

Here you can see a folder created by each user based on his/her timestamp
And here you can see the file that was uploaded y him/her
screenshot-area-2016-07-04-124957
Lastly our webapp (Looks stunning right?)

So, that was all for this week, hope to see you again next time.
Cheers and all the best 🙂

Continue ReadingUploading a file to a server via PHP

Debugging with Node

Nodejs is a powerful Event-driven I/O server-side JavaScript environment based on V8. Debugging of Node applications is not as easy as the browser code. But the node wonderful debugger can make it easy if it is used effectively.

How to start the debugger

For debugging node applications, we have to only run a debug command. Here for a quick demonstration, I have used Open-Event-Webapp fold.js code.

Suppose there is a problem in the script file and we have to debug it. All we have to do is to run the debug command from the directory containing the file.

node debug ./fold.js

The output screen will show something like this:

25

This brings us into the debug mode. When we are in debug mode, we can try various commands like ‘n’ for next, ‘s’ for the step into a function, ‘list(k)’ where k is the number of lines of the code you want on the screen.

26

The ‘n’ command always takes us to next instruction, hence in long codebases, it is always recommended to use ‘c’ or Continue Execution command for going to the next breakpoint.

To set the breakpoint, we can use the command:

setBreakpoint() or sb()

The snapshot shows the output once the breakpoint is set. We can check the values at the breakpoint by using command repl.

4

Debugging the code correctly can save a lot of time and effort. These techniques provided by the debugger are necessary to learn.

Alternates

Continue ReadingDebugging with Node

The three C’s of Javascript

week5gsoc1

You might be wondering what the three C’s are :

  • Currying
  • Closures
  • Callbacks

Ok what are those ?

Before i start, let me tell you that in Javascript Functions are Objects. So every object in Javascript, be it Number, String, Array; Every Object in javascript has a prototype object. For instance if the object is declared using an object literal then it has access to Object.prototype, Similarly all the arrays so declared have access to the Array.prototype. So since functions are objects, they can be used like any other value. They can be stored in variables, objects, and arrays. They can also be passed as arguments to functions, and donot forget that functions can be returned from functions.
Currying :

In Javascript if one wants to partially evaluate functions then one can take advantage of a concept called function currying. Currying allows us to produce a new function by combining a function and an argument. For example let us consider writing an add function, :

function add(foo, bar) {
if(arguments.length === 1) {
return function (boo) {
return foo + boo;
}
}
return foo + bar;
}
So for the above code,
add(12, 13); // gives 25
add(12)(13); // gives 25

The curry method works by creating a closure that holds that original function and the arguments to curry. It returns a function that, when invoked, returns the result of calling that original function, passing it all of the arguments from the invocation of curry and the current invocation
Closures :

Simply put, a closure is an inner function that has access to the outer (enclosing) function’s variables scope chain. Except the parameters and variables that which are defined using this and arguments all, the inner functions have access to all the parameters and variables of the function in which those are defined.

var a = 0;
function counter() {
var i = 2;
return i*i;
}
function counter1() {
return a+= 1;
}

// this wont work as part of Js closures
function counter_foo() {
var a = 0;
a += 1;
}

// this also wont work as part of Js closures
function counter_bar() {
var c = 0;
function go() { c+= 1;}
go();
return counter;
}
// this will work as part of Js closures
var counter_closure = (function () {
var incr;
return function() {return incr+= 1;}
})();

show(counter1());
show(counter1());
show(counter1()); // since we are added the counter three times the value of a is set to 3.
show(counter_foo());
show(counter_foo());
show(counter_foo()); // this is similar to the above but doesnot set the value of a to 3, but returns undefined.
show(counter_bar());
show(counter_bar());
show(counter_bar()); // Neither this works which will always set the value to 1
show(counter_closure());
show(counter_closure());
show(counter_closure()); // Now this is called closures implementation in Js

Function Closures in Javascript is all about how are the variables being treated and referred to in the local or global scope. In Js variables can be given : 'local scope' 'global scope' There is no inbuilt concept for something called private variables, so when there is a requirement for such a scenario Closures are written in Js in order to make scope for variables that are private in scope. Observing the functions ‘counter1()’, ‘counter_foo()’ and ‘counter_bar()’ there is a similarity that can be observed, Basically we can understand that closures are nothing but self invoking functions in Js. Observe the example ‘counter_closure()’ where in we are calling the function thrice and hoping to increment the functional value each time when we call the function. So this self invoking function runs only once but it increments the value each time it is called. The scope of the variable is protected by the anonymous return function making us assume that this can be called implementation of private variables in Js.
Callbacks :

A callback function is a function that is passed to another function as a parameter and giving the provision for the function to “call us back” later. Since the callback function is just a normal function when it is executed, we can pass parameters to it. We can pass any of the containing function’s properties (or global properties) as parameters to the callback function. Let us look at an example :

function manipulate(foo, bar) {
console.log("Do you know that " + foo + " is better than " + bar);
}
function useIt(boo, callback) {
var t1 = boo.slice(1,5);
var t2 = boo.slice(31,36);
callback(t2, t1);
}
The above code can be used like this :
var str = "Akhil is going to wrestle with hector";
useIt(str, manipulate); // Gives : Do you know that Akhil is better than hector.

So that is how we can implement Currying, Closures and Callbacks in Javascript.

Thats it folks,
Happy Hacking !!

Continue ReadingThe three C’s of Javascript

Responsive UI: Modifying Designs with Device Width

An important feature of websites these days with the advancement of smartphones is being responsive with device size. We nowadays not only worry about the various width of laptop or desktop, which don’t vary by a huge amount but also need to worry about tablets and phones which have a much lesser width. The website’s UI should not break and should be as easy to use on phones as it is on desktops/laptops. Using frameworks like bootstraps, Semantic-UI solves this problem to a large extent. But what if we need to modify certain parts by our own in case of mobile devices? How do we do that?

Continue ReadingResponsive UI: Modifying Designs with Device Width

LearnJS

week4gsoc1

LearnJs is an attempt to portray the best parts of Javasript that are pretty tough and hard to find. It is to be noted that this is not a book/guide in any form, but a congregation of best practices, language constructs, and other simple yet effective snippets that gives us an essence of how we can harness the best out of the language.

So what are all covered in the cheatsheet ?

  • Intro
  • Arrays
  • Strings
  • Objects
  • Functions
  • Conventions
  • Closures
  • Currying
  • Tail Calls

Intro : Declarations

week4gsoc2

We have to understand the fact that in Javascript everything is an object, so for suppose if we declare a string using the String object and compare it with var a = “” then the outcome of the comparision would be false. This is simply because if we declare a string using the bad way and compare it with a string declared using the good way then fundamentally we are comparing a string with an Object(String).
Intro : Semicolons

week4gsoc3

Code Snippet one and two are the same. but the fundamental difference between both the code samples is that one uses semicolons in the lang- -uage semantics but whereas the other doesnot. Basically we are taught to use semicolons in languages such as C, C++, Java etc since lines of code are terminated using ‘;’ but in Javascript the entire scenario is different. There is absolutely no difference in execution of code with or without semicolons.

Objects

week4gsoc4

So basically except the primitive values all are objects in Javascript

Tail Calls

week4gsoc5

Tail calls are nothing but essentially replacing the concept of recursive functions with loop. In a way this can not only save time but also saves space i.e better time complexity and space complexity.Observing both the algorithms above written for factorial we can understand that f() is the traditional recursive method used for finding the factorial, but f1() is the tail call optimized algorithm which is better and fast.

The work is going in progress, since there is still a lot to cover.
Github : Click here
Source : Click here

Thats it folks,
Happy Hacking !!

Continue ReadingLearnJS

Building interactive elements with HTML and javascript: Resizing

{ Repost from my personal blog @ https://blog.codezero.xyz/building-interactive-elements-with-html-and-javascript-resizing }

Unlike draggable, HTML/js does not provide us with a direct spec for allowing users to graphically resize HTML DOM elements. So, we’ll be using mouse events and pointer locations to achieve the ability of resizing.

We’ll start with a box div.

<div id="box">  
    <div>Resize me !</div>
</div>  

A little bit of CSS magic to make it look a little bit better and square.

#box {
    position: relative;
    width: 130px;
    height: 130px;
    background-color: #2196F3;
    color: white;
    display:flex;
    justify-content:center;
    align-items:center;
    border-radius: 10px;
}

Now, we need a handle element. The user will be using this handle element to drag and resize the box.

<div id="box">  
    <div>Resize me !</div>
    <div id="handle">
    </div>
</div>  

Now, we just have an invisible div. Let’s give it some color, make it square. We also have to position it at one corner of the box.

#handle {
    background-color: #727272;
    width: 10px;
    height: 10px;
    cursor: se-resize;
    position:absolute;
    right: 0;
    bottom: 0;
}

The parent div#box has the CSS property position: relative and by setting div#handle the property position:absolute, we have the ability to position the handle absolutely with respect to its parent.

Also, note the cursor: se-resize property. This instructs the browser to set the cursor to the resize cursor () when the user is over it.

Now, it’s upto to javascript to take over. :wink:

var resizeHandle = document.getElementById('handle');  
var box = document.getElementById('box');  

For resizing, the user would click on the handle and drag it. So, we need to start resizing the moment the user presses and holds on the handle. Let’s setup a function to listen for the mousedown event.

resizeHandle.addEventListener('mousedown', initialiseResize, false);  

the initialiseResize function should do two things:

  1. Resize the box every time the mouse pointer moves.
  2. Listen for mouseup event so that the event listeners can be removed as soon as the user is done resizing.
function initialiseResize(e) {  
    window.addEventListener('mousemove', startResizing, false);
    window.addEventListener('mouseup', stopResizing, false);
}
function startResizing(e) {  
    // Do resize here
}
function stopResizing(e) {  
    window.removeEventListener('mousemove', startResizing, false);
    window.removeEventListener('mouseup', stopResizing, false);
}

To resize the box according to the user’s mouse pointer movements, we’ll be taking the current x and y coordinates of the mouse pointer (in pixels) and change the box’s height and width accordingly.

function startResizing(e) {  
   box.style.width = (e.clientX) + 'px';
   box.style.height = (e.clientY) + 'px';
}

e.clientX gives the mouse pointer’s X coordinate and e.clientY gives the mouse pointer’s Y coordinate

Now, this works. But this would only work as expected if the box is placed in the top-left corner of the page. We’ll have to compensate for the box’s left and top offsets. (position from the left and top edges of the page)

function startResizing(e) {  
   box.style.width = (e.clientX - box.offsetLeft) + 'px';
   box.style.height = (e.clientY - box.offsetTop) + 'px';
}

There you go :smile: We can now resize the box !

https://jsfiddle.net/niranjan94/w8k1ffju/embedded

Continue ReadingBuilding interactive elements with HTML and javascript: Resizing

The beauty of Directives, Transclusion in Angular.JS

week3gsoc1

To be honest in Angular directives are nothing but DOM elements simply put on steroids. Now if you add transclusion to it literally the possibilty of exploring the playground is boundless .With that said before diving into what directives are and how cool are they, let us basically understand what makes directives in angular so powerful.

Some of the well known directives which are used regularly are :

  • ng-src
  • ng-show
  • ng-hide
  • ng-model
  • ng-repeat

Custom Directives and the benifit of creating reusable components

We often tend to waste a lot of time and energy in writing code which is already/previously written and components which are already built. But what if you could write them only once and reuse them as many times as possible ?
ANS : “Directives”
You can create truly reusable components with directives, and the approach to build custom components is definitely neater and more intuitive.
Where do Custom Directives get implemented ?

  • elements
  • attributes
  • classes

Scope of Directives

After we initialize a directive we can observe that it gets a parent scope by default. In the best interests of the application you write you won’t really want that to happen. So in order to freely modify the properties of the directive we expose the parent’s controller scope to the directives.In some cases your directive may want to add several properties and functions to the scope that are for internal use only.

Example : If you have a directive that deals with comments(just like my sTeam web interface), you may want to set some internal variable to show or hide some of its specific sections. If we set these models to the parent’s scope we would pollute it.

Without polluting, is there any option ?

Absolutely there are two options,

  • Use a child scope
  • Use an isolated scope

If we use a child scope then the child scope prototypically inherits the parent’s scope. If we use an isolated scope then its all on its own, by not inheriting its parent’s scope

Transclusion

Transclusion is a feature that enables us to wrap a directive around arbitrary content. We can extract and compile it against the correct scope later, and eventually place it at the specified position in the directive template. If you set transclude:true in the directive definition, a new transcluded scope will be created which prototypically inherits from the parent scope. If you want your directive with isolated scope to contain an arbitrary piece of content and execute it against the parent scope, transclusion can be used.

Example :

week3gsoc2

See the above snippet, here ng-transclude says where to put the transcluded content. In this case the DOM content Hello {{name}} is extracted and put inside div ng-tran- sclude /div> . The important point to remember is that the expression {{name}} interpolates against the property defined in the parent scope rather than the isolated scope.

Thats it folks,
Happy Hacking !!

Continue ReadingThe beauty of Directives, Transclusion in Angular.JS

Building interactive elements with HTML and javascript: Drag and Drop

{ Repost from my personal blog @ https://blog.codezero.xyz/building-interactive-elements-with-html-and-javascript-drag-and-drop }

Traditionally, all interactions in a website has been mostly via form inputs or clicking on links/button. The introduction of native Drag-and-drop as a part of the HTML5 spec, opened developers to a new way of Graphical input. So, how could this be implemented ?

Making any HTML element draggable is as simple as adding draggable="true" as an attribute.

<div id="a-draggable-div" draggable=true>  
    <h4>Drag me</h4>
</div>  

This will allow the user to drag div#a-draggable-div. Next, we need to designate a dropzone, into which the user can drop the div.

<div id="dropzone" ondragover="onDragOver(event)">  
</div>  
function onDragOver(e) {  
    // This function is called everytime 
    // an element is dragged over div#dropzone
    var dropzone = ev.target;

}

Now, the user will be able to drag the element. But, nothing will happen when the user drops it into the dropzone. We’ll need to define and handle that event. HTML5 provides ondrop attribute to bind to the drop event.

When the user drops the div into the drop zone, we’ll have to move the div from it’s original position into the drop zone. This has to be done in the drop event.

<div id="dropzone"  
ondrop="onDrop(event)"  
ondragover="onDragOver(event)"> </div>  
function onDrop(e) {  
    e.preventDefault();
    var draggableDiv = document.getElementById("a-draggable-div");
    draggableDiv.setAttribute("draggable", "false");
    e.target.appendChild(draggableDiv);
}

So, when the user drops the div into the drop zone, we’re disabling the draggable property of the div and appending it into the drop zone.

This is a very basic drag and drop implementation. It gets the job done. But, HTML5 provides us with more events to make the user’s experience even better 1.

Event Description
drag Fired when an element or text selection is being dragged.
dragend Fired when a drag operation is being ended (for example, by releasing a mouse button or hitting the escape key).
dragenter Fired when a dragged element or text selection enters a valid drop target.
dragexit Fired when an element is no longer the drag operation’s immediate selection target.
dragleave Fired when a dragged element or text selection leaves a valid drop target.
dragover Fired when an element or text selection is being dragged over a valid drop target
dragstart Fired when the user starts dragging an element or text selection.
drop Fired when an element or text selection is dropped on a valid drop target.

With these events a little bit of css magic a more user friendly experience can be created like highlighting the drop zones when the user starts to drag an element or changing the element’s text based on its state.

Demo:

https://jsfiddle.net/niranjan94/tkbcv3md/16/embedded/

External Resources:
Continue ReadingBuilding interactive elements with HTML and javascript: Drag and Drop