FOLLOW

Thursday, April 19, 2018

Simple JavaScript code to design calculator

For creating a basic calculator in JavaScript, we use table structure, input type button, and JavaScript functions.


  • Input type button use is to take input from the user.
  • The table structure use is to create calculator structure.
  • Functions to evaluate the data.



Three simple functions to process all data

Script

1. element()
Which is used to read values from each button

function element(val){
document.getElementById('result').value+=val;
}


2. solve()
This function performs all arithmetic operations like(+,-,/,*)

function solve(){
var value1= document.getElementById('result').value;
let res = eval(value1);
document.getElementById('result').value=res;
}


3. clearElement()
Which is used to clear input value in the calculator 

function element(val){
document.getElementById('result').value+=val;
}

HTML


<body>
<div id='wrap'>
<table border="1">
<tr>
<td colspan="3"><input type="text" id="result" readonly></td>
<td><input type="button" value="C"  onClick="clearElement()"></td>
</tr>
<tr>
<td><input type="button" value="1" onClick="element('1')"></td>
<td><input type="button" value="2" onClick="element('2')"></td>
<td><input type="button" value="3" onClick="element('3')"></td>
<td><input type="button" value="+" onClick="element('+')"></td>
</tr>
<tr>
<td><input type="button" value="4" onClick="element('4')"></td>
<td><input type="button" value="5" onClick="element('5')"></td>
<td><input type="button" value="6" onClick="element('6')"></td>
<td><input type="button" value="-" onClick="element('-')"></td>
</tr>
<tr>
<td><input type="button" value="7" onClick="element('7')"></td>
<td><input type="button" value="8" onClick="element('8')"></td>
<td><input type="button" value="9" onClick="element('9')"></td>
<td><input type="button" value="/" onClick="element('/')"></td>
</tr>
<tr>
<td><input type="button" value="*" onClick="element('*')"></td>
<td><input type="button" value="0" onClick="element('0')"></td>
<td><input type="button" value="." onClick="element('.')"></td>
<td><input type="button" value="=" onClick="solve()"></td>
</tr>
</table>
</div>
</body>

CSS


<style type="text/css">
body,html{
matgin:0px;
}
input[type="button"]{
border:none;
width:100%;
outline: none;
}
#wrap
{
margin:10%;
}
</style>



Tuesday, April 17, 2018

Generating path between start and end points through way points using google map API

In this article we explaining about how to dynamically generate a path between multiple points(start, end and way points) by using google map direction API.

Here is the simplest way of doing it, we explain it step by step.

CSS

<style>
      #right-panel {
        font-family: 'Roboto','sans-serif';
        line-height: 30px;
        padding-left: 10px;
      }

      #right-panel select, #right-panel input {
        font-size: 15px;
      }

      #right-panel select {
        width: 100%;
      }

      #right-panel i {
        font-size: 12px;
      }
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
      #map {
        height: 100%;
        float: left;
        width: 70%;
        height: 100%;
      }
      #right-panel {
        margin: 20px;
        border-width: 2px;
        width: 20%;
        height: 400px;
        float: left;
        text-align: left;
        padding-top: 0;
      }
      #directions-panel {
        margin-top: 10px;
        background-color: #23b0ff;
        padding: 10px;
        overflow: scroll;
        height: 174px;
      }
    </style>

Script

<script>
      function initMap() {
        var directionsService = new google.maps.DirectionsService;
        var directionsDisplay = new google.maps.DirectionsRenderer;
        var map = new google.maps.Map(document.getElementById('map'), {
          zoom: 6,
          center: {lat: 41.85, lng: -87.65}
        });
        directionsDisplay.setMap(map);

        document.getElementById('submit').addEventListener('click', function() {
          calculateAndDisplayRoute(directionsService, directionsDisplay);
        });
      }

      function calculateAndDisplayRoute(directionsService, directionsDisplay) {
        var waypts = [];
        var checkboxArray = document.getElementById('waypoints');
        for (var i = 0; i < checkboxArray.length; i++) {
          if (checkboxArray.options[i].selected) {
            waypts.push({
              location: checkboxArray[i].value,
              stopover: true
            });
          }
        }

        directionsService.route({
          origin: document.getElementById('start').value,
          destination: document.getElementById('end').value,
          waypoints: waypts,
          optimizeWaypoints: true,
          travelMode: 'DRIVING'
        }, function(response, status) {
          if (status === 'OK') {
            directionsDisplay.setDirections(response);
            var route = response.routes[0];
            var summaryPanel = document.getElementById('directions-panel');
            summaryPanel.innerHTML = '';
            // For each route, display summary information.
            for (var i = 0; i < route.legs.length; i++) {
              var routeSegment = i + 1;
              summaryPanel.innerHTML += '<b>Route Segment: ' + routeSegment +
                  '</b><br>';
              summaryPanel.innerHTML += route.legs[i].start_address + ' to ';
              summaryPanel.innerHTML += route.legs[i].end_address + '<br>';
              summaryPanel.innerHTML += route.legs[i].distance.text + '<br><br>';
            }
          } else {
            window.alert('Directions request failed due to ' + status);
          }
        });
      }
    </script>
