Wednesday 31 October 2018

css selector with attribute value




$('a[href$="ABC"]')...

= is exactly equal
!= is not equal
^= is starts with
$= is ends with
*= is contains
~= is contains word
|= is starts with prefix (i.e., |= "prefix" matches "prefix-...")

css selector with attribute's value contains








Tuesday 23 October 2018

Length of Number in JavaScript

get length of number with out converting to string.



Method 1: 
var x = 1234567;

x.toString().length;

Method 2:
const num = 123456
`${num}`.length // 6


Thursday 18 October 2018

detect webview or browser


This is working and tested in all platforms

Step1: create a Utility file

export class Utility {
constructor() { }

public static get isMobile(): boolean {

if (this.isIOS || this.isAndroid) {
return true;
} else {
return false;
}
}

public static get isWebview(): boolean {
const useragent = navigator.userAgent;
const rules = ['WebView', '(iPhone|iPod|iPad)(?!.*Safari\/)', 'Android.*(wv|\.0\.0\.0)'];
const regex = new RegExp(`(${rules.join('|')})`, 'ig');
return Boolean(useragent.match(regex));
}

public static get isWindowsPhone(): boolean {
const userAgent = navigator.userAgent || navigator.vendor || window['opera'];
// Windows Phone must come first because its UA also contains "Android"
if (/windows phone/i.test(userAgent)) {
return true;
} else {
return false;
}
}

public static get isAndroid(): boolean {
const userAgent = navigator.userAgent || navigator.vendor || window['opera'];
return /android/i.test(userAgent);
}

public static get isIOS(): boolean {
const userAgent = navigator.userAgent || navigator.vendor || window['opera'];
if (/iPad|iPhone|iPod/.test(userAgent) && !window['MSStream']) {
return true;
} else {
return false;
}
}
}

Step2: import in ur file .ts
import { Utility } from '../../classes/util';

Usage :
if (Utility.isWebview && Utility.isAndroid) {

} else if (Utility.isWebview && Utility.isIOS) {

}

Wednesday 17 October 2018

table with fixed td

This combined solution worked for me, I wanted equal width columns

<style type="text/css">

    table {
        table-layout: fixed;
        word-wrap: break-word;
    }

        table th, table td {
            overflow: hidden;
        }

</style>

enter image description here





Monday 15 October 2018

Angular directive that automatically adjusts textarea height to fit content.


Angular directive that automatically adjusts textarea height to fit content.

HTML:
<textarea MyAppAutoHeight 
class="my-textarea">Hello, this is an example of Autosize in Angular.</textarea>

TS - Directive:
import { Directive, HostListener, ElementRef, Input, OnInit } from '@angular/core';

@Directive({
  selector: '[MyAppAutoHeight]' // Attribute selector
})
export class AutoHeightDirective implements OnInit {
  // @Input('autoresize') maxHeight: string;
  @Input() maxHeight: string;

  @HostListener('input', ['$event.target'])
  onInput(textArea: HTMLTextAreaElement): void {
    this.adjust();
  }

  constructor(public element: ElementRef) {
  }

  ngOnInit(): void {
    this.adjust();
  }

  adjust(): void {
    const ta = this.element.nativeElement;
    let newHeight;

    if (ta) {
      ta.style.overflow = 'hidden';
      ta.style.height = 'auto';
      if (this.maxHeight) {
        newHeight = Math.min(ta.scrollHeight, +this.maxHeight);
      } else {
        newHeight = ta.scrollHeight;
      }
      if (newHeight === 0) {
        ta.style.height = '50px';
      } else {
        ta.style.height = newHeight + 'px';
      }
    }
  }
}

Tuesday 28 August 2018

2 Way Data Binding in JavaScript

2 Way Data Binding in Plain Vanilla JavaScript
Whenever someone asks me about the advantages of AngularJS the first thing that simply comes into my mind is 2-way data binding.

For those who still aren't aware about it, 2-way data binding means when you change anything in your model, view gets updated and on changing anything in the view, model gets updated.

Everyone who knows Angular(having worked on it) or in fact has worked upon any other JavaScript framework(missed working on it) would actually know the beauty of this feature.

Well, now let's try to simply implement this feature in pur own plain vanilla JavaScript.

Let us take 4 text boxes to easily demonstrate 2-way data binding. Here is our small piece of HTML code:

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>2 Way Data Binding</title>
</head>
<body>
Name: <input class="name" type="text">
<input class="name" type="text">
<hr />
Age: <input class="age" type="text">
<input class="age" type="text">
<script src="2WayDataBinding.js"></script>
</body>
</html>
Now, let's have a look at our magical JavaScript code which will do wonders for us:

var $scope = {};
(function () {
    var bindClasses = ["name", "age"];
    var attachEvent = function (classNames) {
        classNames.forEach(function (className) {
            var elements = document.getElementsByClassName(className);
            for (var index in elements) {
                elements[index].onkeyup = function () {
                    for (var index in elements) {
                        elements[index].value = this.value;
                    }
                }
            }
            Object.defineProperty($scope, className, {
                set: function (newValue) {
                    for (var index in elements) {
                        elements[index].value = newValue;
                    }
                }
            });
        });
    };
    attachEvent(bindClasses);
})();
Output:


