Monday, October 9, 2017

React Native Code to vertically stack two sets of boxes

Here's a code I experimented with while brushing up on React Native. This stacks two sets of boxes in a vertical position. The first set is stacked to the top, while the second at stacked at the bottom. Here is the output on the mobile screen when viewed in the normal landscape manner:

When the mobile device is tilted, the auto rotate still keeps the boxes in their default positions.

My React Native code defines two components for the boxes, the TopBoxes, which well, stacks the first set of boxes (the red, green and blue) to the top and the BottomBoxes, which well again, stacks the second set of boxes (the blue variations) to the bottom.

The main component AlignItemsBasics, will render the main View, which in turn calls the TopBoxes and BottomBoxes components. Both TopBoxes and BottomBoxes components styles will overwrite the default AlignItemsBasics style.

The full code is shown below

import React, {Component} from 'react';
import {AppRegistry, View} from 'react-native';

class TopBoxes extends Component{
 render(){
  return(
   <View style={{
    flex:1,
    justifyContent: 'flex-start',
    alignItems: 'flex-start',
   }}>
    <View style={{width: 50, height: 50, backgroundColor: 'red'}} />
    <View style={{width: 50, height: 50, backgroundColor: 'green'}} />
    <View style={{width: 50, height: 50, backgroundColor: 'blue'}} />
   </View>
  );
 }
}

class BottomBoxes extends Component{
 render(){
  return(
   <View style={{
    flex:1,
    justifyContent: 'flex-end',
    alignItems: 'flex-end',
   }}>
    <View style={{width: 50, height: 50, backgroundColor: 'skyblue'}} />
    <View style={{width: 50, height: 50, backgroundColor: 'steelblue'}} />
    <View style={{width: 50, height: 50, backgroundColor: 'powderblue'}} />
   </View>
  );
 }
}

export default class AlignItemsBasics extends Component{
 render(){
  return(
   <View style={{
    flex:1,
    flexDirection: 'column',
    justifyContent: 'center',
    alignItems: 'center',
   }}>
   <TopBoxes />
   <BottomBoxes />
   </View>
  );
 }
};

AppRegistry.registerComponent('AwesomeProject', () => AlignItemsBasics);

The JSFiddle link for the code can be found at https://jsfiddle.net/jundolor/kphc0a4w/

Sunday, April 23, 2017

JQuery code to restrict form entries to alphanumeric and force lowercase to uppercase

I've come up with a JavaScript/JQuery code that restricts form input entries to alphanumeric and at the same time forces lowercase letter entries to uppercase entries. Users entering the form may only type letters and numbers but when they type lower case letters, the entry gets converted to uppercase. The HTML code is listed below. A form with with ID "input-toupper" is where the user will type in their entry. The javaScript on script.js will restrict the entry to letters and numerals. But when a lowwercase letter is entered, it gets converted to uppercase.
<!DOCTYPE html>
<html>
<head>
 <title>Restrict enter and force lower to upper</title>
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
 <script type="text/javascript" src="script.js"></script>
</head>
<body>
<form>
 <!--restricts entry to alpha number and forces lowercae to uppercase-->
 <input id="input-toupper" type="text">
</form>
</body>
</html>

The JavaScript contains the JQUery code for make this happen. The keydown event for the input checks against the regex to see if the character typed in is a letter or numeral. If the character entry does not match the regex, the entry is prevented on the input.
$(document).ready(function(){

 $('input#input-toupper').on('keypress',function(event){
  var regex=new RegExp("^[a-zA-Z0-9]+$");
  var key=String.fromCharCode(!event.charCode?event.which:event.charCode);
  if(!regex.test(key)){
   event.preventDefault();
   return false;
  }
 });
 
 $('input#input-toupper').on('keyup',function(){
  
  var toupper=$(this).val().toUpperCase();
  $(this).val(toupper);
 })
})

The jsfiddle link to the codes can be found here, https://jsfiddle.net/jundolor/sm0jjopm/

Thursday, April 13, 2017

Creating a radar monitor like animation using HTML5 and JavaScript

Using HTML5 Canvas and JavaScript, I created a radar monitor like animation-this where you see a line from the center to the end of a round screen, moving in a clockwise direction. The screen shots below shows how the animation works:


The HTML code defines a canvas (id:myCanvas) where the animation will happen. As soon as all HTML elements have been rendered, the function init() is triggered,



The CSS draws a border around the canvas.






Just like the previous blog, the JavaScript code starts by declaring the c and ctx variables. These will hold the canvas HTML object and define the context of the canvas respectively. Unlike the previous blog wherein the arc angle parameters are in radians, I assigned the parameter values in degrees. The x1 and y1 variables will be the center position of the arc.











