How to declare an array in javascript?

JavaScript arrays are used to store multiple values in a single variable. An array is a special variable, which can hold more than one value at a time.

Method 1:

var cars = new Array("Saab", "Volvo", "BMW");

Access the Elements of an Array
var name = cars[0];//Saab
This statement modifies the first element in cars:
cars[0] = "Opel";

'Saab' is replaced by 'Opel'.

Method 2:

var cars = ["Saab", "Volvo", "BMW"];

Method 3:

var person = [];

Eg:
var person = [];
person[0] = "John";
person[1] = "Doe";
person[2] = 46;
var x = person.length;         // person.length will return 3
var y = person[0];             // person[0] will return "John"

Method 4:

var person = {firstName:"John", lastName:"Doe", age:46};

In this example, person.firstName returns 'John'

How do I know if a variable is an array?

Creating a sample array.
var fruits = ["Banana", "Orange", "Apple", "Mango"];

Method 1:

Array.isArray(fruits);     // returns true

NB: THis method not supported in older browsers.

Method 2:

To overcome the method 1, Cretae an isArray() function
function isArray(x)
{
    return x.constructor.toString().indexOf("Array") > -1;
}

The function above always returns true if the argument is an array.

Or more precisely: it returns true if the object prototype contains the word "Array".

Method 3:

The instanceof operator returns true if an object is created by a given constructor:
fruits instanceof Array     // returns true

How to perform a case-insensitive search in JavaScript?

The search() method searches a string for a specified value, and returns the position of the first occurrence of the specified searchvalue, or -1 if no match is founds.
The search value can be string or a regular expression.

Eg:
Case sensitive search
var str = "WELCOME to WebSpeckle.com";
var n = str.search("COM");
Output is: 3 //Found in third position
var str = "Welcome to WebSpeckle.com";
var n = str.search("COM");
Output is: -1 //Not found
Case insensitive search
var str = "Welcome to WebSpeckle.com";
var n = str.search(/COM/i); Output is: 3 //Found in third position

How do i get the current URL in JavaScript?

The window.location object can be used to get the current page URL and also we can use to redirect the browser to a new page.

The window.location.href property returns the URL of the current page.
Eg:
<script>
Console.log("The curret page URL is: " + window.location.href);
</script>
window.location.href returns the href (URL) of the current page
window.location.hostname returns the domain name of the web host
window.location.pathname returns the path and filename of the current page
window.location.protocol returns the web protocol used (http: or https:)
window.location.assign loads a new document

How to empty an array in JavaScript?

JavaScript arrays are used to store multiple values in a single variable.An array is a special variable, which can hold more than one value at a time.

Here we have an array
Eg:
var Arr = [1,2,3,4,5];
4 ways to empty this array

Method 1:

Arr = [];

Method 2:

Arr.length = 0;

Method 3:

Arr.splice(0,Arr.length)

Method 4:

while(Arr.length > 0)
    Arr.pop();
}

Clearing object array

var website = {url:"http://www.webspeckle.com", type:"blog"};
console.log(website); //{ url:"http://www.webspeckle.com", type:"blog"}
var websiteData = null;
for(websiteData in website)
{
    website[websiteData] = null;
}
console.log(website); //{ url:null, type:null}

window.location.search vs window.location.href

window.location.href
The href property sets or returns the entire URL of the current page.

window.location.search
The search property sets or returns the querystring part of a URL, including the question mark (?).

Suppose  our current page url is "http://www.example.com/p/online-html-editor?demoid=4545454545"
window.location.href is "http://www.example.com/p/online-html-editor?demoid=4545454545"
window.location.search is "?demoid=4545454545"


Demo

How to show a confirmation box in JavaScript?

In JavaScript 'confirm()' function is used for this purpose. This method displays a dialog box with a specified message, along with an OK and a Cancel button.

The confirm() method returns true if the user clicked "OK", and false otherwise.

The parameter type of this function is 'String'. This method does not accept HTML string as parameter. For 'line-breaks' please use '\n'.

var UserAction = confirm("Are you sure you want to delete?");
if (UserAction  == true)
{
    //User pressed on OK button
}
else
{
    //User pressed on CANCEL button
}
Final code and demo is here


Demo

How can i show confirmation box before page reload?

In some cases before page refresh/reload we have to show confirmation message to the user. The page reload only if the user allow. In JavaScript we can use 'onbeforeunload ' function for this case.

