Wysiwyg: What you see is what you get editor

I created a wysiwyg editor using Javascript, jQuery, HTML5 and bootstrap for designing. It has some basic formatting options. I will keep adding and making it robust. But it is yours to use for the purpose.

Here is the link to demo. It is compatible with firefox and chrome for now but not that much robust.

Backbone.js: MVC framework for Javascript – Views

In the previous post, we saw Routers of Backbone. Views as name suggests give views to your page, form whatever. In a single page application, each page has a view and they in result have multiple form views eg- one for login, one for home, one for landing page. How it is done?

As we have seen in the routers we created a single page (http;//yourwebsiteurl/) and it had three views default, loginpage, loginuser. We are going to take advantage of the router and will create views for each of them

Requirement: Backbone.js ( + Underscore.js ), jQuery.js ( latest )

Usage:

Consider the html below the body of a html page which we are using, default-view, userpage-view, userlogin-view.

<html>
<!--  Remember the order of the scripts. We will describe the the contents of default.js in next post while summing up the example. Right now example wont work, that is, all the views will be displayed-->
     <script type="text/javascript" src="jquery.js"></script>
     <script type="text/javascript" src="underscore.js"></script>
     <script type="text/javascript" src="backbone.js"></script>
     <script type="text/javascript" src="view.js"></script>
     <script type="text/javascript" src="router.js"></script><!-- Router we explained in the previous post is used-->
     <!-- script type="text/javascript" src="default.js"></script -->

     <body>
         <div id="default-view">
               <input id="loginpage" type="button" value="Login Page" />
         </div>
         <div id="loginpage-view">
               <input id="email" type="text" name="email" /><input id="login" type="button" value="Login" />
         </div>
         <div id="loginuser-view"></div>
    </body>
</html>

Contents of view.js

var pageview = Backbone.View.extend({  //Creating the view by extending backbone.

    el: $(document), //it is not playing role in this example as we are creating multiple views. if in case we were implementing let say loginuser view only, we would have set it $('#loginuser').

    events: { //events that we needs to bind, here click on buttons is used.
        'click input#loginpage': 'loginpage',
        'click input#login': 'loginuser'
    },

    initialize: function(){   //this is called when an object of view is created.
        _.bindAll(this, 'render', 'loginpage', 'loginuser', 'loginpageview', 'loginuserview');  //binds all the function that we to the view(pageview) object
       // this.model = new loginModel();  //comment it as we are not implementing model
        this.render();   //render function will be called, it is sort of convention to use it to show default view. not necessary always.
    },

    render: function(){ //default view
        $('#loginuser-view').hide();
        $('#loginpage-view').hide();
        $('#default-view').show();
    },

    loginpage: function(){ //when Login Page button is clicked this function is called which we bound in events.
//Your pre processing of data if any.
        window.location.href = 'http://yourwebsiteurl/#/loginpage';
    },

    loginuser: function(){ //when login button is clicked this function is called which we bound in events.
//Your pre processing of data if any. Generally model is used here. In this case when you will get email and password use model to check if the user is valid. Then perform resultant action.
    	var email = $('#email').val();
    	window.location.href = 'http://yourwebsiteurl/#/loginuser/'+email;
    },

    loginpageview: function(){
//This function will display the contents of loginpage view.
    	$('#default-view').hide();
        $('#loginuser-view').hide();
        $('#loginpage-view').show();
    },

    loginuserview: function(email){
/* Resultant of the login action is this view. This is just for the sake of explaining views. */
        $('#default-view').hide();
        $('#loginpage-view').hide();
/*some action here to retrieve the view of logged in user, most probably from database */
	$('#loginuser-view').text('Hi '+email);
        $('#loginuser-view').show();
    }
});

Explanation:

Everything is explained in the comments. We are left with only connecting router with view, which will be the content of “default.js”. In the next post over simple working backbone backed application will be ready (minus model). Hope I have managed to make you understand backbone.

Backbone.js: MVC framework for Javascript – Routers

In the previous post, we saw Models of Backbone. We will see about Router in this post.

Router provides method for routing client side pages. Pages using REST API have multiple views on one page and are displayed as a result of some action. Like you have one view of login and other of home page. So when you login the view of the page changes and it displays your home page. Router helps to keep url tidy and makes easy to perform action accordingly. Lets take a look at example.

A normal web application.

URL for signup page: http://example.com/signup.php

URL for home page: http://example.com/home.php?u=1234

Single page web application.

URL for signup page: http://example.com#/singup

URL for home page: http://example.com#/home/1234

Requirement: Backbone.js (+Underscore.js),  jquery.js (latest)

Using:

Contents of router.js

//Router is created using Router of Backbone.
var route = Backbone.Router.extend({
//initialize is called when we will create a route object. pageview is the view of the page which will be created in next post
 initialize: function(pageview){
//We store the views so that it is not called everytime the url changes.
 this.view = pageview;
 },
//routes are the link with respect to the default url, we want to implement.
 routes:{
 'loginpage': 'loginpage', //http://yourwebsiteurl/#/loginpage
 'loginuser/:email': 'loginuser', //:email is the variable which is analogous to get method, which backbone matches by itself.
 '': 'index' //http://yourwebsiteurl/
 },

 loginpage: function(){
//Whenever we land on the url using loginpage its view must be called.
 this.view.loginpageview();
 },

 loginuser: function(email){ // matched :email from  url can be taken in variable(like email in our case) in this function.
//Whenever we land on the url using loginuser its view must be called. We can store multiple views and call them as required.
 this.view.loginuserview(email);
 },

 index: function(){
//by default this is called as we have marked.
 this.view.render();
 }
});

Explanation:

Everything is explained in comments. We will use this router.js in our next post on views.

Backbone.js: MVC framework for Javascript – Models

There are many MVC frameworks for Javascript. Spine.js and Backbone.js are most famous and used of all. But we’ll be seeing only Backbone.js here only.

Before that, spine is fundamentally different from backbone. Spine strictly follows MVC model, while there is actually nothing like Views in backbone conceptually. Plus there is no controller either in backbone, C stands for collection.

So, model is model+controller, and controller is views in backbone. Backbone also uses Underscore.js as helper for collections. So, we need both underscore and backbone for the application while spine is used alone.

We will start with models first. Model have numerous methods to perform various operations. The example are based on ajax requests, instead of CRUD operations using REST API. We’ll get back to those later. Its not that complicated just lets get started with what we know already.

Requirement: Backbone.js ( + Underscore.js ), jQuery.js ( latest )

Usage:

/*
* Backbone model should have everything which is interacting with your database.
* A user model can be implemented by extending backbone's existing model and its methods.
*/
var book = new Backbone.Model.extend({
// defaults method holds key-value pair object. These are like class variables. You can set them and use them later.
    defaults: {
        'Title': '',
        'Author': '',
        'Publisher': '',
        'ISBN_No': 0
    },

/*
* fetch method by default is associated with url we specify for model but we have overwritten it for now.
* We are using fetch for fetching the data from database.
*/
    fetch: function(){
        var url = 'http://example.com';
        var call = 'getBook';
        var id = '12';

// Ajax call
        $.ajax({
            url: url,
            type: 'GET',
            dataType: 'JSON',
            data: {'call': call, 'id': id},
            success: function(data){
                //Do something with your data using jquery or return some html from the handler.
            }
        });

    },

/*
* save method is used for saving data to database. By default on calling save default url is used to save.
* We have overwritten just for now. Save by itself identify create and update operation for database.
* We will come back to this later
*/
    save: function(){
/*
* this is pointing to the instance which has called save method.
* get method for model will get you the values stored in the variable in defaults of the model's instance.
*/
        var url = 'http://example.com/savebook.php';
        var data = {'title': this.get('Title'), 'author': this.get('Author'), 'publisher': this.get('Publisher'), 'isbn': this.get('ISBN_No')};
        $.ajax({
            url: url,
            type: 'POST',
            dataType: 'JSON',
            data: data,
            success: function(data){
                //Do something when your data get saved in your database.
            }
        });
    },
/*
* When we try to update the defaults or save the model validate methods is called by default.
* It should return nothing if validation succeeds because this method by default returns true;
* In case of fail an error string can be returned as below.
*/
    validate: function(attrs){
        //validation for the values to be saved.
        var error = '';

        if(attrs.ISBN_No == 0)
            error += 'ISBN No cannot be equal to 0';
        if(error != ''){
             return error;
        }
    }
});

Explanation:

Everything is explained in comments. Also go through the methods associated with model here.

Hope you like it. It may not seem very intuitive for now. But I think you must have gotten taste for it. We’ll work with Routers in upcoming post.

Notify.js: jQuery plugin for notification

Notify.js is a small jQuery plugin to display notification. It creates a notification box for the notification to display. You might have seen the real time notifications of Facebook in bottom-left corner, this plugin does the same.

You can see the demo and download it from here.

Refreshing a particular div

With the evolving and more dynamic web application. Refreshing particular part of the page is very much required. Recommended ads on Facebook use it. When we click on like ad, it sends the server tag of the ad the server recommends you another ad. The use of it I can think of is for Views. Create a view of different object on your page and call them using load method.

Required: jquery-latest.js

Using:

<script type="text/javascript" src="jquery-1.6.js">
</script>
<script type="text/html">
      $('#newcontent').load('file2.php');
</script>
Explanation:
       # is selector for id which is newcontent, a div here. Load method loads the content of file2.php in newcontent div.

Creating custom HTML tags

Why not have something like facebook login button, which we see on many sites now. This is basically custom tag which facebook has made. In this post we will see how it can be made.

Requires: HTML, Javascript, CSS

Using:

CSS for the custom tag

<style type="text/css">
@media all 
{
IW\:button {
 font-size: 24pt;
 background-color:#999;
 border-top:1px solid #CCC;
 border-left:1px solid #CCC;
 border-right:2px solid black;
 border-bottom:2px solid black;
 border-radius:5px;
 font-family:"Times New Roman", Times, serif;
 cursor:pointer; 
 color:black;
 padding:1px;
 padding-left:2px;
 padding-right:2px;
}
} 
span{
 color:white;
 padding-left:2px;
 padding-right:4px;
 border-right: 2px solid #020;
}
</style>

Javascript for the custom tag

<script type="text/javascript">// <![CDATA[
function ActasMytag(myTag)
{
myTag.style.borderLeft = '1px solid #CCC';
myTag.style.borderTop = '1px solid #CCC';
myTag.style.borderRight = '2px solid black';
myTag.style.borderBottom = '2px solid black';
}

function ActasButton(myTag)
{
myTag.style.borderLeft = '1px solid black';
myTag.style.borderTop = '1px solid black';
myTag.style.borderRight = '2px solid #CCC';
myTag.style.borderBottom = '2px solid #CCC';
}
</script>

HTML to be written for the custom tag

Add ‘IW’ in xmlns of HTML.

<IW:button onmousedown="ActasButton(this)" onmouseup="ActasMytag(this)">IW Custom Button</IW:button>

Explanation:

Lets start with the HTML first.

Adding IW is an not that important. But should be done as browser can ignore the custom tag as it is not known to it.

Look at the html tag we have created. ‘IW’ is tag name we want to create. Notice the specified ‘button’ after ‘:’, it is written because only one custom tag can be inserted in a page but can have any number of attributes. So, to solve that problem we distinguish different tags on the basis of value written after ‘:’. Next we are calling Javascript function to give this tag functionality of a button.

Javascript

Line 2: This function changes the property back to default property we have set for our custom tag. It is called on mouseup.

Line 10: This function simulates the pressing of button. It is called on mousedown.

CSS

Line 2: @media all, what it does is the xmlns IW will work across the page and will apply CSS specified inside it.

Line 4: IW\:button selects the IW tag with attribute button and apply the defined CSS to it.

Note:

  • @media all is important part otherwise CSS may not work.
  • Modern browsers may run without xmlns and @media all.
  • <IW:button> should be there otherwise if IW is only specified, only one custom tag can be used.
  • JS function ActasButton is important because it makes button looks like its pressed on mouse button down.
  • Functionality like redirecting can be given onclick or performing any other action.

You can download the working repository from github.

Tag hinting or label hinting javascript library

Tag hinting or label hinting is a very useful thing for forums and blogs, where it is used to tag post or as generally termed as auto suggestion.
tag-hinting.js is a Javascript library for embedding tah hinting to a webpage, it is very useful on blogs and forums where you tag post. I have created it in such a way that it is easy to use and understand. All you have to do is include the tag-hinting.js file in your webpage and write the following lines:
&lt;script type=&quot;text/javascript&quot;&gt;
arr = ['your','tag','values'];
&lt;/script&gt;

and a div to show the hints.

&lt;div id=&quot;hintwords&quot; style=&quot;display: none;&quot;&gt;&lt;/div&gt;

The function which is to be called is:

hint(this, event)

Note:

  • Other style values can be added to above div.
  • id of the div has to be hintwords.
  • arr has to be declared and should be after file inclusion.
  • hint take only the specified arguments.
  • hint can work on keypress, keyup and keydown events.

There is a example file on this in repository on git. Pretty soon i’ll be sharing a library which interacts with database and can be helpful in searches.

Javascript Library for dynamic element creation

d-element.js is a javascript library I have created. With the help of it you can easily create dynamic elements, in just one line. Try it!

Required: d-element.js

Using:

$('div').addelement('p',{'background-color':'blue'},'hi');

Explanation:

     This has identical syntax as of jQuery. ‘div’ here is selector which selects all the div tags.
     addelement method takes three arguments of which first is required and null can be given in other two.

Note:

  •     Only element(ex: div), id(ex: .id), class(ex: #class) can be used as selector for now, element under which element has to be created.
  •     First argument of addelement is required which is the element to be created.
  •     Second argument if given should be associative array, it is for the attributes of the element to be created.
  •     Third argument is data, if any string to be inserted. It can be a string having other html elements.
  •     Check console for error logs.

jQuery plugin – cycle: Slideshow of your own in a sec

The jQuery Cycle Plugin is a slideshow plugin that supports many different types of transition effects. It supports pause-on-hover, auto-stop, auto-fit, before/after callbacks, click triggers and much more.

 

Requires: Javascript, jquery

Using:

&lt;div class=&quot;classObject&quot;&gt;
&lt;img src=&quot;img1.jpg&quot; alt=&quot;&quot; /&gt;
&lt;img src=&quot;img2.jpg&quot; alt=&quot;&quot; /&gt;
&lt;img src=&quot;img3.jpg&quot; alt=&quot;&quot; /&gt;
&lt;/div&gt;

&lt;script type=&quot;text/javascript&quot; src=&quot;jquery.js&quot;&gt;
&lt;/script&gt;
&lt;script type=&quot;text/javascript&quot; src=&quot;jquery.cycle.js&quot;&gt;
&lt;/script&gt;
&lt;script type=&quot;text/javascript&quot;&gt;
  $(document).ready(function(){
       $('#classObject').cycle({
               fx:'shuffle',
               shuffle:{
                         top:-230,
                         left:230
                       },
               easing:'easeInOutBack',
               delay:-2000
       });
  });
&lt;/script&gt;
Explanation:
          Line 12: it means check if document is ready to apply javascript over it.
          Line 13: $(‘#classObject’) selects the object having class name classObject. # is called selector. We apply a method cycle over this class.
          Line 14: fx(function/effect) is required parameter which can be defined in many ways here it is shuffle.
          Line 15: shuffle is optional, if its not defined there is default value top:15px and left: width of container. Here both are defined in line 16 and 17.
         Line 19: easing can only be used with easing plugin of jquery.
         Line 20: delay is also required parameter, which takes time for effect for single transition in milliseconds.

 

Note:

  • Take care of the brackets people usually get it wrong. 
  • “id” can also be used instead of class (instead of #(hash) .(dot) is used as selector). 
  • jquery.js is required.
  • jquery easing plugin will make it great.
  • Give 3-4 div same class name, by this way there will equal number of div having slideshow of there own. Like if you need multiple slides at a time slideshow.
  • There are many other cool fx. You can also create custom.
  • There are also some other parameter apart from fx, delay etc. Take a look into the coding of jquery.cycle for other parameters.

There some great demos on the site of jQuery cycle. You can also find easing plugin on this site.