Showing posts with label Javascript. Show all posts
Showing posts with label Javascript. Show all posts

Sunday, July 28, 2019

React with Redux authorization workflow example (react-router-dom v6)

This a simple React example which demonstrates how to restrict access to routes to authenticated users.

Complete source code can be found in GitHub -
https://github.com/madan712/auth-workflow

Below packages are used in this example -
  • React router - React Router is used to manage navigation in react application
  • Redux - Redux is used to manage state of react applications
  • react-router-dom v6 - React routing library
  • react-bootstrap - React-Bootstrap is a complete re-implementation of the Bootstrap components using React
  • react-redux-toastr - Used to show alert messages
  • Webpack - Webpack is used to create prod ready build which can be used to deployed in production
  • Babel - Babel is used to convert ECMAScript 2015+ code into a backwards compatible version of JavaScript in current and older browsers or environments

About the example - We have a landing page i.e public page which can be viewed by anyone. As this is a public page, user need not required to go through any sort of authorization


Our private page is a restricted page. If user clicks on private page link, user is taken to login page where user is asked to enter user name and password



Saturday, June 1, 2019

Example with React, Redux and Axios API

In previous article we have seen a simple react with redux example. In this article we will add Axios api to it. Axios is used for Promise based HTTP client for the browser and node.js. To know more about axios package, click here.

In this example we will get input name from user and hit a hello world rest endpoint. For running this example you may need to install below packages -
  • redux
  • react-redux
  • axios
  • redux-thunk


App.js

Sunday, March 31, 2019

Simple React + Redux example

In the previous article we have seen Spring boot with react example. In this example we will see how to configure React with Redux. Now what is all this fuss about Redux?


In simple term Redux is used to manage state of your application. As your application starts growing it gets difficult to manage state of your application. This is when Redux comes to help you.

Redux data flow



Lets see a simple counter example. Assuming npm is already installed in your machine. If not, install npm.

Saturday, September 3, 2016

Drag and Drop example in HTML5

HTML5 has made dragging and dropping objects from one place to another very easy.

We will see an example of the HTML5 API’s that can be used to drag and drop objects
  1. How to make the object draggable
    • For making object draggable, we need to first set the draggable attribute of that object to true.
    • Then use the onDragStart method to capture the data that needs to be dragged
  2. How to make the object Droppable
    • We use 3 methods that will be used to define a object is droppable
      • onDrop
      • onDragEnter
      • onDragOver

Please see the sample code

Output



Author -

I am Ketan and have a blog KSCodes that is developed to share some of the common examples that we come across in web development. You can get examples on java tutorials and spring tutorials.

Wednesday, September 24, 2014

Javascript code for 2048 number puzzle

Other day I was playing this game on my android mobile and I was so amazed with it that I thought why not try to write a JavaScript code for this game. So here I am with it.

new game

Score :

HOW TO PLAY: Use your arrow keys to move the tiles.

Please see the complete source code -


Output -

Saturday, September 14, 2013

Javascript - Password strength meter

Password Strength Algorithm

Password Length:
5 Points: Less than 4 characters
10 Points: 5 to 7 characters
25 Points: 8 or more

Letters:
0 Points: No letters
10 Points: Letters are all lower case
20 Points: Letters are upper case and lower case

Numbers:
0 Points: No numbers
10 Points: 1 number
20 Points: 3 or more numbers

Characters:
0 Points: No characters
10 Points: 1 character
25 Points: More than 1 character

Bonus:
2 Points: Letters and numbers
3 Points: Letters, numbers, and characters
5 Points: Mixed case letters, numbers, and characters

Password Text Range:

>= 90: Very Strong
>= 70: Strong
>= 50: Good
>= 30: Weak
>=  0: Very Weak

Wednesday, January 23, 2013

JavaScript - onscroll function not working


Today I faced a weird issue, when I add below DOCTYPE in HTML or JSP file onscroll function stops working

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

Also I saw that, document.body.scrollTop is always coming as 0 and document.body.scrollHeight & document.body.clientHeight are always same no matter where my scroll bar is.

