Tuesday 16 April 2019

Javascript search/filter list highlight



OutPut:










      Create a html file index.html

      <html>

      <head>

      <script src="https://rawgit.com/Microsoft/TypeScript/master/lib/typescriptServices.js"></script>
      <script src="https://rawgit.com/basarat/typescript-script/master/transpiler.js"></script>
      <script src="script.js"></script>

      </head>

      <body>

      <table>
      <tr>
      <td>
      <input type="text" value="" onblur="searchItem(this)">
      <ul id="demo"></ul>

      </td>
      <td>
      <ul id="list"></ul>
      </td>
      </tr>
      </table>


      <style>
      table td {
      vertical-align: top;
      }

      ul li {
      margin: 2px 0;
      list-style-type: decimal;
      }
      </style>

      </body>

      </html>



          Create a script.js file


          var getJSON = function (url) {
          return new Promise(function (resolve, reject) {
          var xhr = new XMLHttpRequest();
          xhr.open('get', url, true);
          xhr.responseType = 'json';
          xhr.onload = function () {
          var status = xhr.status;
          if (status == 200) {
          resolve(xhr.response);
          } else {
          reject(status);
          }
          };
          xhr.send();
          });
          };

          getJSON('https://raw.githubusercontent.com/Bowserinator/Periodic-Table-JSON/master/PeriodicTableJSON.json').then(function (data) {
          // result.innerText = data.elements; //display the result in an HTML element
          setTimeout(() => {
          console.log('hello');
          let list = document.getElementById('list');
          data.elements.forEach(elem => {
          var entry = document.createElement('li');
          entry.appendChild(document.createTextNode(elem.name));
          list.appendChild(entry);
          });
          }, 500);
          }, function (status) { //error detection....
          alert('Something went wrong.');
          });


          function searchItem(typed) {
          document.getElementById('demo').innerHTML = '';
          var items = document.getElementById("list").getElementsByTagName("li");
          for (i = 0; i < items.length; i++) {
          text = (items[i].innerHTML).toLowerCase();
          if (!typed.value || text.indexOf((typed.value).toLowerCase()) != -1) {
          items[i].style.border = '1px solid red';
          var entry = document.createElement('li');
          entry.appendChild(document.createTextNode(items[i].innerHTML));
          document.getElementById('demo').appendChild(entry);
          }
          }
          }

          Friday 15 February 2019

          Find All Combinations of array JavaScript

          function combinations(str) {
              var fn = function(active, rest, a) {
                  if (!active && !rest)
                      return;
                  if (!rest) {
                      a.push(active);
                  } else {
                      fn(active + rest[0], rest.slice(1), a);
                      fn(active, rest.slice(1), a);
                  }
                  return a;
              }
              return fn("", str, []);
          }
          var allArrays = [['a', 'b'], ['c'], ['d', 'e', 'f']]
          function allPossibleCases(arr) {
            if (arr.length == 1) {
              return arr[0];
            } else {
              var result = [];
              var allCasesOfRest = allPossibleCases(arr.slice(1));  // recur with the rest of array
              for (var i = 0; i < allCasesOfRest.length; i++) {
                for (var j = 0; j < arr[0].length; j++) {
                  result.push(arr[0][j] + allCasesOfRest[i]);
                }
              }
              return result;
            }
          }
          console.log( combinations("abcd") );
          console.log( allPossibleCases(allArrays) );

          O/P:
          [object Array]: ["abcd", "abc", "abd", "ab", "acd", "ac", "ad", "a", "bcd", "bc", "bd", "b", "cd", "c", "d"]
          [object Array]: ["acd", "bcd", "ace", "bce", "acf", "bcf"]

          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';
                }
              }
            }
          }