<html>

<head lang="en">

   

    <title>2 Way Data Binding</title>

</head>

<body>

Name: <input class="name" type="text" />

<input class="name" type="text" />

<hr />

Age: <input class="age" type="text" />

<input class="age" type="text" />

<script>
var $scope = {};

(function () {

    var bindClasses = ["name", "age"];

    var attachEvent = function (classNames) {

        classNames.forEach(function (className) {

            var elements = document.getElementsByClassName(className);

            for (var index in elements) {

                elements[index].onkeyup = function () {

                    for (var index in elements) {

                        elements[index].value = this.value;

                    }

                }

            }

            Object.defineProperty($scope, className, {

                set: function (newValue) {

                    for (var index in elements) {

                        elements[index].value = newValue;

                    }

                }

            });

        });

    };

    attachEvent(bindClasses);

})();
</script>

</body>

</html>



 Here is a detailed explanation of the above snippet:

We have taken the classes of the elements on which we need to apply 2-way Data Binding in an array named bindClasses.

Then we have an attachEvent which basically iterates through the classes passed in array bindClasses.

We are extracting all the elements by using their class names document.getElementsByClassName(className).

Once the elements are extracted we are binding onkeyup event on it. When this event is triggered it calls a function which stores the current value inside the element.

In this way we are successfully able to implement 2-way Data Binding on our HTML.

But how to update our model??

Here is the explanation of the rest of the part of the code which actually updates the value in our model:

We have used object.defineProperty to define a property of an object. Here our object is $scope and property is className.

Then we have a set function which serves as setter of the property.

So, if you do something like - $scope.name="Hari", "Hari" would be passed as newValue, which would ultimately replace the value being displayed on the view through the following piece of code elements[index].value = newValue.

Hurray!! We have now implemented the 2-way Data Binding successfully.

| Please note that this is just a small piece of code demonstrating 2-way Data Binding using JavaScript this code can be improved a lot on the basis of element type.e We can also have a getter function for getting the value in $scope.name. But for the sake of simplicity I have deliberately avoided it.


Ref: https://namitamalik.github.io/2-way-data-binding-in-Plain-Vanilla-JavaScript/

Friday 17 August 2018

input type number restrict negative values entering

input type number restrict negative values entering




<input type="number" min=0 oninput="validity.valid || (value='');" required>

Thursday 16 August 2018

Find duplicate values in a array



Solution1: 

function find_duplicate_in_array(arra1) {
        var object = {};
        var result = [];

        arra1.forEach(function (item) {
          if(!object[item])
              object[item] = 0;
            object[item] += 1;
        })

        for (var prop in object) {
           if(object[prop] >= 2) {
               result.push(prop);
           }
        }

        return result;

    }

    console.log(find_duplicate_in_array([1, 2, 2, -2, 4, 5, 4, 7, 8, 7, 7, 71, 3, 6]));

Output: ["2","4","7"]

Solution2:

function likeRepeat(array) {
     const arrayDuplicated = [];
     let element;
     let times = 0;

     for(let i = 0 ; i < array.length ; i++) {
         for(let j = 0 ; j < array.length ; j++) {
             if(array[i] === array[j]) {
                 times++;
                 element = array[i];
             }
             if(times == 2) {
                arrayDuplicated.push(element);
             }
          }
          times = 0;
      }
   
      console.log([...new Set(arrayDuplicated)]);
}

const array = ["dos", "dos", 5, 2, true, true, false, false, 7, 8, "quirim", 10, "aquaman", "aquaman"];

likeRepeat(array);

Output: ["dos",true,false,"aquaman"]



["2","4"["2","4","7"],"7"]

Monday 13 August 2018

Convert currency to words


example: getTotalInWords(5123)


outPut: five thousand one hundred and twenty-three

getTotalInWords(number) {
    const first = ['', 'one ', 'two ', 'three ','four ', 'five ','six ','seven ','eight ','nine ','ten ','eleven ','twelve ',
      'thirteen ','fourteen ','fifteen ','sixteen ','seventeen ','eighteen ','nineteen '];
    const tens = ['', '', 'twenty','thirty','forty','fifty', 'sixty','seventy','eighty','ninety'];
    const mad = ['', 'thousand', 'million', 'billion', 'trillion'];
    let word = '';
 
    for (let i = 0; i < mad.length; i++) {
      let tempNumber = number%(100*Math.pow(1000,i));
      if (Math.floor(tempNumber/Math.pow(1000,i)) !== 0) {
        if (Math.floor(tempNumber/Math.pow(1000,i)) < 20) {
          word = first[Math.floor(tempNumber/Math.pow(1000,i))] + mad[i] + ' ' + word;
        } else {
          word = tens[Math.floor(tempNumber/(10*Math.pow(1000,i)))] + '-' + first[Math.floor(tempNumber/Math.pow(1000,i))%10] + mad[i] + ' ' + word;
        }
      }
 
      tempNumber = number%(Math.pow(1000,i+1));
      if (Math.floor(tempNumber/(100*Math.pow(1000,i))) !== 0) {
        word = first[Math.floor(tempNumber/(100*Math.pow(1000,i)))] + 'hunderd ' + word;
      }
    }
    return word;
  }