Category: Javascript

Vue 3 composition API tutorial: with example project

When Vue 3 was released one of the most exciting features are Composition API . An alternative to Options API.  In this article, let’s take a look at how we can use Composition API in our project

Full source code available in GitHub repo

Demo link: https://vue3-composition-api.pages.dev/

Vue 3 Setup

Now let’s start by installing Vue CLI globally. If you already have the CLI, make sure your running at least (I am using Vue CLI v5.0.4)

npm install -g vue-cli

We’ll use the Vue CLI to build a simple application( I am using vue3-composition-todo as project name here )

vue create vue3-composition-todo

Here I am selecting default Vue 3

After installation move into the folder and as shown above cd vue3-composition-todo and start-server npm run serve . This will start a development server and we can see it on http://localhost:8080/

Install plugins

Let us install Bootstrap for styles in our project

npm install bootstrap --save

lets import in bootstrap CSS in App.vue (We are using only Bootstrap CSS)

import 'bootstrap/dist/css/bootstrap.css'

Final code in main.js looks like below

import { createApp } from 'vue'
import App from './App.vue'
import 'bootstrap/dist/css/bootstrap.css'

createApp(App).mount('#app')

Create UI for TODO

First let’s create a file inside the component TodoList.vue

Inside template, we can do small HTML to show todo list

<template>
  <div class="hello">
    <section class="vh-100" style="background-color: #eee">
      <div class="container py-5 h-100">
        <div class="row d-flex justify-content-center align-items-center h-100">
          <div class="col col-lg-9 col-xl-7">
            <div class="card rounded-3">
              <div class="card-body p-4">
                <table class="table mb-4">
                  <thead>
                    <tr>
                      <th scope="col">No.</th>
                      <th scope="col">Todo item</th>
                      <th scope="col">Status</th>
                      <th scope="col">Actions</th>
                    </tr>
                  </thead>

                  <tbody data-v-3de47834="">
                    <tr class="" data-v-3de47834="">
                      <th scope="row" data-v-3de47834="">1</th>
                      <td data-v-3de47834="">Buy groceries for next week</td>
                      <td data-v-3de47834="">In progress</td>
                      <td data-v-3de47834="">
                        <button
                          type="submit"
                          class="btn btn-danger"
                          data-v-3de47834=""
                        >
                          Delete</button
                        ><button
                          type="submit"
                          class="btn btn-success ms-1"
                          data-v-3de47834=""
                        >
                          Complete
                        </button>
                      </td>
                    </tr>
                    <tr class="" data-v-3de47834="">
                      <th scope="row" data-v-3de47834="">2</th>
                      <td data-v-3de47834="">Pay credit card bill</td>
                      <td data-v-3de47834="">In progress</td>
                      <td data-v-3de47834="">
                        <button
                          type="submit"
                          class="btn btn-danger"
                          data-v-3de47834=""
                        >
                          Delete</button
                        ><button
                          type="submit"
                          class="btn btn-success ms-1"
                          data-v-3de47834=""
                        >
                          Complete
                        </button>
                      </td>
                    </tr>
                  </tbody>
                </table>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  </div>
</template>

<script>

</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h3 {
  margin: 40px 0 0;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #37dd92;
}
a.link {
  color: #3771dd;
}
.stricked {
  text-decoration: line-through;
}
</style>

Create composable function

Now we can create a new folder composable inside src (we can use clean code and write in separate composable function )

In composible/useTodoList.js we can add some basic TodosList

import { reactive } from "vue";
function useTodoList() {
  let state = reactive({
 
    todos: [
      {
        id: 1,
        title: "Buy groceries for next week",
        completed: false,
      },
      {
        id: 2,
        title: "Pay credit card bill ",
        completed: false,
      },
    ],
  });

  
  return {
    state,
  };
}

export default useTodoList

Now we can import useTodoList in TodoList.vue and tweak some code