I have checked the below code in latest Chrome & Firefox.

<script>
window.onbeforeunload = function(event)
{
    return confirm("Confirm refresh");
};
</script>
Final code and demo is here


Demo

How to decode a URL in JavaScript?

The decodeURI() function is used to decode a URI.

Eg:
<script>
var URL = "https://www.example.com/p/online-html-editor.html?filename=How%20to%20decode%20a%20URL%20in%20JavaScript";
var EncodedURL = decodeURI(URL);
</script>
Final code and demo is here

Demo

How to encode a URL in JavaScript?

The encodeURI() function is used to encode a URI.
This function encodes special characters, except: , / ? : @ & = + $ #

Eg:
<script>
var URL = "https://www.example.com/p/online-html-editor.html?filename=How to encode a URL in JavaScript";
var EncodedURL = encodeURI(URL);
</script>
Final code and 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

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

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

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

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

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

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'.

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

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> 

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

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

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

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'


How to delay an execution in jquery?

delay() method allows us to delay the execution of functions that follow it in the queue. It can be used with the standard effects queue or with a custom queue. Only subsequent events in a queue are delayed; for example this will not delay the no-arguments forms of .show() or .hide() which do not use the effects queue.

Durations are given in milliseconds; higher values indicate slower animations, not faster ones. The strings 'fast' and 'slow' can be supplied to indicate durations of 200 and 600 milliseconds, respectively.

Using the standard effects queue, we can, for example, set an 800-millisecond delay between the .slideUp() and .fadeIn() of <div id="foo">:

$( "#foo" ).slideUp( 300 ).delay( 800 ).fadeIn( 400 );

When this statement is executed, the element slides up for 300 milliseconds and then pauses for 800 milliseconds before fading in for 400 milliseconds.

The .delay() method is best for delaying between queued jQuery effects. Because it is limited—it doesn't, for example, offer a way to cancel the delay—.delay() is not a replacement for JavaScript's native setTimeout function, which may be more appropriate for certain use cases.

Reset a form elements using jquery/javascript

By using jquery
$('#formID')[0].reset();

By using Javascript
document.getElementById("myForm").reset(); 

The reset() method resets the values of all elements in a form (same as clicking the Reset button)
.

Remove all child elements of a parent by using JavaScript or JQuery

Here we explaining how to remove all HTML DOM child elements of a parent by using JavaScript or JQuery.

Eg:
<div id="Parent">
<span>This is some text in the div.</span>
<p>This is a paragraph in the div.</p>
<p>This is another paragraph in the div.</p>
<input type="text" value="webspeckle.com"/>
</div>
In the above example div is the parent element because 'div' tag is wrapped the other HTML DOM (Document Object Model) elements. Here the parent has four child elements. i.e span,p,input.

We can remove the elements by two way.

1) Remove the parent element and its child elements.
2) Remove only the child elements.

In JQuery it is very easy
Catch the parent element. Remove the parent element & its child or Delete all child elements.

$("#Parent").remove(); //Removes the selected element (and its child elements)
$("#Parent").empty(); //Removes the child elements from the selected element
In JavasCript
Remove all child elements
var Parent = document.getElementById("Parent");
while (Parent.hasChildNodes())
{
   Parent.removeChild(Parent.firstChild);
}
Remove parent and its child elements
var Parent = document.getElementById("Parent");
var ParentWrapper = Parent.parentNode;
while (ParentWrapper.hasChildNodes())
{
   ParentWrapper.removeChild(ParentWrapper.firstChild);
}

First character of each word to uppercase in JavaScript

Here we introducing a function 'ucwords'. Which is used for convert the first character of each word to uppercase in JavaScript. In PHP a built-in function named 'ucwords' is used to uppercase the first character of each word in a string. But in JavaScript there is no equivalent built-in function.

function ucwords(str)
{
    return str === null ? "" : str.toLowerCase().replace(/^(.)|\s+(.)/g, function ($1)
    {
        return $1.toUpperCase();
    });
}
Eg:
ucwords("CONVERT the fIRst character of each word to uppercase in javascript");
ucwords("convert the first character of each word to uppercase in javascript");
ucwords("CONVERT THE FIRST CHARACTER OF EACH WORD TO UPPERCASE IN JAVASCRIPT");
ucwords("Convert the first character of each word to uppercase in javascript");