I didn't get much time to do research on it however to resolve this I modified DOCTYPE as shown below. If you need quick fix please add below DOCTYPE in your HTML or JSP file.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

If I find more info on it, I will update the post.

Wednesday, January 16, 2013

Open Popup div with disabled background using Javascript


Let's see a simple HTML code for Popup div with disabled background. On clicking a particular link it will open a popup div with desire information, it can also be used as popup window. Below example shows following features -

  1. Onclick opens a popup div with disabled background
  2. Close popup div using escape button
  3. Opens popup div exactly at the center of the screen
  4. Opacity can be controlled within 

Below is the tested code, directly you can save it and see the output.

Tuesday, January 15, 2013

Javascript example - Set cookies and Remove cookies


A cookie is a variable that is stored on the users browser and depends on browser's configuration. A cookie, also known as an HTTP cookie, web cookie, or browser cookie, is usually a small piece of data sent from a server and stored in a user's web browser while a user is browsing a website. When the user browses the same website in the future, the data stored in the cookie can be retrieved by the website to notify the user's previous activity like clicking particular buttons, logging in, or a record of which pages were visited.

Example - The first time a user visits to your web page, he or she must fill in her/his name. The name is then stored in a cookie. Next time when the user visits at your page, he or she could get a welcome message like "Welcome Alex!" The name is retrieved from the stored cookie. In the below example we will see how to set cookie and remove cookie.

Below is the tested code, you can directly save it and see the output.

Friday, January 11, 2013

Javascript - Unterminated string constant


If you receive below error, check at the specified line. As the error suggest, most probably you have added a line break or some incorrect syntax. To resolve the error just remove the line break or check for proper syntax and the error would go off.

Message: Unterminated string constant
Line: 443

 If you are using Linux, check for line break using below command in vi editor. It will show you symbol '$' at the end of each line. Just remove the line break at the specified line.

 :se list

As the error suggest 'Unterminated string constant', mostly it may occur due to some incorrect syntax.

Tuesday, January 8, 2013

JavaScript - How to get random numbers and random alpha-numeric numbers?


In this article we will see how to generate random numbers and alpha-numeric numbers in JavaScript  We will use JavaScript Math.random function to generate random numbers.

Math.random function returns a floating-point, pseudo-random number in the range [0, 1) that is, from 0 (inclusive) up to but not including 1 (exclusive), which you can then scale to your desired range.

Please see the below function.


1. Get random numbers

//get random numbers
function getRandomNumber() {
var max = 10;
var randomnumber = Math.floor(Math.random()*max)
return randomnumber;
}

2. Get random numbers between minimum and maximum range

//get random numbers between minimum and maximum range
function getRandomNumber() {
var min = 10;
var max = 20;
var randomnumber = Math.floor((Math.random()*(max - min + 1))+min);
return randomnumber;
}


Monday, November 5, 2012

How to iterate Java object in JavaScript using JSON?


You may require passing a java object to javascript and iterating through it. Java object could be literally anything whether it List, Map, List of Map, Map of List etc.
For example: ArrayList<String>, Hashtable<String,String>, ArrayList<Hashtable<String,String>>, Hashtable<String,ArrayList<String>> etc.

This can be easily achieved using JSON. To run below JSP you need to include json-simple-1.1.1.jar in classpath. Download the JAR file from http://code.google.com/p/json-simple/

About the example: In below example I have created a java object i.e. HashMap<String, ArrayList<String>>. Add some values to the object. Convert the object into JSON string using method JSONValue.toJSONString(). In JavaScript pass the JSON string to JSON.parse() and get the corresponding JavaScript object. Now you are ready to iterate it using below syntax. Please see the self explanatory example below.

Friday, November 2, 2012

Convert an object to json string and vice versa in Java and Javascript

Today we will see how to convert an object to json string and vice versa. An object could be JSONObject or any Java Object for example Map of list, List of map etc. Also please see my earlier post on Java Examples for JSON encoding, click here.

Note - To run below examples you need to include json-simple-1.1.1.jar in classpath. Download the JAR file from http://code.google.com/p/json-simple/