The function init() is called when all HTML elements have been rendered.








The function draw() calls the JavaScript built-in function setInterval(). Parameters are the callback function and millisecond interval when the callback function is triggered.











The callback function clears any previous drawn object by refilling the canvas with yellow color, i.e. gives an animating effect. The variables startAngle and endAngle are incremented with the arc length (degree). Once the endAngle reaches 360 (degrees), both startAngle and endAngle are reset to their default values. The arc lis drawn using degree values.












The x and y coordinates of the endAngle end degree are computed.



A line is drawn from the center of the arc to the end point defined by the x and y coordinates.






The code is listed below.

<!DOCTYPE html>
<html>
<head>
 <title>Animating circle</title>
 <style type="text/css">
  canvas{
   border:1px solid #000;
  }
 </style>
 <script type="text/javascript">
  var c, ctx;
  var arcLength = 30;//in degrees
  var startAngle = 0;//in degrees
  var endAngle = 360;//in degrees
  var radius = 100;
  var x1 = 300;
  var y1 = 200;

  function init(){
   c = document.querySelector("#myCanvas");
   ctx = c.getContext("2d");
   ctx.strokeStyle = "red";

   draw();
  }

  function draw(){

   setInterval(function(){
    //redraw the canvas
    ctx.fillStyle = "yellow";
    ctx.fillRect(0, 0, c.width, c.height);

    if(endAngle >= 360){
     //reset
     startAngle = 0;
     endAngle = arcLength;
    }
    else{
     //start where the last angle ended
     startAngle = endAngle;
     endAngle += arcLength;
    }

    ctx.beginPath();
    ctx.arc(x1, y1, radius, startAngle*Math.PI/180, endAngle*Math.PI/180);
    ctx.stroke();
    //ctx.closePath();

    // compute x and y coordinates of the end angle relative to canvas
    var x2 = x1 + Math.cos(endAngle * Math.PI / 180) * radius;
    var y2 = y1 + Math.sin(endAngle * Math.PI / 180) * radius;

    console.log('startAngle', startAngle);
    console.log('endAngle', endAngle);

    console.log('x2',x2);
    console.log('y2',y2);

    console.log('x2 end',x2|0);
    console.log('y2 end',y2|0);

    console.log(startAngle*Math.PI);
    console.log(endAngle*Math.PI);

    console.log('***');

    ctx.beginPath();
    ctx.moveTo(x1, y1);
    ctx.lineTo(x2, y2);
    ctx.stroke();
    //ctx.closePath();

   }, 50);
   
  }
 </script>
</head>
<body onload="init();">
 <canvas id="myCanvas" width="600" height="400"></canvas>
</body>
</html>


The code is also available at this jsfiddle link, https://jsfiddle.net/dyy5xtv2/

Running around in circle animation using HTML5 Canvas

Using HTML5 and JavaScript, I'll be creating a running around in circle animation effect. The screen shots below will show how the animation will look like:


The animation will consist mainly of drawing a portion on the circle at regular intervals. Each interval will clear the previously drawn portion and start the new portion where the cleared portion ended.

The HTML code creates a canvas with an id "myCanvas" width of 600px and height of 400px. As soon as all HTML elements are rendered, the JavaScript function init() is called.

The CSS code creates a black solid border around the canvas.
The JavaScript starts by declaring variables that will be used for the animation. The variable c will hold the canvas object while ctx will define the context of the canvas. The variable arcLength will be the portion of the circle that will be drawn, which is 1/16 of the circumference. The variable startLength will be set to initial zero. In HTML5, the value zero is positioned at the 3 o'çlock of the circle. The endAngle is end portion to be drawn.
The function init() is called when all HTML elements have been rendered. The document object function querySelector() identifies the canvas by its id and assigns it as an object to the variable c. The context of the canvas will be in 2D. The portion that will be drawn on the circle to create the animating effect will be in color red. The function draw() is called next.
The setInterval function called by draw() is a built in JavaScript function. This takes two parameters, a callback function, and the interval in milliseconds when the callback function will be called repeatedly.
The callback starts by refilling the canvas with the color yellow. The circle portion that was drawn in the previous call is covered by the refill of the canvas, i.e. cleared on the current call. HTML5 defines zero position at 3 o'clock of the circle; the position 2 closes the circle. When the endAngle reaches the position 2, both startAngle and endAngle are reset.  Otherwise, the startAngle takes the previous endAngle and the endAngle is incremented by the circle portion to be drawn.

The circle, or circle portion is drawn on the canvas.
The jsfiddle link to the full code is at https://jsfiddle.net/jundolor/bebyqpxq/