API
    <script async defer
    src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
    </script>

Here is the procedure to create new API key
Body
<div id="map"></div>
<a href ='http://www.phpjavascript.com/2018/02/how-to-add-google-map-to-website-using.html'>MAP</a>
    <div id="right-panel">

    <div>

    <b>Start:</b>

    <select id="start">

      <option value="Hyderabad">Hyderabad</option>

      <option value="Banglore">Banglore</option>

      <option value="Delhi">Delhi</option>

      <option value="Pune">Pune</option>

    </select>

    <br>

    <b>Waypoints:</b> <br>

    <i>(Ctrl+Click or Cmd+Click for multiple selection)</i> <br>

    <select multiple id="waypoints">

      <option value="Delhi">Delhi</option>

      <option value="Banglore">Banglore</option>

      <option value="Chenai">Chenai</option>

      <option value="Hyderabad">Hyderabad</option>

      <option value="Tripura">Tripura</option>

      <option value="Varanasi">Varanasi</option>

    </select>

    <br>

    <b>End:</b>

    <select id="end">

      <option value="Chenai">Chenai</option>

      <option value="Kolkata">Kolkata</option>

      <option value="Mumbai">Mumbai</option>

      <option value="Rajasthan">Rajasthan</option>

    </select>

    <br>

      <input type="submit" id="submit">

    </div>

    <div id="directions-panel"></div>

    </div>

Result


Saturday, April 14, 2018

How to draw a path between two marker points?

In this tutorial, we’ll be learning about how to draws a route between two points. We’ll be using Google Maps Directions API in our application.

Create a new Google Map API Key from the API console using the steps demonstrated in this tutorial.

CSS

You can define map height and width under #map section 
Add this code in your head section of the html file

    <style>
      #map {
        height: 100%;
      }
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
    </style>

Script


<script>

      function initMap() {
        var map = new google.maps.Map(document.getElementById('map'), {
          zoom: 10, 
          center: {lat: 17.3483, lng: 78.3915}, //Default location to show on the map
          mapTypeId: 'terrain'
        });

       //Two coordinates to draw a path
        var flightPlanCoordinates = [
          {lat: 17.4483, lng:  78.3915},
          {lat: 17.291, lng: 78.821}
        ];

        //Draw a simple Polyline
        var flightPath = new google.maps.Polyline({
          path: flightPlanCoordinates,
          geodesic: true,
          strokeColor: '#FF0000',
          strokeOpacity: 1.0,
          strokeWeight: 2
        });

        flightPath.setMap(map);
      }
    </script>


Use your API key here, that you created in the google console.
If you are not created follow this link to create, it's a simple process.

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

Body


<body>
      <div id='map'>
</body>

 Result




Monday, March 26, 2018

Simple Text Animation Using HTML, CSS and JQuery

In this article, we are explaining a very simple way to animate text in different ways.

1. Includes(jquery and bootstrap libraries)
2. CSS to design content
3. Body of content
4. Javascript to perform actions

Animations
1. Blur-in on mouse hover
2. Blur-out on mouse hover
3. Change background to the text
4. Show/hide text in sequence


Includes

   <script src="https://code.jquery.com/jquery-1.12.4.js"></script>    <link rel="stylesheet" href='https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css'>


