x This domain is for sale. If you intrested, Please contact : webspeckle@gmail.com

JavaScript

Bootstrap model with jquery ui dialog occur a max callstack size exceeded error

Open a jquery ui dialog from bootstrap modal. This occur a max call stack size exceeded error in console.

We can solve this error in two way in my knowledge.

1) set 'modal' property to false in jqueryui dialog.
e.g.
$( ".selector" ).dialog({
  modal: false
});
2) Add the below line of code to your page
$.fn.modal.Constructor.prototype.enforceFocus = function (){};

Access global variable from a function, which has same variable name

How to access global variable from a function, which has same variable name in java script.

You can use the window object to get the global variable.
e.g. window.variableName
Here we write an example
var blogName = "webspeckle";
var blog = function()
{
    var blogName = window.blogName || "";
    return blogName;
}
blog();

//The output is 'webspeckle'


Split a string into an array of strings in JavaScript

Definition and Usage
The split() method is used to split a string into an array of strings.

Syntax
stringObject.split(separator, howmany) 
separator Required.
Specifies the character, regular expression, or substring that is used to determine where to split the string

howmany Optional. Specify how many times split should occur. Must be a numeric value

Note: If an empty string ("") is used as the separator, the string is split between each character.

Sample code and demo is here

Demo

Add new properties to an object constructor in JavaScript

Add new properties to an object constructor in JavaScript

Suppose we have a function WebsiteData() and it has two parameters(title,description).

function WebsiteData(pageTitle, pageDescription) {
    this.title = pageTitle;
    this.description = pageDescription;
}
Add a new property 'keywords' to this function WebsiteData().
WebsiteData.prototype.keywords = "my website keywords";

Sample code and demo is here

Demo

Search a string in JavaScript

The indexOf() method returns the position of the first occurrence of a specified string value in a string.

stringObject.indexOf(searchvalue,fromindex) 
searchvalue Required. Specifies a string value to search for
fromindex Optional. Specifies where to start the search

Tips and Notes
Note: The indexOf() method is case sensitive!

Note: This method returns -1 if the string value to search for never occurs.

Example
In this example we will do different searches within a "Hello world!" string:
<script type="text/javascript">
var str="Hello world!";
document.write(str.indexOf("Hello") + "<br />");
document.write(str.indexOf("World") + "<br />");
document.write(str.indexOf("world"));
</script> 
The output of the code above will be:

0
-1
6

Final code and demo is here

Demo

Get year in JavaScript

The getYear() method returns the year, as a two-digit OR a four-digit number.

dateObject.getYear() 
Tips and Notes
Note: The value returned by getYear() is not always 4 numbers! For years between 1900 and 1999 the getYear() method returns only two digits. For years before 1900 and after 1999 it returns four digits!
This method is always used in conjunction with a Date object.

Important: The getYear() method should no longer be used. Use the getFullYear() method instead!!

Example
In this example we get the current year and print it:
<script type="text/javascript">
var d = new Date()
document.write(d.getYear())
</script> 
The output of the code above will be:

105

Example 2
Here we will extract the year out of the specific date:
<script type="text/javascript">
var born = new Date("July 21, 1983 01:15:00");
document.write("I was born in " + born.getYear());
</script> 

Onclick event in JavaScript

The onclick event occurs when an object gets clicked.

Syntax
onclick="SomeJavaScriptCode" 
Parameter: SomeJavaScriptCode
Description: Required. Specifies a JavaScript to be executed when the event occurs.

Example
In this example the text in the first input field will be copied to the second input field when a button is clicked:

Demo

What is gulp.js?

gulp is a toolkit that helps you automate painful or time-consuming tasks in your development workflow. It is a task runner built on Node.js and npm, used for automation of time-consuming and repetitive tasks involved in web development like minification, concatenation, cache busting, unit testing, linting, optimization etc.

Getting Started


1) Install 'nodejs'
2) Create 'package.json'
3) Create 'gulpfile.js'
4) run 'gulp' command

Install 'nodejs'

After installing go to the project directory through 'Node.js command prompt' and check the version first
node --version
npm --version
Install the gulp command
npm install --global gulp-cli

Create a package.json

npm init
If you don't have a package.json, create one. If you need help, run an 'npm init' which will walk you through giving it a name, version, description, etc.
A sample file look like this
{
  "name": "PROJECT_NAME",
  "version": "PROJECT_VERSION",
  "description": "PROJECT_DESCRIPTION",
  "main": "",
  "dependencies": {
    "gulp": "^3.9.1"
  },
  "devDependencies": {
    "del": "^3.0.0",
    "gulp": "^3.9.1",
    "gulp-concat": "^2.6.1",
    "gulp-uglify": "^3.0.0",
  },
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "AUTHOR",
  "license": "ISC"
}
Install gulp in your devDependencies
npm install --save-dev gulp