The above all sentences are converted to
"Convert The First Character Of Each Word To Uppercase In Javascript"

How to Generate Random Colors in JavaScript?

Random is an action that happens without order or reason. In some cases we need random values. JavaScript provides a function for generating random values

i.e.
Math.random()
The random() method returns a random number from 0 (inclusive) up to but not including 1 (exclusive).

In our case we need six digit random hexadecimal color. i.e #FF0000 represent the "RED" color. Read more about Hex colors.
For example in dynamic pie or bar chart view, we need random colors. Here we explain how to generate random colors in javascript.

function GetRandomHexColor()
{
    var AllowedLetters = '0123456789ABCDEF';
    var Color = '#';
    for (var i = 0; i < 6; i++ )
    {
        Color += AllowedLetters[Math.floor(Math.random() * 16)];
    }
    return Color;
}
A demo for changing the border color and text color of a div by using JQuery.


Demo

How to create blinking effect in JQuery?

Here we created a simple function "Blink". It required two parameters. One is the element object and other is the blinking speed. You will have to include jQuery library. In this example the blink() function is used for to blink the span element. jQuery animate() method is the main part of this function.

<script>
function Blink(Element,Speed)
{
    Element.animate({opacity: 0.2},Speed,function()
    {
    Element.animate({opacity: 1.0},Speed,function()
        {
        Blink(Element,Speed);
        });
});
}
$(document).ready(function()
{
Blink($(".Warning"),200); //400 = Blinking Speed
});
</script>
Final code and demo is here


Demo

How to change anchor element URL dynamically?

The HTML <a> element (or anchor element) creates a hyperlink to other web pages, files, locations within the same page, email addresses, or any other URL.

Change anchor element (<a>) href url dynamically by using jquery.

<script>
$(document).ready(function()
{
$("p").text("Anchor element url = "+$("a").attr("href"));
    $("button").click(function()
    {
        $("a").attr("href","http://www.webspeckle.com");
        $("p").text("Anchor element url = "+$("a").attr("href"));
    });
});
</script>
Final code and demo is here


Demo

Search and highlight using JavaScript?

Using a regex rule for search a word in JavaScript

new RegExp("Keyword",'gim')
And replace the keyword by '<span class=\"Highlight\">Keyword</span>'

Defined a 'Highlight' css class for highlight the keyword.

<style>
.Highlight
{
  background-color:#FF9;
  color:#555;
}
</style>
JQuery 'unwrap()' methord is used for unwrap the previously highlighted elements.

Final code and demo is here

Demo

How to add keyboard shortcut in JavaScript and JQuery?

Here i explain how to add 'Ctrl+S' and 'Alt+S' keyboard shortcut to your webpage using JQuery and JavaScript.

Please follow the below steps

1) Catch the 'keydown' event
2) Check whether 'Ctrl' key is pressed or not
3) Check whether the 'S' key is pressed or not
4) Prevent the default behavior of 'Ctrl+S'.

//In JQuery
<script>
    $(document).bind('keydown', function (e)
    {
        if (e.ctrlKey && (e.which === 83)) //Ctrl+S
        {
            e.preventDefault();
            alert('Ctrl+S Pressed');
            return false;
        }
    });
</script>
1) Catch the 'keydown' event
2) Check whether 'Alt' key is pressed or not
3) Check whether the 'S' key is pressed or not
4) Prevent the default behavior of 'Alt+S'.

//In JavaScript
<script>
document.onkeydown=function(e)
{
    var e = e || window.event; // for IE to cover IEs window object
    if(e.altKey && e.which === 83)
    {
        alert('Alt+S Pressed');
        return false;
    }
};
</script>
Some control key combinations have been reserved for browser usage only and can no longer be intercepted by the client side JavaScript in the web page.
Eg: Ctrl+N, Ctrl+W, Ctrl+T etc...

Note: In the demo page, after executing the below html code please click on the output pane and press 'Ctrl+S' & 'Alt+S'

Final code and demo is here


Demo

How to store JavaScript object in HTML attribute?

HTML5 has a new attribute "data-*". The data-* attributes is used to store custom data to the page. By adding data-* attributes, even ordinary HTML elements can become rather complex and powerful program-objects.

Eg:
<div data-website-name="webspeckle.com"></div>
In the above example 'div' element has an attribute "data-website-name". This is a custom data attributes. The string "webspeckle.com" set to "data-website-name" attribute.

Set JSON string in 'data' attribute

