BCDash Reference Tool

git repo @ https://github.com/lelanavilla/bcdash

Code Snippets

Find Page Count [lang]

                    function pageCount(n, p){
                        if (p % 2 === 1) {
                            let total = Math.ceil(p / 2);
                            return Math.floor(total);

                        } else if ((n -1) === p) {
                            let total = 0;
                            return Math.floor(total);
                    
                        }
                        
                        else {
                            let total = p / 2;
                            return Math.floor(total)
                            
                    
                        }
                    }
                    pageCount(200,32);//
                                                  
Remove Dups from Array [JS]

console.log([...new Set(arr)]);
        -or-                                                                                                    
console.log(Array.from(new Set(arr)));
Convert Arguements into Arrays [JS]

 var args = Array.prototype.slice.call(arguements);
                                                                                            
Random Password Generator [JS]

    function randomPassword(str){
      var charSet = "abcdefghijklmnopqrstuvwxyz1234567890";
    for ( var i =0; i < charSet.length; i++){
      var random = Math.random().toString(36).slice(2);
    }
        return random
    }
    
    **USES BASE 36 STRING
                                                                                            
Factorlize a number [JS]
          
    function factorialize(num) { 
     var total = 1;{
    for (var  i= 1; i <= num; i++){
        total *= i; 
    }
    }
      return total;
    }
    
    factorialize(5);
                                                                                              
Reverse a string [JS]

     function reverseString(str) {
      var answer = str.split('').reverse().join('');
        return answer;
     }
                                            
    *SEXY WAY: 
    return str.split('').reverse().join ('');
                                                                                                
                                                                                                
                                                                                              
Check for palindromes [JS]

                                                                                             
        function palindrome(str) {
         str= str.toLowerCase();
        var symbols= /\W+|_/g;
         str = str.replace(symbols,"");
        var newString = str.split("")
        .reverse().join("");
          if ( newString === str){
            return true;
         } else{
            return false;
        }
        }
                                                                                           
Find the longest word in a string [JS]

                                                                                        
                                            
         function findLongestWord(str) {
            var splitString = str.split(" ");
            var biggestWord = 0;
         for(var i =0; i < splitString.length; i++){
            if (biggestWord < splitString[i].length){
        biggestWord = splitString[i].length;
        }
        }
        return biggestWord;
        }
                                             
                                                                                        
Title case a sentence [JS]

                                                                                              
 function titleCase(str){
    var words = str.toLowerCase().split(" ");
for ( var i= 0; i< words.length;i++){
    var letters = words[i].split("");{
letters[0] = letters[0].toUpperCase();
 words[i]= letters.join("");
}
}
     return words.join(" ");
}
                                              
                                              
                                             
                                                                                              
Find the largest numbers in an array [JS]

                        function largestOfFour(arr){ 
                        var results = [];
                        for(var n in arr){
                        var largestNumber = 0;
                        for(var sb in arr[n]){
                          if(arr[n][sb] > largestNumber){
                        largestNumber = arr[n][sb];
                        }
                        }    
                           results[n]= largestNumber;
                        }
                           return results;
                        }
                                                                                              
                                                                                              
Validate an IP Address [JS/REGEX]

        const validateIp =
        (ipAddress) => /^(?!0)(?!.*\.$)((1?\d?\d|25[0-5]|2[0-4]\d)(\.|$)){4}$/.test(ipAddress);  
        EXPLAINED:
        ^ start of string
  (?!0)         Assume IP cannot start with 0
  (?!.*\.$)     Make sure string does not end with a dot
  (
    (
    1?\d?\d|   A single digit, two digits, or 100-199
    25[0-5]|   The numbers 250-255
    2[0-4]\d   The numbers 200-249
    )
  \.|$ the number must be followed by either a dot or end-of-string - to match the last number
  ){4}         Expect exactly four of these
$ end of string
                                                                                            
                                                                                              
Confirm an ending [JS]

                     function confirmEnding(str, target) {
                        return str.substr(-target.length)===target;
                     }
                        confirmEnding("Bastian", "n");
                                                                                              