<template>
 ...

                  <tbody>
                    <tr
                      v-for="(todo, idx) in state.todos"
                      :key="todo.id"
                      :class="todo.completed && 'stricked'"
                    >
                      <th scope="row">{{ idx + 1 }}</th>
                      <td>{{ todo.title }}</td>
                      <td>
                        {{ todo.completed ? "Completed" : "In progress" }}
                      </td>
                      <td>
                        <button
                          type="submit"
                          class="btn btn-danger"
                          @click="removeItem(todo)"
                        >
                          Delete
                        </button>
                        <button
                          type="submit"
                          class="btn btn-success ms-1"
                          @click="toggleCompleted(todo)"
                        >
                          {{ todo.completed ? "Re-open" : "Complete" }}
                        </button>
                      </td>
                    </tr>
                  </tbody>
             ...
</template>

<script>
import useTodoList from "@/composable/useTodoList";
export default {
  setup() {
    const { state } = useTodoList();
    return {
      state,
    };
  },
};
</script>
...

Let us try to run the server

npm run serve

Access http://localhost:8080/ and we can see our code is running 🙂

Add todo

Let us add some input fields to add a todo to list

in TodoList.vue

<form
                  class="row row-cols-lg-auto g-3 justify-content-center align-items-center mb-4 pb-2"
                  @submit.prevent="addToDo"
                >
                  <div class="col-12">
                    <div class="form-outline">
                      <input
                        type="text"
                        id="form1"
                        v-model="state.newTodo"
                        class="form-control"
                        placeholder="Enter a task here"
                      />
                    </div>
                  </div>

                  <div class="col-12">
                    <button
                      type="button"
                      class="btn btn-primary"
                      @click="addToDo"
                    >
                      Save
                    </button>
                  </div>
                </form>
...
<script>
...
  setup() {
    const { state, addToDo } =
      useTodoList();
    return {
      state,
      addToDo,
      
    };
};
...
</script>

In useTodoList.js we can add new methode and export

...  
function addToDo(e) {
    e.preventDefault();
    state.todos.push({
      id: state.todos.length + 1,
      title: state.newTodo,
      completed: false,
    });
    state.newTodo = "";
  }
...
return {
    state,
    addToDo, 
  };
...

We have a save function now, after typing on click of saving we call addToDo and push data into our todos object. and the table will re-render and show a new to-do items.

The same way we can add more functionality like removeItem (delete a todo item on click of delete button), toggleCompleted (toggle as completed and in progress) and addTodoForme (adding sample data )

Final code

final code in component/TodoList.vue

<template>
  <div class="hello">
    <section class="vh-100" style="background-color: #eee">
      <div class="container py-5 h-100">
        <div class="row d-flex justify-content-center align-items-center h-100">
          <div class="col col-lg-9 col-xl-7">
            <div class="card rounded-3">
              <div class="card-body p-4">
                <div>
                  <a
                    href="http://shabeebk.com/blog/simple-vue-composition-api-example-with-todo-app/"
                    target="_sb"
                    class="link"
                    >Read Full Blog
                  </a>
                </div>
                <h4 class="text-center my-3 pb-3">
                  Vue 3 with composition-api To Do App
                </h4>

                <form
                  class="row row-cols-lg-auto g-3 justify-content-center align-items-center mb-4 pb-2"
                  @submit.prevent="addToDo"
                >
                  <div class="col-12">
                    <div class="form-outline">
                      <input
                        type="text"
                        id="form1"
                        v-model="state.newTodo"
                        class="form-control"
                        placeholder="Enter a task here"
                      />
                    </div>
                  </div>

                  <div class="col-12">
                    <button
                      type="button"
                      class="btn btn-primary"
                      @click="addToDo"
                    >
                      Save
                    </button>
                  </div>

                  <div class="col-12">
                    <button
                      type="button"
                      class="btn btn-warning"
                      @click="addTodoForme"
                    >
                      Add sample
                    </button>
                  </div>
                </form>

                <table class="table mb-4">
                  <thead>
                    <tr>
                      <th scope="col">No.</th>
                      <th scope="col">Todo item</th>
                      <th scope="col">Status</th>
                      <th scope="col">Actions</th>
                    </tr>
                  </thead>

                  <tbody>
                    <tr
                      v-for="(todo, idx) in state.todos"
                      :key="todo.id"
                      :class="todo.completed && 'stricked'"
                    >
                      <th scope="row">{{ idx + 1 }}</th>
                      <td>{{ todo.title }}</td>
                      <td>
                        {{ todo.completed ? "Completed" : "In progress" }}
                      </td>
                      <td>
                        <button
                          type="submit"
                          class="btn btn-danger"
                          @click="removeItem(todo)"
                        >
                          Delete
                        </button>
                        <button
                          type="submit"
                          class="btn btn-success ms-1"
                          @click="toggleCompleted(todo)"
                        >
                          {{ todo.completed ? "Re-open" : "Complete" }}
                        </button>
                      </td>
                    </tr>
                  </tbody>
                </table>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  </div>