<div data-website-name="webspeckle.com" data-website-data='{"name":"webspeckle.com","type":"blog"}'></div>
In the above example the JSON string '{"name":"webspeckle.com","type":"blog"}' set to the 'data-website-data' attribute.

Get the value of data attribute using JQuery
$("div").data("data-website-name") //webspeckle.com
$("div").data("data-website-data") //JSON Object
$("div").data("data-website-data").type //blog
Set value to data attribute using JQuery
<script>
var car =
{
color: "red",
        owner: "rahul"
}
$(document).ready(function()
{
      $("div").data("car",car)
});
</script>
Final code and demo is here

Demo

How to detect ENTER key press in HTML textbox?

Suppose you have a search form in your web page. User type search keyword in the textbox(input tag) and press the ENTER key instead of click on the search button. How to detect ENTER key press HTML input tag?

Eg:
<input type="text" id="SearchKeyword"/>
<button type="button" onclick="Search()">Search</button>
<script>
//Using JQuery
$('#SearchKeyword').keyup(function(e)
{
    if(e.keyCode == 13)
    {
        $(this).trigger("enterKey");
    }
});

//Using JavaScript
document.getElementById("SearchKeyword").onkeypress = function(e)
{
    if (e.keyCode === 13)
    {
        alert("Enter key pressed");
        Search();
    }
};
</script>
Final code and demo is here

Demo

How to display dialog for user to input in JavaScript?

The prompt() is used for displays a dialog for user to input some text.

If the user clicks "OK", the input value is returned. If the user clicks "cancel", null is returned. If the user clicks OK without entering any text, an empty string is returned.

Dialog boxes are modal windows; they prevent the user from accessing the rest of the program's interface until the dialog box is closed. For this reason, you should not overuse any function that creates a dialog box

var Name = prompt("Please enter your name");
if (Name !== null)
{
    if (Name !== "")
    {
        //If the user clicks OK with text
    }
    else
    {
        //If the user clicks OK without entering any text
    }
}
Final code and demo is here

Demo

How to remove white space from the beginning and end of a string in JavaScript?

Method 1: using trim()
The trim() method returns the string stripped of white space from both ends. trim() does not affect the value of the string itself.

var str = "    hello, how are you?    ";
str.trim(); //hello, how are you?
Method 2: using regex
The expression '/^\s+|\s+$/g' removes white space from both sides of a string.

var str = "    hello, how are you?    ";
str.replace(/^\s+|\s+$/gm,''); //hello, how are you?
Method 3: using JQuery
The $.trim() function removes all newlines, spaces (including non-breaking spaces), and tabs from the beginning and end of the supplied string. If these white space characters occur in the middle of the string, they are preserved.

$.trim("    hello, how are you?    "); //hello, how are you?
Final code and demo is here

Demo

Get the current position of an element in jQuery?

Object .offset( )

Get the current coordinates of the first element in the set of matched elements, relative to the document.

The .offset() method allows us to retrieve the current position of an element relative to the document. Contrast this with .position(), which retrieves the current position relative to the offset parent. When positioning a new element on top of an existing one for global manipulation (in particular, for implementing drag-and-drop), .offset() is the more useful.

.offset() returns an object containing the properties top and left.

Note: jQuery does not support getting the offset coordinates of hidden elements or accounting for borders, margins, or padding set on the body element.

Object.offset( Object coordinates )

Set the current coordinates of every element in the set of matched elements, relative to the document.

The .offset() setter method allows us to reposition an element. The element's position is specified relative to the document. If the element's position style property is currently static, it will be set to relative to allow for this repositioning.

Final code and demo is here

Demo

Encode a set of form elements as a string for submission

The .serialize() method creates a text string in standard URL-encoded notation. It operates on a jQuery object representing a set of form elements.

.serialize( )
Eg:
<form>
  <div><input type="text" name="a" value="1" id="a" /></div>
  <div><input type="text" name="b" value="2" id="b" /></div>
  <div><input type="hidden" name="c" value="3" id="c" /></div>
  <div>
    <textarea name="d" rows="8" cols="40">4</textarea>
  </div>
  <div><select name="e">
    <option value="5" selected="selected">5</option>
    <option value="6">6</option>
    <option value="7">7</option>
  </select></div>
  <div>
    <input type="checkbox" name="f" value="8" id="f" />
  </div>
  <div>
    <input type="submit" name="g" value="Submit" id="g" />
  </div>
