Load JSON data to Table using Jquery

Load JSON data to table using Jquery

Demo

See the Pen bLjwzy by Vinothkumar Rajendran (@fedtutorial) on CodePen.0

Note
For demo purpose I am using external api from www.mocky.io

JSON


//service.json
{
    "Cities": ["LUSAKA", "HARARE"],
    "Countries": ["ZAMBIA", "ZIMBABWE"]
}

Script


<!DOCTYPE HTML>
<html>
<head>
    <meta charset="utf-8">
    <title>WCF Client</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
</head>
<body>
    <table id="location" border='1'>
        <tr>
            <th>Countries</th>
            <th>Cities</th>
        </tr>
    </table>
    <script>
        var service = 'service.json';

        $(document).ready(function() {

            jQuery.support.cors = true;

            $.ajax({
                type: "GET",
                // url: service + '/service/',
                url: service,
                data: "{}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                cache: false,
                success: function(data) {

                    var trHTML = '';

                    $.each(data.Countries, function(i, item) {

                        trHTML += '<tr><td>' + data.Countries[i] + '</td><td>' + data.Cities[i] + '</td></tr>';
                    });

                    $('#location').append(trHTML);

                },

                error: function(msg) {

                    alert(msg.responseText);
                }
            });
        })
    </script>
</body>
</html>

Note

If you are working in local environment, please use some local server (XAMPP, WAMP, Apache) to run this code. Because of JSON local access it is not working directly without server.

Continue Reading

Swiper Jquery Plugin

It is a modern mobile touch slider.

CSS:


<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/Swiper/4.0.7/css/swiper.min.css" />

JS:


<script src="https://cdnjs.cloudflare.com/ajax/libs/Swiper/4.0.7/js/swiper.min.js "></script>

It has lot of components.

  • Swipe slider navigation
  • Swipe pagination
  • Swipe pagination with dynamic bullets
  • Progress pagination
  • Fraction pagination
  • Custom pagination
  • Page Scrollbar
  • Vertical page slider
  • Space between slides
  • Multiple slides per view
  • Scroll container
  • Multiple row slides layout
  • Nested swipers
  • Loop mode carousel
  • Loop mode with multiple slides per group
  • 3D cube effect
  • 3D coverflow effect
  • 3D Flip effect
  • Mousewheel control
  • Autoplay carousel
  • Dynamic slides (append/prepend slide pagination)
  • Thumbs gallery with two-way swipe
  • Parallax (Parallax scrolling is a web site trend where the background content (i.e. an image) is moved at a different speed than the foreground content while scrolling.)
  • Responsive breakpoints slider
  • Auto height slider
  • Zoom slider
  • Slideable navigation drawer

Demo: http://idangero.us/swiper/demos/

Continue Reading

How to fix footer at bottom using Jquery?

Fixed footer at bottom of window using Jquery


 $(function () {
        function adjust() {
            var winH = $(window).height(),
                docH = $('document').height();

            if (docH > winH) {
                //leave it
            } else {
                $('.footer').addClass('fixedfooter');
            }
        }
        $(window).on('resize', adjust);
 adjust();
    })

Explanantion

  • $ (window).height() returns the height of the browser viewport.
  • $ (document).height() returns the height of entire HTML document.
  • .fixedfooter class will add to footer section when document height is less than window height.

Result

See the Pen Fixed footer at bottom of window by Vinothkumar (@fedtutorial) on CodePen.0

Continue Reading

Full screen bootstrap carousel slider using Jquery

Create a full page bootstrap carousel

We can develop a full screen bootstrap carousel or slider by using below scripts.

Demo

See the Pen Full screen bootstrap carousel slider by Vinothkumar Rajendran (@fedtutorial) on CodePen.0

Include bootstrap library files and jquery library. After that use the below script to achieve full page carousel.


/* full page carousel */
$(document).ready(function () {
$('.carousel').carousel({
	pause: "false"
});
$('.carousel').css({ 'margin': 0, 'width': $(window).outerWidth(), 'height': $(window).outerHeight() });
//$('.carousel-inner').css({'z-index': 0});
$('.carousel .item').css({ 'position': 'fixed', 'width': '100%', 'height': '100%' });
$('.carousel-inner div.itemimg').each(function () {
	varimgSrc = $(this).attr('src');
	$(this).parent().css({ 'background': 'url(' + imgSrc + ') center center no-repeat', '-webkit-background-size': '100% ', '-moz-background-size': '100%', '-o-background-size': '100%', 'background-size': '100%', '-webkit-background-size': 'cover', '-moz-background-size': 'cover', '-o-background-size': 'cover', 'background-size': 'cover' });
	$(this).remove();
});
$(window).on('resize', function () {
	$('.carousel').css({ 'width': $(window).outerWidth(), 'height': $(window).outerHeight() });
});
});
Continue Reading