css

    <style>
            #fadeIn { font: 15px monospace; }
            #fadeIn .letter { opacity: 0; }
            #fadeIn .opacity {
                -webkit-transition: opacity .15s ease-in-out;
                -moz-transition: opacity .15s ease-in-out;
                -ms-transition: opacity .15s ease-in-out;
                -o-transition: opacity .15s ease-in-out;
                transition: opacity .15s ease-in-out;
                opacity: 1;
            }
            #backgroundPaint .background {
                -webkit-transition: background .3s ease-in-out;
                -moz-transition: background .3s ease-in-out;
                -ms-transition: background .3s ease-in-out;
                -o-transition: background .3s ease-in-out;
                transition: background .3s ease-in-out;
                background: yellow;
            }
            h1, h2
            {
                font-size: 1.6em;
                font-weight: normal;
                margin: 0;
            }
            h2
            {
                font-size: 1.3em;
                margin-top: 1.5em;
            }
            a.blur
            {
                text-decoration: none;
                color: #339;
            }
            a.blur:hover, a.blur:focus
            {
                text-decoration: underline;
                color: #933;
            }
            .textshadow a.blur, .textshadow a.blur:hover, .textshadow a.blur:focus
            {
                text-decoration: none;
                color: rgba(0,0,0,0);
                outline: 0 none;
                -webkit-transition: 400ms ease 100ms;
                -moz-transition: 400ms ease 100ms;
                transition: 400ms ease 100ms;
            }

            .textshadow a.blur,
            .textshadow a.blur.out:hover, .textshadow a.blur.out:focus
            {
                text-shadow: 0 0 4px #339;
            }
            .textshadow a.blur.out,
            .textshadow a.blur:hover, .textshadow a.blur:focus
            {
                text-shadow: 0 0 0 #339;
            }
        </style>



Body

    <body>
        <div id="fadeIn">
            <button>Click</button>
            <h2>Hello Programmer, Welcome to PHP Javascript - Wonderful place to learn programming.</h2>
        </div>

        <div id="backgroundPaint">
            <button>Click</button>
            <h2>Hello Programmer, Welcome to PHP Javascript - Wonderful place to learn programming.</h2>
        </div>

        <p>The following links blur in on hover/focus</p>

        <h1><a href="http://www.phpjavascript.com/" class="blur">Hover me (Blur-in)</a></h1>

        <p>The following links blur out on hover/focus</p>

        <h1><a href="http://www.phpjavascript.com/2018/01/display-json-data-in-table-using-jquery.html" class="blur out">Hover me (Blur-out)</a></h1>
    </body>



JavaScript

<script>
        $.fn.animateText = function (delay, styleclass) {
            var text = this.text();
            return this.each(function () {
                var $this = $(this);
                $this.html(text.replace(/./g, '<span class="letter">$&</span>'));
                $this.find('span.letter').each(function (i, el) {
                    setTimeout(function () {
                        $(el).addClass(styleclass);
                    }, delay * i);
                });
            });
        };

        $('#fadeIn button').click(function () {
            $(this).next('h2').animateText(15, 'opacity');
        });

        $('#backgroundPaint button').click(function () {
            $(this).next('h2').animateText(8, 'background');
        });

        if (document.createElement("detect").style.textShadow === "") {
            document.getElementsByTagName("html")[0].className += " textshadow";
        }
    </script>



Note:Paste javscript code at te bottom of your html code.
*Please share the article and follow our PHP Javascript for more.

Display JSON data in dropdown

Display JSON data in a table



Thursday, March 22, 2018

Form Validation Using Jquery

The code that every web developer looking for. Validating a form in all possible ways. A simple and effective code is here. 

Here we are validating all common input types which we use in register form like name, email, phone, password, radio button, select option.

Includes

    <link rel="stylesheet" href='https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css'>
    <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.js"></script>



Script

