CategoryJavascript

Start with react — React starter kit

Reactjs is one of the powerful library for building user interfaces.

Let’s start with reactjs project.

To start with reactjs I created a react-starter-kit which can be downloaded from github.

In this starter kit, I am using following modules.
Nodejs — Node server
Expressjs — Express framework
Reactjs — React as view layer
React-router — For routing the application
Eslint — For best practices.
Webpack — For bundling

First, we have to clone this repo.

git clone https://github.com/shabeeb/react-starter-kit
once it cloned we have to move to that directory
cd react-starter-kit
Then we have to install all depentency modules. dont worry below commands will do it.
npm install
Now our sample reactjs project is ready,
We can run development server using below command
npm run dev

Now go to the editor and change something in src/components/home.js and see the browser again, react-hot-loader will reload the page.

To run production build
npm run build
it will minify all the js/jsx code and save to build/bundle.js file
npm start or npm run start
will start server with production version.

You can remove the strict code check (best practices ) by removing below lines (line 25 to 30) of code from webpack.config.js
{
enforce: "pre",
test: /\.js$/,
exclude: /node_modules/,
loader: "eslint-loader",
},

532 total views, 4 views today

lazy scroll – infinite scrolling angularjs plugin

What is lazy scrolling?

lazy-scroll is an angularjs directive for infinite scrolling. Instead of click pagination links or going to next page , this will help to load data on scrolling like you see in Facebook. lazy-scroll will work even without jquery .

Download lazy-scroll

minified version      |     uncompressed version 

What you have to do to implement on angularjs project?

lazy-scroll is a simple directive for angularjs application. We just have to call the function which you want to call for pagination in lazy-scroll attribute.

It will magically load data and append into variable when user reaches bottom of the page. There are also API’s available to control the behavior.

Just see some demo samples.

 Check out some Demo

Demo with explanation can see here

How do I use in my project?

You can download the minified version   or you can use the cdn and follow the 3 simple steps below:

STEP 1 :

Add ascript at the bottom of the page after angularjs

<script src="path-to-script/angularjs.min.js"></script>
<script src="path-to-script/lazy-scroll.min.js"></script>
STEP 2:

Ensure that your application module specifies lazy-scroll as a dependency.

var app = angular.module("yourModule",['lazy-scroll']);
STEP 3:

Use the directive by specifying a lazy-scroll attribute on an element.

<div lazy-scroll="paginationFuntion()" lazy-scroll-trigger="80" >

That is it  and it will work like a magic!

What is next?

Check our API  here 

See some demo and implement 🙂

4 total views, no views today

Simple web server using nodejs

We can make a folder just like a web server using nodejs for quick jobs

First we can install connect and expressjs, serve-static with Node.js:

$ npm install connect serve-static

We can make .js file (serve.js) and write the below code in that file:

var connect = require('connect');
var serveStatic = require('serve-static');
connect().use(serveStatic(__dirname)).listen(8080);

Then in cmd, run this file:

$ node server.js

Now we can access the local server in URL:

 http://localhost:8080/myfiles.html

And can exit by pressing:

ctrl+c

1,416 total views, no views today

Clear your form using Javascript

If you need to clear all the input fields irrespective of type in a form, try the below code.  The below code works even if your fields contains place holders.

    $.fn.clearForm = function() {
      return this.each(function() {
        $(':input', this).each(function() {
          var type = this.type, tag = this.tagName.toLowerCase();
          if (type == 'text' || type == 'password' || tag == 'textarea')
            this.value = '';
          else if (type == 'checkbox' || type == 'radio')
            this.checked = false;
          else if (tag == 'select')
            this.selectedIndex = -1;
        });
      });
    };

 

700 total views, no views today

jquery scrollTop – with animation

The jquery scrolltop () method gets the top offset of the first matched element.

Let us have a look,

If we want to know vertical scroll postion of current window we can use,

scroll_leng= $(window).scrollTop();

It will return the vertical scrollbar position of corresponding to window.

like the same we can set the vertical scrollbar position of window into some postion as below

 $(window).scrollTop(position);

If we want to know vertical scroll postion of a perticular element window we can use,

scroll_leng= $(selector).scrollTop();

It will return the vertical scrollbar position of particular element.

like the same we can set the vertical scrollbar position of particular element into some postion as below

 $(selector).scrollTop(position);

Sometime we have to give animation also , it is simple by using animate function in jquery