Trunacate a string [JS]

                                                                                              
                     function truncateString(str, num) {
                      if( str.length > num && num > 3){
                        return str.slice(0, (num - 3)) + '...';
                    }else if ( str.length > num && num < 3){
                        return str.slice(0,num) +'...';
                    }else{
                        return str;
                    }
                    }
                                              
                                                                                              
Repeat a String X number of times [JS]

                    function repeatStringNumTimes(str, num) {
                        if ( num <0){
                            str="";
                        return str;
                     } else {
                    var strTimes = str.repeat(num);
                        return strTimes;
                     }
                     }
                     repeatStringNumTimes("abc", 3);
                                                                                              
How many [JS]

                         function slasher(arr, howMany) {
                            var newArray =arr.splice(howMany);
                            return newArray;
                         }
                                                                                      
                                                                                              
Is it a boolean [JS]

                         function bouncer(arr) {
                         return arr.filter(Boolean);
                        }                                  
                                                                                              
Sort array smallest to largest [JS]

                                                                                              
                            function getIndexToIns(arr, num) {
                             arr.push(num);
                                arr.sort(function(a,b) {
                                return a-b;
                             });
                                return arr.indexOf(num);
                             }
                                                                                              
Caesars Cipher [JS]

                         function rot13(str) { //SERR PBQR PNZC
                            var rotCharArray = [];
                            var regEx = /[A-Z]/ ;
                            str = str.split("");
                         for (var x in str) {
                            if (regEx.test(str[x])) {
                         rotCharArray.push((str[x]
                         .charCodeAt() - 65 + 13) % 26 + 65);
                         } else {
                         rotCharArray.push(str[x].charCodeAt());
                        }
                        }
                        str = String.fromCharCode.apply(String, rotCharArray);
                            return str;
                        }
                                                                                 
Add two numbers [JS]

                    var sum = 10 + 10;
                                                                                              
Increment a number [JS]

                    var myVar = 87; 
                    myVar++;
                                                                                              
Access Multidimensional arrays with index [JS]

                    // Setup
                    var myArray = [[1,2,3], [4,5,6], [7,8,9],[[10,11,12], 13, 14]];
                     var myData = myArray[2][1]
                                                                                              
Modify an array with index [JS]

var ourArray = [1,2,3];
ourArray[1] = 3; // ourArray now equals [1,3,3].
                                                                                      
Random integer between two numbers [JS]

function randomIntFromInterval(min,max){
return Math.floor(Math.random()*(max-min+1)+min);
}
                                                        
Add your site to users bookmarks [JS]

function bookmark(address, sitename){
    if(sidebar){
     .sidebar.addPanel(sitename,address, '');
 } else if (document.all){
    .external.AddFavorite(address,sitename);
 } else if(.opera && .print){
     return true;
}
}
                                                  
Sort array of numbers to find where in the array an arg goes. [JS]

    function getIndexTo(arr, num) {
      arr.sort(function(a,b){
        return a-b ;
    });
    for (var a = 0; a < arr.length; a++){
     if (arr[a] > num){
        return a;
     }
        return arr.length
     }
    }
                                                  
Remove Duplicate letters from string [JS]

            var removeDuplicates(str){
            var output = {
                noDupes:"",
                extras:""
                }
               var output :{
            for(var i = 0; i < str.length; i++){
             if(str.indexOf(str[i] === i)){
                output,noDupes += str[i];
            }else{
                 output.extras += str[i];
            }                                                  
            }
                 return output;
            }
            }
        
            SEXY WAY:
            let arr_without_duplicates
            = Array.from(new Set(arr));
                                                  
Get URL parameter [JS]