</template>

<script>
import useTodoList from "@/composable/useTodoList";
export default {
  setup() {
    const { state, addToDo, toggleCompleted, removeItem, addTodoForme } =
      useTodoList();
    return {
      state,
      addToDo,
      toggleCompleted,
      removeItem,
      addTodoForme,
    };
  },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h3 {
  margin: 40px 0 0;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #37dd92;
}
a.link {
  color: #3771dd;
}
.stricked {
  text-decoration: line-through;
}
</style>

In composable/useTodoList.js

import { reactive } from "vue";
function useTodoList() {
  let state = reactive({
    newTodo: "",
    todos: [
      {
        id: 1,
        title: "Buy groceries for next week",
        completed: false,
      },
      {
        id: 2,
        title: "Pay credit card bill ",
        completed: false,
      },
    ],
  });

  function addToDo(e) {
    e.preventDefault();
    state.todos.push({
      id: state.todos.length + 1,
      title: state.newTodo,
      completed: false,
    });
    state.newTodo = "";
  }

  function toggleCompleted(item) {
    item.completed = !item.completed;
  }
  function removeItem(item) {
    state.todos = state.todos.filter((newItem) => newItem.id !== item.id);
  }
  function addTodoForme(e) {
    e.preventDefault();
    const text = `New to do list item with id ${state.todos.length + 1}`;
    state.todos.push({
      id: state.todos.length + 1,
      title: text,
      completed: false,
    });
  }
  return {
    state,
    addToDo,
    toggleCompleted,
    removeItem,
    addTodoForme,
  };
}

export default useTodoList;

And final output

Conclusion

Finally, we’ve built our app with Vue 3 Composition API.
I hope you learned a few things about Vue 3 and Composition API, Let me know if you have any comments

You can download the full source code from my GitHub repo

Demo link: https://vue3-composition-api.pages.dev/

 1,184 total views

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",
},

 7,226 total views

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

promises and call back

promises and call back are only doing similar job,  but sometimes we have to think whether to have a callback function or promises.

Here we will be discussing about promises and call back function. So let have look on both callback function and promises and how it works.

Call back function

Callback functions are functions that are executed after completing one function.

For example, if we have to do something after getting the result from the server, then we can write a call back function and it will execute once it gets the result from the server.

Let us have a look on the below example:

function first(arg1, callback){
//do some code
//after that call back funtion will be callled
if(type of callback ==function ) 
callback(options);

}

 

promises

Promise is just a way of writing asynchronous code in a more synchronous fashion.
ie, When you call promises, it will return a promise value and the calling code will wait until the promise is full filled, before executing next.

angularjs promises example:

var promise = asyncGreet('Robin Hood');
promise.then(function(greeting) {
alert('Success: ' + greeting);
}, function(reason) {
alert('Failed: ' + reason);
});
 //then(successCallback, errorCallback, notifyCallback)

We can pass three parameters for ".then" function, of which one is on success, 
another one on failure and last one is notifyCallback .notifyCallback can be 
called more than one time to the show progress and it is an optional parameter.

 Some differences between call back promises

  • Call back can be called once or more than once (depends on how it is written).
  • Promises will be called only once
  • Call back can throw errors and exceptions (have to write more call back for errors)
  • Promises have error handling
  • then(fulfilledHandler, errorHandler, progressHandler)
  • No states in call back
  • May have one of 3 states: unfulfilled, fulfilled and failed or only move from unfulfilled to either fulfilled or failed
  • In call back we can call N function in N levels
  • Can write a sequence of N async calls without N levels of indentation

These are some of my view points, if you have any suggestions or addons, you comments are welcome.

 214,944 total views,  3 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

 7,936 total views

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;
        });
      });
    };

 

 3,211 total views

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


 3,512 total views

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 😉

 13,209 total views

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" />

 3,052 total views

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

 2,622 total views