$(selector).animate({scrollTop: scroll_value}, delay);

sample demo below:




Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry’s standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry’s standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry’s standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.



0 px

Now Let us look a demo with window object ,
Enter a value to scroll top


Now letus look scrollTo with animations

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry’s standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry’s standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry’s standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.



0 px

Now Let us look a demo with window object animated ,
Enter a value to scroll top


768 total views, no views today

Regular expression for at least one number capital letter and a special character


Here we are going to write a regular exprestion for Password to check the condition like , password must contain at least one number,one capital letter and one special character.

First we can write Regex as below,

^(((.*\d.*[A-Z].*[!@#$%^&amp;*? ~].*))|(.*[A-Z].*\d.*[!@#$%^&amp;*? ~].*)|(.*[!@#$%^&amp;*? ~].*[A-Z].*\d.*)|(.*[!@#$%^&amp;*? ~].*\d.*[A-Z].*))$

This will check the string contain at at least one number,one capital letter and one special character,

Here i am going to show examples with Javascript function ,

We can write a function in javascript as below

 function validatePassword(str)
            {
                // patter to match : Atleast one number ,one capital letter, one special charector
                var reg = /^(((.*\d.*[A-Z].*[!@#$%^&amp;amp;*? ~].*))|(.*[A-Z].*\d.*[!@#$%^&amp;amp;*? ~].*)|(.*[!@#$%^&amp;amp;*? ~].*[A-Z].*\d.*)|(.*[!@#$%^&amp;amp;*? ~].*\d.*[A-Z].*))$/;
                if (reg.test(str)) {
                    return true;                                     
                }
                else {
                    return false;                  
                }
            }

and we can pass the string as function argument “str”, It will return if it matches the condition else it will return false.

Let us look on the demo

Javascript function sample

Enter password :


Let us look a jquery demo

Jquery sample

Enter password :


You can download from github

Have a noce day 😉

2,311 total views, 2 views today

How to add integer only in a text field using jquery


To allow integer only in text field we can use the following jquery function .
We can write below code inside a document.ready function and give the class “integer-allowed” for the text box we needed.


 $('.integer-allowed').keyup(function () {
                            this.value = this.value.replace(/[^0-9\.]/g, '');
                            }); 

Working demo


Enter value (Numbers only allowed)

Working code

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
 <script  type="text/javascript">
$(document).ready(function() {
   $('.integer-allowed').keyup(function () {
          this.value = this.value.replace(/[^0-9\.]/g, '');
       });
});
</script>


<strong>Enter value (Numbers only allowed)</strong><br />
<input type="text" class="integer-allowed" name="demoname" /><br />
<input type="submit" class="" name="demosubmit" />

872 total views, 1 views today

Hello world in angular


Guys,

Today we are going to learning Hello world in Angularjs .

AngularJS, a JavaScript M-V-W (Model-View-What ever) framework developed by a Googler and supported by Google.
if you are using jquery in your application , Angular will amaze you. We are writing very less code in jquery , angular will minify it again !!

Angularjs is giving amazing support to AJAX and we can make a very interactive website with angularjs.

Angular can be defined as a client side javascript framework adding intractivity to HTML. As i mention on top angular is MVW framework
which means ,model view and what ever. There are many software architecture patterns like MVC,MVP (Model View-presenter).

But angular doesn’t care about software architecture . A basic concept of MVW is that all definitions are associated with a named Module.
Angular come with a rich set of APIs to defined and this modules can be linked together by dependency injection.

Hello world in Angular js

let us try a simple hello world in angular js

in order to write angular js in our application we need to include angular js in our HTML page,
We can download and include or we can directily include from CDN

Here i am including


<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.16/angular.min.js"></script>
<div  ng-app>  
  Write some text in textbox:
    <input type="text" ng-model="text" />
 
    <h1>Hello {{ text}}</h1>
</div>

Note that we didn’t write a single line of JavaScript and still this example works like a charm! Live example

Write some text in textbox:

Hello {{ text}}

Let us check step by step

Here i had included “ng-app” after. This tell angular that , angular need to monitor this section if we want angular to monitor one part of our application we can wrap with a div and we can write “ng-app” there. So angular will only monitor that part.

Now we defined ng-model=”text” in text box ng-model bind the state with model value.if we made any changes in the
textbox it will reflect {{text}}.

This is twoway binding. Angular will always keep an eye in ng-model defined and when ever it is changing ,
it will reflect on the ng-model value in double curly braces. .

This is a simple hello world application in angularjs

649 total views, no views today

Simple form submit in angularjs with php


Guys,

Today we are going to learning Angularjs, just try out What I found, an easier and simple way to write simple form submit in angularjs with php.

angularjs_PHP_form_submission

angular js with php form submission

We can make a HTML form to submit and save to database,

Here we are going to include 2 js files; one is Angularjs library and another one formjs.js which we will be using in writing controller of our form.

Let us dig deep into the form

  • We will be adding ng-app=”formExample” after the html tag -ng-app tells the angular, this block needs to be watched by the angular module.
  • After that we need to add the controller to form tag like ng-controller=”formCtrl”
    – we are going to define formCtrl in formjs.js to tell what are the action need to do with that form
  • Lastly we will add ng-click=”formsubmit(userForm.$valid)”
    On clicking the button, it will go to formsubmit function and we will pass the validation rules as parameters. We will use native $valid function to validate the form.

Sample HTML page – index.html page

<!DOCTYPE html>
<html ng-app="formExample">
    <head>
        <title>simple form with AngualrJS</title>
        <link rel="stylesheet" href="css/bootstrap.min.css" type="text/css" />
        <script src="js/angular.js" ></script>
        <script src="js/formjs.js"></script>
    </head> 

    <body>

        <div ng-controller="formCtrl">
            <form  name="userForm"  class="well form-search"   >
                
                <input type="text" ng-model="name" class="input-medium search-query" placeholder="Name" required >
                <input type="email" ng-model="email" class="input-medium search-query" placeholder="Email" required >
                <input type="text" ng-model="message" class="input-medium search-query" placeholder="Message" required >
                <button type="submit" class="btn" ng-click="formsubmit(userForm.$valid)"  ng-disabled="userForm.$invalid">Submit </button>
		
            </form>
            <pre ng-model="result">
                {{result}}
            </pre>
        </div>
    </body>

</html>

Now we will have a look on the javascript (formjs.js) file

  • First we are going to define the module as “formExample”.(We have already included in html as mentioned above).
  • Next to that we will define our controller with two dependency, ‘$scope’ and ‘$http’. $scope is for current scope and $http for ajax submission.
  • Later we will define formsubmit function and we will pass the validation status as parameter.
  • Now we will fetch all the values from the form and validate, on successful validation it is send to submit.php as json data. If form validation fails, it will show an alert message.

javascript file
formjs.js

<pre class="lang:default decode:true " title="formjs.js" >


/**
 * @filesource : formjs.js
 * @author : Shabeeb  <mail@shabeebk.com>
 * @abstract : controller fo HTML page
 * @package sample file 
 * @copyright (c) 2014, Shabeeb
 * shabeebk.com/blog
 * 
 *  */



var app = angular.module('formExample', []);


app.controller("formCtrl", ['$scope', '$http', function($scope, $http) {
        $scope.url = 'submit.php';

        $scope.formsubmit = function(isValid) {


            if (isValid) {
              

                $http.post($scope.url, {"name": $scope.name, "email": $scope.email, "message": $scope.message}).
                        success(function(data, status) {
                            console.log(data);
                            $scope.status = status;
                            $scope.data = data;
                            $scope.result = data; 
                        })
            }else{
                
                  alert('Form is not valid');
            }

        }

    }]);</pre> 

In submit.php page we are going to retrieve the json data and decode using it json_decode.
For that we can use the below code:

$post_date = file_get_contents(“php://input”);
$data = json_decode($post_date);

Below is the query to save data to database .
Here I am just printing all the values which we will get from the form for illustration.
php submission form

submit.php

<?php
/**
 * @filesource : submit.php
 * @author : Shabeeb  <mail@shabeeb.com>
 * @abstract : simple submission php form
 * @package sample file 
 * @copyright (c) 2014, Shabeeb
 * 
 * 
 *  */

$post_date = file_get_contents("php://input");
$data = json_decode($post_date);


//saving to database
//save query

//now i am just printing the values
echo "Name : ".$data->name."n";
echo "Email : ".$data->email."n";
echo "Message : ".$data->message."n";



?>

Download files

Demo

Enjoy your Coding with Coffee 😉

12,821 total views, 9 views today

© 2017 shabeeb Blog

Theme by Anders NorénUp ↑