</form>
The .serialize() method can act on a jQuery object that has selected individual form elements, such as <input>, <textarea>, and <select>. However, it is typically easier to select the <form> tag itself for serialization:

$('form').submit(function()
{
  alert($(this).serialize());
  return false;
});
This produces a standard-looking query string:

a=1&b=2&c=3&d=4&e=5
Warning: selecting both the form and its children will cause duplicates in the serialized string.

Note: Only "successful controls" are serialized to the string. No submit button value is serialized since the form was not submitted using a button. For a form element's value to be included in the serialized string, the element must have a name attribute. Values from checkboxes and radio buttons (inputs of type "radio" or "checkbox") are included only if they are checked. Data from file select elements is not serialized.

Final code and demo is here

Demo

Load a JavaScript file dynamically

Load a JavaScript file dynamically using jQuery

jQuery.getScript()
Load a JavaScript file from the server using a GET HTTP request, then execute it.

Eg:
$.getScript( "ajax/test.js", function( data, textStatus, jqxhr ) {
  console.log( data ); // Data returned
  console.log( textStatus ); // Success
  console.log( jqxhr.status ); // 200
  console.log( "Load was performed." );
});
By default, $.getScript() sets the cache setting to false. This appends a timestamped query parameter to the request URL to ensure that the browser downloads the script each time it is requested. You can override this feature by setting the cache property globally using $.ajaxSetup():

$.ajaxSetup({
  cache: true
});
Sample code and demo

Demo

An Introduction To WebSockets

Web Sockets is a next-generation bidirectional communication technology for web applications which operates over a single socket and is exposed via a JavaScript interface in HTML 5 compliant browsers.

Once you get a Web Socket connection with the web server, you can send data from browser to server by calling a send() method, and receive data from server to browser by an onmessage event handler.

WebSocket Events

Following are the events associated with WebSocket object. Assuming we created Socket object as mentioned above −
open:
Socket.onopen
    This event occurs when socket connection is established.
message:
  Socket.onmessage
            This event occurs when client receives data from server.
error:
  Socket.onerror
            This event occurs when there is any error in communication.
close:
Socket.onclose
      This event occurs when connection is closed.

WebSocket Methods

Following are the methods associated with WebSocket object. Assuming we created Socket object as mentioned above −

Socket.send()
The send(data) method transmits data using the connection.

Socket.close()
The close() method would be used to terminate any existing connection.
if ("WebSocket" in window)
{
    WebSocket = new WebSocket("wss://echo.websocket.org");
    WebSocket.onopen = function (Event)
    {
        //Web Socket Connected Successfully";
        WebSocket.send("Message to send");
    };
    WebSocket.onmessage = function (Event)
    {
        //Message is received...
    };

    WebSocket.onclose = function (event)
    {
        //Web Socket Closed Successfully
    };

    WebSocket.onerror = function (Error)
    {
        //Web Socket Error
    };
}
else
{
    //Web Socket Error: NOT supported by your Browser!
}

Change message converter to Gson in RestTemplate

Message converters are used to convert the Http request to an object representation and back.

RestTemplate restTemplate = new RestTemplate();
         
List<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
GsonHttpMessageConverter gsonHttpMessageConverter = new GsonHttpMessageConverter();
messageConverters.add(gsonHttpMessageConverter);
restTemplate.setMessageConverters(messageConverters);

How to send HTTP request in spring boot?

If you need to call remote REST services from your application, you can use Spring Framework’s RestTemplate class. Since RestTemplate instances often need to be customized before being used, Spring Boot does not provide any single auto-configured RestTemplate bean. It does, however, auto-configure a RestTemplateBuilder which can be used to create RestTemplate instances when needed. The auto-configured RestTemplateBuilder will ensure that sensible HttpMessageConverters are applied to RestTemplate instances.

RestTemplateBuilder includes a number of useful methods that can be used to quickly configure a RestTemplate. For example, to add BASIC auth support you can use builder.basicAuthorization("user", "password").build().


Eg:
HttpResponse httpResponse;
HttpRequest httpRequest = new HttpRequest();
HttpRequest.setName("webspeckle.com");

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<HttpRequest> entity = new HttpEntity<>(httpRequest,headers);

RestTemplate restTemplate = new RestTemplate();