What are the best practices of Javscript coding?

Best Practices for Javascript Coding

Inclusion of Code

  • Use external JavaScript files. Do NOT include JavaScript in-line in the page unless there is a good reason.
  • Use the <script> tag to include your JavaScript files at the bottom of your HTML document just before the closing </body> tag. For optimal page performance, concatenate your JavaScript into separate file.

Formatting of Javascript Code

  • Open braces are preceded by a single space.
  • Open braces should appear on the same line as their preceding argument.
  • Close braces should appear at the same indentation as the statement preceding the opening brace.
  • There should be no space characters between parentheses and their contents.
  • Use semicolons and do not rely on automatic semicolon insertion.
  • Each comma and colon (and semi-colons that don’t end a line) should be followed by a single space.

Variable declaration

To avoid confusion between global and local variables, we declare each variable on its own line with the var keyword. We do not use a single var keyword and then chain several variable declarations onto it separated by a comma.

Variable Names and Types

  • Variable names should be Camel Case.
  • Objects, classes, and name-spaces should be Title Case.
  • Boolean values should be prefixed with is if at all possible.
    Cached JQuery objects can be prefixed with $.
  • Use shorthand versions of empty Arrays and Objects.

Examples:

// some examples
var exampleValue ='my example variable value';
var numberOfTimes =3;
// booleans
var isThisWorking =true;
var isNotWorking =0;
// cache a selector
var $body =$('body');
// short hand objects and arrays
var newObject ={};
var newArray =[];

Limit Events ā€” Use Event Delegation

With jQuery this is easy, simply use the on method with a selector:


$('body').on('click','a.scroller',function(){
// this only runs if the a.scroller is matched
});

Too many events bound on a page can mean memory leaks or just an accumulation of handlers bound to DOM elements which becomes less and less efficient over time.

Additionally, event delegation has the added benefit of persisting events over dynamic page updates when items are added or removed from the DOM.

More code practices

  • Avoid using document.write.
  • Only run scripts on a page that are needed for that page.
  • Don’t repeat yourself (i.e. keep your code DRY)
  • Do not modify JavaScript core objects .prototype unless you really know what you’re doing.
  • Use method names that make sense, such as init() or setup() for code that starts things off. Be consistent on your project.
  • Binary and ternary operators should have a single space on each side.
  • Quoted values should be in ‘single quotes’ so that double quotes may easily exist inside them.
  • Comment JavaScript code thoroughly and consider using a pattern such as those described by JSDocs so that documentation may be generated automatically.
  • Conditional statements go on a new line followed by the opening brace. Else/else go on the same line as the brace.
  • Use type strict checks with === as opposed to == whenever possible.
Continue Reading

Change the background color of table row when select a checkbox

Change the background color of table row by checking checkbox using Jquery

Script:


 $(function() {
    $('td:first-child input').change(function() {
        $(this).closest('tr').toggleClass("highlight", this.checked);
});

Explanation

  • Change method is used to identify the event change of checkbox.
  • We can set some CSS properties to class name ‘highclass’ for changing the background color.

Demo

See the Pen Change the background of table row when select a checkbox by Vinothkumar Rajendran (@fedtutorial) on CodePen.0

Continue Reading

How to do Form Validation using Jquery?

Form validation using Jquery

Include the Jquery library and jquery.validate file.

Include below JS files


<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/jquery.validate.min.js"></script>

Script


$(document).ready(function(){
  $(function() {
 $("form[name='register-form']").validate({  
rules: {
         firstname: "required",
		  password: {
			required: true,
			minlength: 6
		  },
         email: {               
             required: true,
             email: true
         },
     },
messages: {
			firstname: "Enter First Name",
			 password: "Enter Passowrd",
			 email: "Enter Valid Email ID"
		},
		 submitHandler: function(form) {
			 form.submit();
		 }
 });

  });
})

Explanation:

Validate method will apply to form. By using validate method we can define two arrays like rules and messages. In the rules, we can set the validation conditions to accept the given input. In the messages part, we should define the validation messages to show when the user entered the detail wrongly.

Output

See the Pen Form validation using Jquery by Vinothkumar (@fedtutorial) on CodePen.0

Continue Reading

How to change the background color of odd and even rows?

Change the background color for odd and event rows using Jquery

‘Odd’ and ‘even’ pseudo classes are used to selecting the odd and even number of row.

Script:


  $(function(){
   $('table tr:even').addClass('even');
    $('table tr:odd').addClass('odd');
});

Explanation:

By using odd and even classes we can set the required background color using CSS.

Demo

See the Pen Change the background color of add and event table rows by Vinothkumar Rajendran (@fedtutorial) on CodePen.0

Continue Reading