var getURLParameter = function(name) {
return decodeURIComponent((new RegExp('[?|&] ' + name + '=' + ' ([^&;]+?)
(&|#|;|$) ').exec(location.search)||[,""])[1]
.replace(/\+/g, '%20 '))||null;};
var urlVar = getURLParameter("varname");
                                                
Load DOM without Script [JS]

js.http.get(files[0],loader.js, {}, function(data){
 eval(data);
 if(files.length >1){
load(files.slice(1));
}
});
        
        
Gradients [CSS]

 /*linear*/
background: linear-gradient(red, blue);
background: linear-gradient(90deg, red, blue);
background: linear-gradient(90deg, red 0%, blue 50%, yellow 100%);
 /*radial*/
background: radial-gradient(red, blue);
background: radial-gradient(circle closest-side, red, blue);
background: radial-gradient(ellipse at top right, red 0%, blue 50%, yellow 100%);
/*repeating*/
background: repeating-linear-gradient(45deg, red, red 10px, blue 10px, blue 20px);
background: repeating-radial-gradient(circle at 0 0, red, blue 50px);
                                                    
Get video to fill screen at all screen sizes [CSS]

         .video{
         position:relative;
         padding-bottom:56.25%;
         height:0;
         overflow:hidden;
         }
         .videoFrame,
         .videoObj,
         .videoEmbed{
         position:absolute;
         top:0;
         left:0;
         width:100%;
         height:100%
         }
                                              
Perfect Full Size Responsive Background Image [CSS]

html { 
  background: url(images/bg.jpg) no-repeat center center fixed; 
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
}
                                          
Sticky Footer [CSS]

     html{
     height:100%;
    }
     body{
     min-height:100%;
     position:relative;
     padding-bottom:[footer - height];
            }
    .footer{
    position:absolute;
    left:0;
    right:0;
    bottom:0;
    height:[footer-height];
    }
                                              
Make image auto resize to max width of the boundary [CSS]

        img{
         max-width:100%;
         height:auto;
        }
    **FOR RELATIVE MARGINS USE EMS OR % NOT PIXELS
    **FOR RELATIVE PADDING USE %
    **FOR RELATIVE FONT SIZE USE vw( 1vw = 1% viewport width;
    ex: 50cm width = .5cm so .5 is 1vw )
                                                  
Microformat hCard [HTML]

<div id="hcard-Firstname-Lastname" class="vcard">
<a class="url fn n" href="http://website.net">
<span class="given-name">Firstname</span>
<span class="additional-name">Middlename</span>
<span class="family-name">Lastname</span>
</a>
<div class="org">Company</div>
<a class="email" href="mailto:whoever@gmail.com">firstname@website.net</a>
<div class="adr">
<div class="street-address">123 Streetname</div>
<span class="locality">Cityname</span>, <span class="region">Region </span> <span class="postal-code">12345</span>
<span class="country-name">Countryname</span>
</div>
<div class="tel">555-555-5555</div>
</div>
                                                    
Table markup [HTML]

    <table>
    <thead>
         <tr>
     <th></th>
    <th></th>
       </tr>
    </thead>
     <tbody>
     <tr>
     <td></td>
     <td></td>
        </tr>
        <tr>
    <td></td>
    <td></td>
        </tr>
    </tbody>
    </table>
                                                        
Video click to play/pause [jQuery]

$('video ').on('click ', function(){
if(!$(this)[0].paused)
$(this)[0].pause();
$(this).attr('controls ', false);
 }else{
  $(this)[0].play();
  $(this).attr('controls ', true);
  }
});
                                                    
Calculate Distance Between Mouse and Element [JQUERY]

    (function() {
        var mX, mY, distance,
    $distance = $('#distance span'),
    $element  = $('#element');
                                                        
    function calculateDistance(elem, mouseX, mouseY) {
     return Math.floor(Math.sqrt(Math.pow(mouseX - (elem.offset().left+(elem.width()/2)), 2) + Math.pow(mouseY - (elem.offset().top+(elem.height()/2)), 2)));
     }
                                                        
    $(document).mousemove(function(e) {  
        mX = e.pageX;
        mY = e.pageY;
    distance = calculateDistance($element, mX, mY);
    $distance.text(distance);         
    });
                                                        
    })();
                                              
Ajax loading json [jquery]

    var myData = {};
    $.ajax({
     'async ': false,
       'url ': 'data/data.json ',
       'dataType ': 'json ',
       'success ': function(data) {
    myData = data;
    },
     'error ': function() {
     console.log('ERROR: could not load data json ');
      }
      });        
                                                    
Get JSON from API with jQuery [jQUERY]

        $(document).ready(function() {
        $("#getMessage").on("click", function(){
        $.getJSON("http://forAPI.com/queryParams", 
        function(json) {
        $(".message").html(JSON.stringify(json));
        });
                                                
                                          
Convert JSON to html [jQUERY]

        var html = "";.
        json.forEach(function(val) {
        var keys = Object.keys(val);
        html += "
"; keys.forEach(function(key) { html += "" + key + ": " + val[key] + "
"; }); html += "

"; });
Render Images from Data Sources with jQuery [jQUERY]

 $(document).ready(function() {
$("#getMessage").on("click", function() {
$.getJSON("/json/whatever.json", function(json) {
var html = "";
 json.forEach(function(val) {
 html += "
"; html += "" + val.altText + ";" html += "
"; });      $(".message").html(html); }); }); });
Prefilter Json with jQuery [jQUERY]

  json = json.filter(function(vsl){
  return (val.id !==1);
 });
                                                  
                                          
Get Geolocation with jQuery [jQUERY]

                                               
 if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position){
$("#data").html("latitude: " + position.coords.latitude + "

longitude: " + position.coords.longitude); }) }
Trigger Click Events with jQuery [jQUERY]

        $(document).ready(function)
        $("#getMessage").on("click", function(){
         });
        });
                                          
Change Html Text with jQuery [jQUERY]

     $(document).ready(function() {
     $("#getMessage").on("click", function(){
     $(".message").html("Here is the message");
     });
     });
                                          
Scrollbars customizer [SCSS]

    ::-webkit-scrollbar-button{
    display: none;
    }
    ::-webkit-scrollbar {
    width:  2px;
    height: 2px;
    }
    ::-webkit-scrollbar-thumb {
     background: transparent;
    border: 1px solid rgba(220,220,220,1);
    cursor: pointer;
    }
    ::-webkit-scrollbar-track {
    background: transparent;
    width: 4px;
    border: 2px solid transparent;
    }
    ::-webkit-scrollbar-track-piece {
    background: transparent;
    width: 4px;
    border: 2px solid transparent;
    }
    body {
    scrollbar-face-color: white;
    scrollbar-track-color: transparent;
    }
                                                        
Scrollbars customizer 2 [SCSS]

            @mixin scrollbars($size, $foreground-color, $background-color) {
            ::-webkit-scrollbar-button{
            display: none;
             }
            ::-webkit-scrollbar {
            width:  $size;
            height: $size;
            }
            ::-webkit-scrollbar-thumb {
            background: $foreground-color;
            border: 1px solid lighten($foreground-color, 10%);
            cursor: pointer;
             }
            ::-webkit-scrollbar-track {
             background: $background-color;
            width: calc(#{$size} * 2);
            border: 2px solid lighten($background-color, 10%);
            }
            ::-webkit-scrollbar-track-piece {
            background: $background-color;
            width: calc(#{$size} / 2);
            border: 2px solid lighten($background-color, 10%);
            }
             body {
            scrollbar-face-color: $foreground-color;
            scrollbar-track-color: $background-color;
            }
            }
                                                        
For loop generating css rules [SCSS]

                @for $i from 1 through 20 {
                $increment: 18;
              &:nth-child( #{$i} ) {
                $r: $i * $increment;
                  transform: rotate(#{$r}deg);
                 }
                 }
                                                                
Center horizontally [SCSS]

     @mixin hcenter(){
        position: absolute;
        left: 50%;
        transform: translatex(-50%);
    }
                                                        
Center vertically [SCSS]

     @mixin vcenter(){
        position: absolute;
        top: 50%;
        transform: translatey(-50%);
    }
                                                        
Center both horizontally and vertically [SCSS]

      @mixin hvcenter(){
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        }
                                                        

Code Tricks

Make Any Site Editable [CDT]


 Add "contenteditable" to any DIV                                             
 then in  console(chromeDevTools) enter :
document.body.contentEditable= true; 
  
[JS]



 

Site Search utilizes
JavaScript Kit