Create a gulpfile

In your project directory, create a file named gulpfile.js in your project root.
A sample file look like this
var gulp = require('gulp');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var del = require('del');
var paths = {
  scripts: ['client/js/**/*.js']
};

gulp.task('clean', function() {
  return del(['build']);
});
gulp.task('scripts', ['clean'], function() {
  // Minify and copy all JavaScript (except vendor scripts)
  return gulp.src(paths.scripts)
      .pipe(uglify())
      .pipe(concat('all.min.js'))
    .pipe(gulp.dest('build/js'));
});

gulp.task('default', ['scripts']);

Run gulp

gulp
run 'gulp' command in 'Node.js command prompt'

After run gulp command all your 'js' files minimized and compressed to a single file 'all.min.js.' A folder 'build' will create in your project directory. It has another folder 'js'. This 'js' folder contains a single js file 'all.min.js'.

How to check if a value is not a number in JavaScript?

The isNaN() function is used to check if a value is not a number.

Syntax
isNaN(number) 
Parameter: number Required.
Description: The value to be tested

Example
In this example we use isNaN() to check some values:
<script type="text/javascript">
document.write(isNaN(123)+ "<br />");
document.write(isNaN(-1.23)+ "<br />");
document.write(isNaN(5-2)+ "<br />");
document.write(isNaN(0)+ "<br />");
document.write(isNaN("Hello")+ "<br />");
document.write(isNaN("2005/12/12")+ "<br />");
</script>
The output of the code above will be:
false
false
false
false
true
true

Final code and demo is here

Demo

How to evaluates a string in JavaScript?

The eval() function evaluates a string and executes it as if it was script code.

Syntax
eval(string) 

Parameter: string Required.
Description: The string to be evaluated

Example
In this example we use eval() on some strings and see what it returns:
<script type="text/javascript">
eval("x=10;y=20;document.write(x*y)");
document.write("<br />");
document.write(eval("2+2"))
document.write("<br />");
var x=10
document.write(eval(x+17))
document.write("<br />")
</script>
The output of the code above will be:
200
4
27

Final code and demo is here

Demo

Get today's date and time in JavaScript

The Date() method returns today's date and time.

Syntax: Date()

Example
In this example we will print today's date and time:
<script type="text/javascript">
document.write(Date())
</script>
The output of the code above will be:

Thu Jul 27 2017 23:23:42 GMT+0530 (India Standard Time)

Final code and demo is here

Demo

Form validation using JavaScript

Parsley is a javascript form validation library. It helps you provide your users with feedback on their form submission before sending it to your server. It saves you bandwidth, server load and it saves time for your users.

Javascript form validation is not necessary, and if used, it does not replace strong backend server validation.

That's why Parsley is here: to let you define your general form validation, implement it on the backend side, and simply port it frontend-side, with maximum respect to user experience best practices.

Basic installation
Parsley relies on jQuery (>= 1.8), and it will need to be included before including Parsley.
 Then, you can either use parsley.js unminified file or parsley.min.js minified one. These files and extras are available here.

Finally, add data-parsley-validate to each <form> you want to be validated.

That would look pretty much like this:
<script src="jquery.js"></script>
<script src="parsley.min.js"></script>

<form id="form">
...
</form>

<script>
  $('#form').parsley();
</script>
Final code and demo is here

Demo

Get Unicode of the character at a specified position

The charCodeAt() method returns the Unicode of the character at a specified position.

stringObject.charCodeAt(index)
Parameter: index Required
Description: A number representing a position in the string

Note: The first character in the string is at position 0.

Example
In the string "Hello world!", we will return the Unicode of the character at position 1:
<script type="text/javascript">
var str="Hello world!"
document.write(str.charCodeAt(1))
</script>
The output of the code above will be:
101

Final code and demo is here

Demo

How to get the character at a specified position?

In JavaScript the charAt() method returns the character at a specified position.

stringObject.charAt(index)
Parameter: index
Description: Required. A number representing a position in the string

Note: The first character in the string is at position 0.

Example
In the string "Hello world!", we will return the character at position 1:
<script type="text/javascript">var str="Hello world!"
document.write(str.charAt(1))
</script>
The output of the code above will be:
e
Final code and demo is here

Demo

Get value of a number rounded upwards

The ceil() method returns the value of a number rounded UPWARDS to the nearest integer.

Math.ceil(x)
'x' is required and should be a number