try
{
    ResponseEntity<HttpResponse> responseEntity = restTemplate.exchange("REST_URL", HttpMethod.POST, entity, HttpResponse.class);
    httpResponse = responseEntity.getBody();
    //Success
}
catch(HttpStatusCodeException ex)
{
    //Error in REST request
}

What is Qt

Qt is a cross-platform application framework that is used for developing application software that can be run on various software and hardware platforms with little or no change in the underlying codebase, while still being a native application with native capabilities and speed.

Qt is used for developing multi-platform applications and graphical user interfaces (GUIs); however, programs without a GUI can be developed, such as command-line tools and consoles for servers. An example of a non-GUI program using Qt is the Cutelyst web framework. GUI programs created with Qt can have a native-looking interface, in which case Qt is classified as a widget toolkit.

Qt uses standard C++ with extensions including signals and slots that simplify handling of events, and this helps in development of both GUI and server applications which receive their own set of event information and should process them accordingly. Qt supports many compilers, including the GCC C++ compiler and the Visual Studio suite. Qt also provides Qt Quick, that includes a declarative scripting language called QML that allows using JavaScript to provide the logic. With Qt Quick, rapid application development for mobile devices became possible, although logic can be written with native code as well to achieve the best possible performance. Qt can be used in several other programming languages via language bindings. It runs on the major desktop platforms and some of the mobile platforms. It has extensive internationalization support. Non-GUI features include SQL database access, XML parsing, JSON parsing, thread management and network support.

A language construct introduced in Qt for communication between objects which makes it easy to implement the observer pattern while avoiding boilerplate code. The concept is that GUI widgets can send signals containing event information which can be received by other controls using special functions known as slots.

Qt works on many different platforms.

How to close a database connection in Qt?

In most cases a warning "QSqlDatabasePrivate::addDatabase: duplicate connection name 'qt_sql_default_connection', old connection removed" occurred while adding or closing database in Qt.

How to solve this problem?

// WRONG
QSqlDatabase db = QSqlDatabase::database("mydb");
QSqlQuery query("SELECT ...", db);
QSqlDatabase::removeDatabase("mydb"); // will output the above warning
//Closing database connection in  CORRECT way
db.close();
db =  QSqlDatabase();
QSqlDatabase::removeDatabase("mydb");
And also you can check the database connection is empty or not.

if(db.connectionName().isEmpty())
{
       //Add database.
}

How to check whether a database is exist in Qt?

Check whether a PostgreSQL database is exist or not in Qt.

If we try to create a PostgreSQL database through a Qt application, we have to check whether the given database is exist or not. Otherwise an error occurred during database creation.

I have checked the below method in Qt5 and it is working fine. Please replace 'MY_DB_NAME' by your database name.

QSqlQuery DatabaseQuery;
if(DatabaseQuery.prepare("SELECT datname FROM pg_catalog.pg_database WHERE lower(datname) =  lower('MY_DB_NAME')"))
{
     if(DatabaseQuery.exec())
     {
          if(DatabaseQuery.size() == 0)
          {
               //Database not exist
          }
          else
          {
               //Database exist
          }
     }
}

How to load Google map in Qt application?

Create an html file 'GMap.html' for Google map like this

<!DOCTYPE html>
<html>
<body>

<h1>How to load Google map in Qt application?</h1>

<div id="GMap" style="width:600px;height:600px;"></div>

<script>
function LoadGMap()
{
var mapOptions = {
    center: new google.maps.LatLng(36.778259, -119.417931),
    zoom: 5
}
var map = new google.maps.Map(document.getElementById("GMap"), mapOptions);
}
</script>

<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=LoadGMap"></script>

</body>
</html>
You must save 'GMap.html' file in your application directory. Then load this file in your Qt application.

In Qt5.5 =<
Header: #include <QWebView>
QString HTMLFilepath =  "YOUR_APPLICATION_PATH+/GMap.html";
QWebView *HTMLPage = new QWebView(parent);
HTMLPage->load(QUrl(QUrl::fromLocalFile(HTMLFilepath));
HTMLPage->show();
In Qt5.6 >=
Header: #include <QWebEngineView>
QString HTMLFilepath =  "YOUR_APPLICATION_PATH+/GMap.html";
QWebEngineView *HTMLPage = new QWebEngineView(parent);
HTMLPage->load(QUrl(QUrl::fromLocalFile(HTMLFilepath));
HTMLPage->show();
'load(url)' loads the specified url and displays it.