Example 1 : Convert JSONObject to JSON String and vice versa

Output :

{"Name":"Ramesh","Nickname":null,"Salary":15000.0,"isPermanent":true,"EmployeeId":121}
121
Ramesh
15000.0
true
null

Thursday, November 1, 2012

JSTL: How to access fmt:message from Javascript


You might have seen How to use fmt:message and ResourceBundle from JSP and Java in my earlier post, click here.

Now we will see how to use fmt:message from Javascript. Its very simple to use JSTL's fmt tag in JavaScript to localize alert messages.

I found two ways in which you can access values from a property file in javascript. Please see the sample codes below.

Method 1.

<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<script type="text/javascript">
<!--
var msg = {
prop1: "<fmt:message key="prop1" />",
prop2: "<fmt:message key="prop2" />"
};

function test() {  
 alert(msg.prop1);
alert(msg.prop2);
}

//-->
</script>

Method 2.

<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<script type="text/javascript">
<!--
<fmt:message key="prop1" var="prop1"/>    
var prop1 = "${prop1}";

function test() {  
 alert(prop1);
}

//-->
</script>

Saturday, September 8, 2012

How to create a Jigsaw puzzle using JSP and Javasacript?


What is Jigsaw puzzle?
A Jigsaw puzzle is a tiling puzzle that requires the assembly of numerous small pieces. Each piece usually has a small part of a picture on it; when complete, a jigsaw puzzle produces a complete picture.

In this article we will see how to create a Jigsaw puzzle using javascript. Initially you will require to cut an image into various pieces, that can be done using a simple java program.

Please see the below Java program that will cut an image into number of pieces for a Jigsaw puzzle. Just provide the desire number of rows and column, it will automatically cut an image into that number of pieces.

Please see the self explanatory Java program below

Sunday, September 2, 2012

Java / JSP : Simple image cropping example


In this article we will see how to crop an image in Java. You are in this page then u might surely know what exactly the Image cropping is, it is nothing but removal of the outer parts of an image  to improve framing, to change aspect ratio etc.

Image cropping can be implemented easily using Java. First lets see the basic example of image cropping. In the below code we have used getSubimage() function of BufferedImage to achive image cropping feature. No need to add any Jar file directly you can run below code and see the output.

Please see the self explanatory java code below.

Friday, August 10, 2012

JavaScript - Simple pagination logic


This article will help you to know how you can create a pagination in any webpage. Here I have used it in JavaScript, of course you can use it in any other language as u wish like Java, PHP, ASP etc.

What is Pagination?

Pagination is nothing but the sequence of numbers assigned to a content in webpage. Lets say if you want to show number of contents in a particular web page, its not recommended to show all of them in a single page instead show specific number of contents in one page followed by next set of content in next page and provide navigation to go through each page. In the same way when we do Google search you can see navigation appears at the bottom of the page to go to the next page.


Please see the self explanatory html code below, no need to have any server directly you can run and see the output

Tuesday, July 3, 2012

Javascript : On scroll fill data at the end of the page

Other day while browsing facebook, i saw when we scroll to the end of the home page it fills more data without refreshing the whole page. Again when u reach to the end of the page it fetches more data and this continues. I didn't bother to check its upper limit, may be at some point of time it will go out of memory of the browser.

So lets see how this functionality can be achieved. Below javascript variables can be used to detect when user have reached to the end of the body.

  • document.body.scrollTop - scroll bar position
  • document.body.scrollHeight - height of the scroll bar
  • document.body.clientHeight - total height of the body

so if (scrollHeight - scrollTop) is equal to clientHeight you have reached to the end of the body. And obviously you can use various APIs like AJAX, DWR, Ext JS etc to load data without refreshing the whole page.

Below is the standalone tested HTML code, directly you can test this example no need to have any server. Please see the self explanatory html code.


<HTML>

<HEAD>
<TITLE>Scroll Example</TITLE>
<SCRIPT LANGUAGE="JavaScript">
<!--
divCount = 1;
function onScrollDiv()
{
if((document.body.scrollHeight - document.body.scrollTop) == document.body.clientHeight)
{
onLoadData();
}

return false;
}