In the following example we will use the ceil() method on different numbers:
<script type="text/javascript">document.write(Math.ceil(0.60) + "<br />")
document.write(Math.ceil(0.40) + "<br />")
document.write(Math.ceil(5) + "<br />")
document.write(Math.ceil(5.1) + "<br />")
document.write(Math.ceil(-5.1) + "<br />")
document.write(Math.ceil(-5.9))
</script>
The output of the code above will be:
1
1
5
6
-5
-5

Final code and demo is here

Demo

How to get the arccosine of a number in JavaScript?

The acos() method returns the arccosine of a number as a numeric value value between 0 and PI radians.

Math.acos(x)
Parameter is required and must be a numeric value in the range -1 to 1

Note: If the parameter x is outside the range -1 to 1, the browser will return NaN.
Note: -1 will return the value of PI

In this example we will get the arccosine of different numbers:
<script type="text/javascript">
document.write(Math.acos(0.64) + "<br />")
document.write(Math.acos(0) + "<br />")
document.write(Math.acos(-1) + "<br />")
document.write(Math.acos(1) + "<br />")
document.write(Math.acos(2))</script>
Sample code and demo is here

Demo

Get value of a number rounded downwards

The floor() method returns the value of a number rounded DOWNWARDS to the nearest integer in JavaScript.

Math.floor(x)
x is required and a number.

In this example we will use the floor() method on different numbers:
<script type="text/javascript">document.write(Math.floor(0.60) + "<br />")
document.write(Math.floor(0.40) + "<br />")
document.write(Math.floor(5) + "<br />")
document.write(Math.floor(5.1) + "<br />")
document.write(Math.floor(-5.1) + "<br />")
document.write(Math.floor(-5.9))
</script>
The output of the code above will be:
0
0
5
5
-6
-6

Final code and demo is here

Demo

How to get the absolute value of a number in JavaScript?

The abs() method returns the absolute value of a number.

Math.abs(x)
Parameter is required and must be a numeric value.

Example
<script>
document.write(Math.abs(7.25) + "<br />")
document.write(Math.abs(-7.25) + "<br />")
document.write(Math.abs(7.25-10))
</script>
Sample code and demo is here

Demo

How to create Pie chart in JavaScript?

Pie chart is a type of graph in which a circle is divided into sectors that each represent a proportion of the whole. Pie charts are very widely used in the business world and the mass media.

Pie charts are probably the most commonly used charts. They are divided into segments, the arc of each segment shows the proportional value of each piece of data. They are excellent at showing the relational proportions between data.

Here i am using chartjs library for creating pie chart. 

Example Usage

var myPieChart = new Chart(ctx,{
    type: 'pie',
    data: data,
    options: options
})
;

Dataset Properties

The pie chart allows a number of properties to be specified for each dataset. These are used to set display properties for a specific dataset. For example, the colour of a the dataset's arc are generally set this way.

Name Type Description
label String The label for the dataset which appears in the legend and tooltips.
backgroundColor Color[] The fill color of the arcs in the dataset.
borderColor Color[] The border color of the arcs in the dataset.
borderWidth Number[] The border width of the arcs in the dataset.
hoverBackgroundColor Color[] The fill colour of the arcs when hovered.
hoverBorderColor Color[] The stroke colour of the arcs when hovered.
hoverBorderWidth Number[] The stroke width of the arcs when hovered.

Config Options 

These are the customisation options specific to Pie charts. These options are merged with the global chart configuration options, and form the options of the chart.

NameTypeDefaultDescription
cutoutPercentageNumber0 - for pieThe percentage of the chart that is cut out of the middle.
rotationNumber-0.5 * Math.PIStarting angle to draw arcs from.
circumferenceNumber2 * Math.PISweep to allow arcs to cover
animation.animateRotateBooleantrueIf true, the chart will animate in with a rotation animation. This property is in the options.animation object.
animation.animateScaleBooleanfalseIf true, will animate scaling the chart from the center outwards.

Data Structure 

For a pie chart, datasets need to contain an array of data points. The data points should be a number, Chart.js will total all of the numbers and calculate the relative proportion of each. You also need to specify an array of labels so that tooltips appear correctly

data = {
    datasets: [{
        data: [10, 20, 30]
    }],

    // These labels appear in the legend and in the tooltips when hovering different arcs
    labels: [
        'Red',
        'Yellow',
        'Blue'
    ]
};
You can download the latest version of Chart.js from the GitHub releases or use a Chart.js CDN.

The final code & demo is here

Demo

How to add slim progress bars in JavaScript?

Use 'NProgress.js' library for nanoscopic progress bar.

NProgress.start() — shows the progress bar
NProgress.set(0.4) — sets a percentage
NProgress.inc() — increments by a little
NProgress.done() — completes the progress

<script>
NProgress.start();
$(document).ready(function ()
{
    NProgress.done();
});
</script>
Final code and demo is here

Demo