<script>
function Validate() {

(function ($) {

 jQuery.validator.setDefaults({
       errorPlacement: function (error, element) {
            error.appendTo('#invalid-' + element.attr('id'));
       }
});

//To validate letters

$.validator.addMethod("letters", function (value, element) {
   return this.optional(element) || value == value.match(/^[a-zA-Z\s]*$/);
});



//To validate Number
$.validator.addMethod("number", function (value, element) {
      return this.optional(element) || value == value.match(/^[0-9]*$/);
});

//To validate digits for phone number that should start with only 7 or 8 or 9
$.validator.addMethod("digits", function (value, element) {
    return this.optional(element) || value == value.match(/^^[789]\d{9}$/);
});

//To validate password
$.validator.addMethod("pwcheckNumber",
   function (value, element) {
   return /\d/.test(value);
});

$.validator.addMethod("pwcheckUppercase",
   function (value, element) {
   return /[A-Z]/.test(value);
});

$.validator.addMethod("pwcheckSpecial",
     function (value, element) {
     return /[!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~]/.test(value);
});

//Form validation
$("#Form").validate({
                    
rules: {

Title: {
     required: true,                  
},

FirstName: {
   required: true,
   minlength: 3,
   letters: true                      
},

Mobile: {
    required: true,
    number: true,
    minlength: 10,
    maxlength: 10,
    digits: true                      
},

Email: {
    required: true,
    email: true,
},

Password: {
     required: true,
     minlength: 8,
     pwcheckNumber: true,
     pwcheckUppercase: true,
     pwcheckSpecial: true,          
},

ConfirmPassword: {
     required: true,
     equalTo: "#Password"                   
},

Gender: {
     required: true,
}
     
},

//Message suggestions that you see on screen     
messages: {

Title: {
       required: "Please select title",
},

FirstName: {
      required: "Please enter first name",
      minlength: "Name should be minimum 3 characters",
      letters: "Only letters and spaces are allowed",                              
},

Mobile: {
       required: "Please enter  phone number",
       minlength: "Please enter valid phone number",
       maxlength: "Please enter valid phone number",
       digits: "Phone number should be start with 789", 
},

Email: {
      required: "Please enter email",
      minlength: "Please enter a valid email address",
},

Password: {
       required: "Please enter password",
       minlength: "Password must be minmum 8 character",
       pwcheckNumber: "Password must contains one digit",
       pwcheckUppercase: "Password must contains atleast one uppercase letter",
       pwcheckSpecial: "Password must contains atleast one special character",
},

ConfirmPassword: {
       required: "Please enter confirm password ",
       equalTo: "Confirm password must same as password",
},

Gender: {
       required: "Please select gender type"                     
}
}

});
})($);
}
</script>

//CSS
<style>
.error_msg {
        color: red;
}

body{
        position: absolute;
        width: 600px;
        height: 200px;
        z-index: 15;
        top: 15%;
        left: 30%;
        margin: -100px 0 0 -150px;
     }

.box-header{
        background: #dc3545;
        width: 500px;
        height: auto;
text-align: center;
        color: white;
        font-size: 30px;
        padding: 10px;
    }

.box{
        background: #43c181;
        padding-top: 10px;
        padding-left: 110px;
        padding-bottom: 30px;
        width: 500px;
        height: auto;
    }
</style>




<body onload="Validate()">

<div class="box-header">Register From</div>

<div class="box">

    <form action='#' method='post' id='Form' enctype='multipart/form-data'>
        <div class="col-md-8">
            <label>Title</label>
            <select id="Title" name="Title" class="form-control">
                <option value="">Select Title</option>
                <option value="Mr.">Mr.</option>
                <option value="Mrs.">Mrs.</option>
                <option value="Ms.">Ms.</option>
                <option value="Mss.">Mss.</option>
                <option value="Dr.">Dr.</option>
            </select>
            <div id="invalid-Title" class="error_msg"></div>
        </div>

        <div class="col-md-8">
            <label>First Name</label>
            <input type="text" id="FirstName" name="FirstName" class="form-control"
                   placeholder="First Name"/>
            <div id="invalid-FirstName" class="error_msg"></div>
        </div>

        <div class="col-md-8">
            <label>Mobile</label>
            <input type="text" id="Mobile" name="Mobile" class="form-control" placeholder="Mobile">
            <div id="invalid-Mobile" class="error_msg"></div>
        </div>

        <div class="col-md-8">
            <label>Email</label>
            <input type="text" id="Email" name="Email" class="form-control" placeholder="Email">
            <div id="invalid-Email" class="error_msg"></div>
        </div>

        <div class="col-md-8">
            <label>Password</label>
            <input type="password" id="Password" name="Password" class="form-control"
                   placeholder="Password"/>
            <div id="invalid-Password" class="error_msg"></div>
        </div>

        <div class="col-md-8">
            <label>Confirm Password</label>
            <input type="password" id="ConfirmPassword" name="ConfirmPassword" class="form-control"
                   placeholder="ConfirmPassword"/>
            <div id="invalid-ConfirmPassword" class="error_msg"></div>
        </div>

        <div class="col-md-8">
            <label>Gender</label>
            <input type="radio" id="Gender" name="Gender" value="Male"> Male
            <input type="radio" id="GenderNew" name="Gender" value="Female"> Female<br>
            <div id="invalid-Gender" class="error_msg"></div>
        </div>

        <div class="col-md-12" align="center">
            <input type="submit" value="Submit" class="btn btn-danger" id="Submit" name="Submit"
                   onclick="Register()">
        </div>
    </form>

</div>

</body>


Result



*Please share, comment and subscribe to PHP Javascript for more.

Display JSON data in dropdown

Display JSON data in a table