function onLoadData()
{
previousCount = divCount;
divCount++;

//Get data using AJAX, DWR, Ext JS etc
htmlData = "<table width='50%' border='1'><tr><td height='200px' align='center'>"+new Date()+"</td></tr></table>";

document.getElementById("div"+previousCount).innerHTML = htmlData;

var newDiv = document.createElement("div");
newDiv.innerHTML = "<div id='div"+divCount+"'>Loading...</div>"
var previousDiv = document.getElementById("div"+previousCount);

insertAfter(newDiv,previousDiv.parentNode);
return false;
}

function insertAfter(new_node, existing_node) {

if (existing_node.nextSibling) {
existing_node.parentNode.insertBefore(new_node, existing_node.nextSibling);
} else {
existing_node.parentNode.appendChild(new_node);
}
}

//-->
</SCRIPT>
</HEAD>
<BODY onload="onLoadData();" onscroll="onScrollDiv();">
<center>
Simple Javascript example which fills data when you scroll at the end of the file same like Facebook
<br />
Resize the window so that scroll bar appears on the right hand side then you can test it.

<div>
<div id="div1"></div>
</div>

</center>
</BODY>
</HTML>

Friday, June 29, 2012

Javascript : Encode special characters

In Javascript, you may required to escape special characters from a text at some point of time and later you may need to retrieve the original text. This may be because of some logic or for passing as argument in some function. The basic is very simple we will write a encode function which will encode the special characters and a decode function which will get the original text out of encoded text.

Please use the below functions in your code accordingly.

<script language="Javascript">


   var toEncode = new Array(" ","!","@","#","$","%","^","&","*","(",")","-","_","=","+",":","\;",".","\"","'","\\","/","?","<",">","~","[","]","{","}","`");
 var toDecode = new Array("%20","%21","@","%23","%24","%25","%5E","%26","*","%28","%29","-","_","%3D","+","%3A","%3B",".","%22","%27","%5C","/ /","%3F","%3C","%3E","%7E","%5B","%5D","%7B","%7D","%60");

 function encode(val)
 {
  for (var i = 0; i < toEncode.length; i++)
  {
   val = val.replace(toEncode[i],toDecode[i]);
  }
  
  return val;
 }

 function decode(val)
 {
  for (var i = toDecode.length; i >= 0; i--)
  {
   val = val.replace(toDecode[i],toEncode[i]);
  }
  
  return val;
 }

</script>

Monday, June 18, 2012

DWR Hello World example

DWR - Direct Web Remoting

DWR is a Java library that enables Java on the server and JavaScript in a browser to interact and call each other as simply as possible. In simple words DWR is Easy Ajax for Java. Unlike AJAX you don't have to write codes to get XHTML object or check for state change etc. To know more about DWR, click here.

DWR is supported by almost all browsers like Firefox,Internet Explorer,Opera and Safari. To know more, click here.

About the example

We will create a simple java class (i.e HelloWorld.java) with a method sayHello() which will accept a name and print Hello name. We can call this java fuction with JavaScript in a browser. Same as Ajax call without refreshing the whole page.

Below are the steps to run the example.

1. For running the below example you need to add below mentioned JAR file in lib folder of your web project.

  • dwr.jar
  • commons-logging-1.1.1.jar 

For downloading dwr.jar, click here
commons-logging-1.1.1.jar, click here.


2. Add the DWR servlet definition and mapping to your application's web.xml. This is just like defining a normal servlet.


<servlet>
  <display-name>DWR Servlet</display-name>
  <servlet-name>dwr-invoker</servlet-name> 
  <servlet-class>org.directwebremoting.servlet.DwrServlet</servlet-class>
  <init-param>
     <param-name>debug</param-name>
     <param-value>true</param-value>
  </init-param>
</servlet>
 
<servlet-mapping>
  <servlet-name>dwr-invoker</servlet-name>
  <url-pattern>/dwr/*</url-pattern>
</servlet-mapping>