This is my  first attempt in creating animations using HTML5. In future blogs, I will attempt to create more complex animations.

Tuesday, March 8, 2016

Embedding YouTube Videos in Bootstrap

The YouTube Embed provides an HTML code to insert the video in your web page. However, the code it self is not (mobile) responsive.

The steps I will describe shows how to use Bootstrap tags in embedding a YouTube video to make it mobile responsive.

The YouTube video https://www.youtube.com/watch?v=i4klEY-S3OQ will be added in a blog post of my client's Bootstrap enabled WordPress themed website.

I started by copying the embed code of the YouTube video. (Code is then pasted to Notepad application)


The html code is listed below. The src attribute contains the link to the YouTube video.
<iframe width="560" height="315" src="https://www.youtube.com/embed/i4klEY-S3OQ?rel=0&amp;controls=0" frameborder="0" allowfullscreen></iframe>

W3schools provides a page where you may copy the Bootstrap tags to embed YouTube videos,  http://www.w3schools.com/bootstrap/bootstrap_images.asp. I copied/ pasted the code to the NotePad where I also pasted the embed code

Here is the code. The src attribute contains the value "...". This should contain the YouTube link.
<div class="embed-responsive embed-responsive-16by9">
  <iframe class="embed-responsive-item" src="..."></iframe>
</div>

The NotePad, which has both the embed tag and the Bootstrap code. 

The src attribute value of the iFrame is copied:

The value is pasted to the iFrame src attribute of the Bootstrap tag:

Here is the code:
<div class="embed-responsive embed-responsive-16by9">
  <iframe class="embed-responsive-item" src=""https://www.youtube.com/embed/i4klEY-S3OQ?rel=0&amp;controls=0"></iframe>
</div>

Finally, the code is added to the blog post:

On desktop https://mentorgroup.org/2016/03/the-mentor-group-rewards-points/, here is the blog with the YouTube video:

On mobile, the embedded YouTube video responded well:

Perfect!

Sunday, July 12, 2015

Calling JavaScript inner array methods

JavaScript array methods may be placed inside an outer array method. When the outer method is run, the inner method is run against the current array element. In this post, the array that will be used is still the objects containing computer units issued to persons. The objective is to determine the percentage of an individual free HD space against the total HD free space:


The standard approach using a for() loops would be as follows:

<script>
 var units =[
 {name: "Ernie", GBHD: 500, GBHDFree: 300, OS: "Windows"}, 
 {name: "Bert", GBHD: 800, GBHDFree: 350, OS: "MacOS"}, 
 {name: "Kermit", GBHD: 600, GBHDFree: 380, OS: "Windows"},
 {name: "Oscar", GBHD: 450, GBHDFree: 200, OS: "Windows"},
 {name: "Grover", GBHD: 700, GBHDFree: 300, OS: "MacOS"}, 
 {name: "Count", GBHD: 700, GBHDFree: 250, OS: "MacOS"}
 ];
 
 var totalFree = 0;
 
 for(var i =0; i < units.length; i++){
  totalFree += units[i].GBHDFree;
 }
 
 var freePercent = [];
 
 for(var i =0; i < units.length; i++){
  freePercent.push((units[i].GBHDFree/totalFree) * 100);
 }
 
 console.log(freePercent);
 </script>

An alternative approach is to use the array map() method to create a parallel array to the units array. The map() method calls a function that goes through each object element and determines the elements free HD space.


The function then calls a combine units array map() and reduce() methods. The map() creates a parallel array of free HD space for each units object element. The reduce() computes the total of each element (Free HD space) in the parallel array.


The combine map() and reduce() are the inner methods called by the function in the outer map() method. The code snipper is listed below:
<script>
 var units =[
 {name: "Ernie", GBHD: 500, GBHDFree: 300, OS: "Windows"}, 
 {name: "Bert", GBHD: 800, GBHDFree: 350, OS: "MacOS"}, 
 {name: "Kermit", GBHD: 600, GBHDFree: 380, OS: "Windows"},
 {name: "Oscar", GBHD: 450, GBHDFree: 200, OS: "Windows"},
 {name: "Grover", GBHD: 700, GBHDFree: 300, OS: "MacOS"}, 
 {name: "Count", GBHD: 700, GBHDFree: 250, OS: "MacOS"}
 ];
 var getPercentageFree = function(unit){
  var free = unit.GBHDFree;
  var totalFree = units.map(function(unit){return unit.GBHDFree}).reduce(function(start, current){
   return start + current;
  }, 0);
  return (free / totalFree) * 100;
 }
 
 console.log(units.map(getPercentageFree));
 
 </script>

