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

jQuery

Expand div to full screen

Here we are showing how to expand a div to full screen. See the demo and do it.

Sample code and demo is here

Demo

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

Search and get the postion of an element in jquery

index() is used for search for a given element from among the matched elements.

If no argument is passed to the .index() method, the return value is an integer indicating the position of the first element within the jQuery object relative to its sibling elements.

If .index() is called on a collection of elements and a DOM element or jQuery object is passed in, .index() returns an integer indicating the position of the passed element relative to the original collection.

If a selector string is passed as an argument, .index() returns an integer indicating the position of the first element within the jQuery object relative to the elements matched by the selector. If the element is not found, .index() will return -1.

Eg:
<ul>
  <li id="foo">foo</li>
  <li id="bar">bar</li>
  <li id="baz">baz</li>
</ul>
var listItem = document.getElementById( "bar" );
console.log( "Index: " + $( "li" ).index( listItem ) );
We get back the zero-based position of the list item:

Index: 1

Sample 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

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

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

How to get suggestions while type into the field?

In jQuery UI the Autocomplete API provides suggestions while you type into the field. The data source is a simple JavaScript array, provided to the API using the source-option. Autocomplete enables users to quickly find and select from a pre-populated list of values as they type, leveraging searching and filtering.

Any field that can receive input can be converted into an Autocomplete, namely, <input> elements, <textarea> elements, and elements with the contenteditable attribute.

When typing in the autocomplete field, the plugin starts searching for entries that match and displays a list of values to choose from. By entering more characters, the user can filter down the list to better matches.

$( ".selector" ).autocomplete({
  source: [ "c++", "java", "php", "coldfusion", "javascript", "asp", "ruby" ]
});
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

How to create pagination in Bootstrap?

This jQuery plugin "twbsPagination()" simplifies the usage of Bootstrap Pagintion.

Plugin requires jQuery (required - 1.7.0 or higher).

You can use Bootstrap CSS styles and markup (or use your own).

More details available here

Add this lines in to your HTML code
<div class="well PageContent"></div>
<ul class="PaginationLinks pagination-sm"></ul>
Add this script in to your JavaScript section
$('.PaginationLinks').twbsPagination(
{
    totalPages: 20,
    visiblePages: 7,
    onPageClick: function (event, PageNo) {
        $('.PageContent').text('Page ' + PageNo);
    }
});
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 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 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 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

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

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 select all text in a DIV?

Here we are showing a simple demo for select all text in a DIV by using JavaScript.


Demo

How to show bootstrap popover one at a time?

First you call the popover plugin with the selector

$('[data-toggle="popover"]').popover(options);
You must be set the "trigger" option to "manual" for showing one popover at a time.

$('[data-toggle="popover"]').popover({'trigger': 'manual'});
Then you should catch the click event. Show the current popover and hide others

$('[data-toggle="popover"]').on('click', function (e)
{
    $(this).popover('show');
    $('[data-toggle="popover"]').not(this).popover('hide');
});
The final code & demo is here


Demo

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

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"