The full code is available at:
https://github.com/jundolor/JavaScript/blob/master/callinginnerarraymethods.html

Monday, July 6, 2015

Combining JavaScript Array Methods filter() and reduce()

JavaScript array methods may be combined to generate a result. The code study in this post will filter selected array elements and summarize the data. The JavaScript array methods that will be combined are filter() and reduce().

The array which will be the subject of the code study is shown below:


Each element of the array is an object with key-value pairs. The idea of the array is to provide information on computers that have been issued to various persons., The name key identifies the person, GBHD stands for Giga Byte HD- the total capacity of the HD, GBHDFree stands for Guga Byte HD Free-meaning the free space on the HD, and OS-the operating system of the computer

Using method filter(), as shown in the code snippet below, the array is narrowed down to computer units with MacOS as the operating system:
      
<script>
 var units =[
 {name: "Ernie", GBHD: 500, GBHDFree: 300, OS: "Windows"}, 
 {name: "Bert", GBHD: 800, GBHDFree: 350, OS: "MacOS"}, 
 {name: "Kermit", GBHD: 600, GBHDFree: 380, OS: "Windows"},
 {name: "Oscar", GBHD: 450, GBHDFree: 200, OS: "Windows"},
 {name: "Grover", GBHD: 700, GBHDFree: 300, OS: "MacOS"}, 
 {name: "Count", GBHD: 700, GBHDFree: 250, OS: "MacOS"}
 ];
 
 var filterOS = function(u){
  return u.OS == "MacOS"
 }
 
 console.log("MacOS Units:" ,units.filter(filterOS));
 //MacOS Units: {name: Bert...}, {name: Grover...}, {name: Count...}
 
</script>

The method filter() calls the function filterOS(). Each array element, an object is passed to the parameter. The function returns back the object has "MacOS" as the value to the OS key. All other objects are filtered out. An array of objects with key-value pair of OS: "MacOS" is returned. Note that the original array is retained.

The method reduce(), as shown in the code snippet below calls the function mostHDFree(). The function, in turn, goes thru each array element, an object, to see which has the biggest GBHDFree value.

<script>
 var units =[
 {name: "Ernie", GBHD: 500, GBHDFree: 300, OS: "Windows"}, 
 {name: "Bert", GBHD: 800, GBHDFree: 350, OS: "MacOS"}, 
 {name: "Kermit", GBHD: 600, GBHDFree: 380, OS: "Windows"},
 {name: "Oscar", GBHD: 450, GBHDFree: 200, OS: "Windows"},
 {name: "Grover", GBHD: 700, GBHDFree: 300, OS: "MacOS"}, 
 {name: "Count", GBHD: 700, GBHDFree: 250, OS: "MacOS"}
 ];
 
 
 var mostHDFree = function(start, current){
  if(start.GBHDFree > current.GBHDFree) return start;
  else return current;
 }
 
 console.log("Unit with most HD free space",units.reduce(mostHDFree));
 //Unit with most HD free space {name: "Kermit", GBHD: 600, GBHDFree: 380, OS: "Windows"}
</script>

The methods filter() and reduce() may be combined to determine what objects with key-value pair of OS: "MacOS" has the most GBHDFree value.

JavaScript starts with the leftmost method and soon as a result is generated, calls the next method to the right, passing the generated result. The cycle will continue for additional methods to the right.

In the case of the filter() and reduce method() combine, the filter() returns an array of objects with OS: "MacOS". The array is passed to the reduce() method which selects the object with the most GBHDFree value.

The code snippet is listed below:
<script>
 var units =[
 {name: "Ernie", GBHD: 500, GBHDFree: 300, OS: "Windows"}, 
 {name: "Bert", GBHD: 800, GBHDFree: 350, OS: "MacOS"}, 
 {name: "Kermit", GBHD: 600, GBHDFree: 380, OS: "Windows"},
 {name: "Oscar", GBHD: 450, GBHDFree: 200, OS: "Windows"},
 {name: "Grover", GBHD: 700, GBHDFree: 300, OS: "MacOS"}, 
 {name: "Count", GBHD: 700, GBHDFree: 250, OS: "MacOS"}
 ];
 
 var filterOS = function(u){
  return u.OS == "MacOS"
 }
 
 var mostHDFree = function(start, current){
  if(start.GBHDFree > current.GBHDFree) return start;
  else return current;
 }
 
 console.log("MacOS with most HD space free",units.filter(filterOS).reduce(mostHDFree));
 //MacOS with most HD space free {name: "Bert"...}, 
</script>

The full code can be downloaded at:
https://github.com/jundolor/JavaScript-Combine-Array-Methods/blob/master/index.html