Materializecss Parallax mousewheel jitters fix

Materializecss Parallax mousewheel jitters fix

I noticed the materializecss parallax plugin was a bit jittery in chrome when using the mousewheel to scroll. I fixed the problem by adding a window mousewheel callback that aborts the default mousewheel scroll then sets the scroll amount consistently. Hope this helps someone.


$( window ).bind('mousewheel', function( ev ){
    var $window = $(window),
        scrollIncrement = ev.originalEvent.deltaY/5,
        scrollPos = $window.scrollTop(),
        newPos = scrollPos+scrollIncrement;
    $window.scrollTop( newPos );          
} );
Posted in Javascript | Leave a comment

Javascript Flatten an n-dimension array iteratively and recursivley

Just in case you need to know how to flatten a multi dimensional array.

Recursively, although a tad more elegant this could blow your stack up if data.length === huge.  ES6 fixes the recursion problem.

var data = [ 1, [ 2, 3 ], [4, [ 5, [ 6, 7 ], 8 ], 9] ];
function flatten( flattenMe ) {    
    var answer = [];
    function doWork( flattenMe ) {
        for( var i =0, l = flattenMe.length; i<l; i++ ) {
            var element = flattenMe[ i ]; 
            if( typeof element  === "object" && element instanceof Array ) {
               doWork( element );
            else {
                answer.push( element );
    doWork( flattenMe );
    return answer;
//Iterativley do the same thing
function flati( data ){
    var flat = [];
    while( data.length ) {
        var currentEl = data.shift();
        if( Array.isArray( currentEl ) ){
            data = currentEl.concat(data)
            flat.push( currentEl )
    return flat;
Posted in Uncategorized | Leave a comment

Install Laravel Spark on workspace

Hope this helps someone. After two days of toil I finally got a spark project up on a workspace here are the steps I took. This assumes you have already bought a Spark license at

  1. Create the c9 workspace.
  2. Because I ultimately want to deploy to a digital ocean droplet and the latest laravel / spark requires PHP >5.6 you need to update php on your c9 workspace. I found using php brew works the best:  ( )  You can use phpbrew on Cloud9. I found that the standard installation process works fine, just run the commands below. We first install the libmcrypt-dev package to avoid running into dependency issues during the build: 
    $ sudo apt-get update
    $ sudo apt-get install libmcrypt-dev

    Next, we download phpbrew and move it to /usr/local/bin:

    $ curl -L -O
    $ chmod +x phpbrew
    $ sudo mv phpbrew /usr/local/bin/
    $ phpbrew init
    # add this to your ~/.bashrc:
    $ [[ -e ~/.phpbrew/bashrc ]] && source ~/.phpbrew/bashrc
    $ phpbrew lookup-prefix ubuntu

    Once set up, we install and load PHP 7:

    $ phpbrew install 7.0 +default
    $ phpbrew switch php-7.0.1
    $ phpbrew use php-7.0.1
    $ php -v
    PHP 7.0.1 (cli) (built: Dec 29 2015 22:04:43) ( NTS )
    Copyright (c) 1997-2015 The PHP Group
    Zend Engine v3.0.0, Copyright (c) 1998-2015 Zend Technologies
  3. Next make a phpinfo.php file in your workspace root if you fire up your workspace you will notice that apache still think php is 5.5. You need to disable the old php module and enable the new php 7.0 module . From Roland on   I had the same problem. You have to disable the php5 module in apache2 and then enable the php7 module:
    $ sudo a2dismod php5
    $ sudo a2enmod php7.0

    When I did this I got an error ‘could not parse envvars’ but I solved this by temporarily renaming this file in the /etc/apache2 directory. Then restart apache.

    If you do not see php7.0 module then do the following:

    $ sudo add-apt-repository ppa:ondrej/php -y
    $ sudo apt-get update -y
    $ sudo apt-get install php7.0-curl php7.0-dev php7.0-gd php7.0-intl php7.0-mcrypt php7.0-json php7.0-mysql php7.0-opcache php7.0-bcmath php7.0-mbstring php7.0-soap php7.0-xml
    $ sudo apt-get install libapache2-mod-php7.0 -y
  4.  If you going to use Spark then you also need PHP Zip so install
    $ sudo apt-get install php7.0-zip
  5. Clone the Laravel Spark Installer into your workspace root
  6. Add Spark to your workspace path.
    $ vim ~/.bashrc

    Add these lines at the end of your file

    # Laravel Installer
    export PATH="$PATH:$HOME/.composer/vendor/bin"
    # Spark Installer
    export PATH="$PATH:$HOME/workspace/spark-installer"
  7. Now you are ready to install Spark. Got into your spark-installer directory and run composer install. That should install spark and all its dependencies.
    composer install
  8. Register Spark, got to and login. In your user settings go to the API page and create a new API token.
  9. From here you can follow the install instructions in Spark’s documentation
  10. Remember you have to create your database and database user and set them in your project .env before you can run php artisan migrate.
  11. The only other problem I had was that the npm intall for my spark project was failing. So to fix it I upgraded nodejs to v 6.4. You can do this by running
    $ nvm install 6.4
    $ nvm use 6.4

    Then run your npm install

    $ npm install --save
Posted in Uncategorized | Leave a comment

Check if images exist before rendering with Javascript and jQuery

Recently I ran into a problem while making an events widget. Problem was, after making a bunch of Facebook Graph API requests for Facebook events some returned event objects had image urls that didn’t resolve. My fix was to check each image url, see if it resolves, if it doesn’t replace it with a default image. Last, after all images have been checked render the events mark up that is built with the Events data.

Because I wanted to check and replace all the image URLs before rendering the events markup, I had to set up some sort of asynchronous system to check all the images url resolution. In a nut shell the algorithm goes

  1. Gather all Image urls and make requests for them.
  2. When all Image requests return check which result in 404s
  3. Replace 404 images with default images
  4. Generate events mark up and add it to the page.

jQuery Deferreds to the rescue.

Considering I have a bunch of Facebook events json in eventsData.

Make a load image function

//Make a deferred array to store a jQuery deferred for every image request.
var deferreds = [];
//make a load image function that takes the event index and event image url
var loadImage = function( i, src ){
                    imgDeff = new $.Deferred();	 
		    deferreds.push( imgDeff);
		    //make an image and set up load callbacks 
		    var img = new Image();
		    img.onload = function() { 
			            console.log("I exist")
				    deferreds[i].resolve( i,src,"exsist" )
		    img.onerror = function() { 
				    console.log("I don't exist)
                                    //image doesn't exist so replace it with a default image in this case the FB user image[i] = "//"[i]"picture";
				    deferreds[i].resolve( i,src,"noexsist" );
		    //apply img
                    img.src = src;
    }//end loadImage
//loop through the events Data
var i = 0;
    loadImage( i, );
//when all the deferreds are resolved add the markup to the page
$.when.apply($,deferreds).done( function(data){ 
    //at this point eventsData has urls that will all resolve so build the markup and render
Posted in Uncategorized | Leave a comment

Template Tag Polyfill for Internet Explorer

Have you used the HTML5 template tag? I have too. Seems like a really great idea. Then QA tests your project and you realize it won’t work in IE. Better yet, not just IE 7 or 8, all versions of IE. Super bummer.

It turns out that IE will allow you to select a template tags but it doesn’t provide a .content property for them. Something like $(‘template’)[0].content fails in IE. This turns out to be a real kick in the junk, so I came up with this polyfill. The idea is that you add a method to the documents Element.prototype that checks for the existence of the .content property, in the event it’s not there override it. All subsequent template tag calls will have .content in IE

Feel free to use, modify, update, or let me know where I’m intellectually lacking:

  Element.prototype.contentTest = function(){ 
      return function( element ){ 
             return element.content;
         var elPlate = element,
             qContent = elPlate.childNodes;           
             docContent = document.createDocumentFragment();
             while(qContent[0]) {
             elPlate.content = docContent;
             return  docContent; 
  //get the templates contents
  var template = $('template')[0],
      templateContents = template.contentTest();
  //all subsequent calls to .content or .contentTest() will return the templates contents
Posted in Uncategorized | Comments Off on Template Tag Polyfill for Internet Explorer

Print only lightbox or modal window content

This was a real kick in the Jimmy.

On a recent project I had a requirement to print contents of a modal window. Solution:

  1. When the user clicks a print button add an iframe to the end of the body tag.
  2. Hide it by moving it off the view port.
  3. Get the modal contents and load them into the iframe.
  4. Finally tell the browser to print the iframe.

Easier said than done. Here is my final code hope this helps someone else not lose an entire Sunday. I started working from this code so props to the Ben for writing and posting it. Note if you want to use this you will have change some of the jQuery selectors to suite your project.

/* @brief Prints modal contents
 * @author
"printModal": function(){
    //make a iframe and hide it
    var tempFrame = $("<iframe id="printFrame" name="printFrame" width="300" height="150">")
    tempFrame.css( {
        "width": "1px",
	"height": "1px",
	"position": "absolute",
	"left": "-100000px"	
    } );
    //attach the iframe to the end of the body so we can hide the body content for IE. I hate IE
    $body = $("body");
    var ieStyle = $("<style class="ie"> body *{ display: none; } body #printFrame{ display: block !important; } </style>");
    //get the print styles, these are my custom print styles you could use a string here I chose to put them in a template file
    var printStyle = new  EJS({url: 'templates/mealModalPrintStyles.ejs'}).render({});
   //get the modal window content
    var $content = this.element.find(".buildAMeal__meal-info").clone();
    $content.find(".buildAMeal__modal-ingredient-edit-button, .btn-group").remove();
<h1>YOUR MEAL" );
   printDocument.write( "<html>" );
   printDocument.write( "<body>" );
   printDocument.write( "<head>" );
   printDocument.write( "<title>" );
   printDocument.write( document.title );
   printDocument.write( "</title>" );
   printDocument.write( printStyle );
   printDocument.write( "</head>" );
   printDocument.write( $content.html() );
   printDocument.write( "</body>" );
   printDocument.write( "</html>" );
   //focus the iframe and print it 
   //cleanup print style and print iframe 
   setTimeout( function(){ tempFrame.remove(); },(60 * 1000));
}// end printModal
Posted in Javascript, Uncategorized | Leave a comment

Facebook profiles vs. pages and graph api data retrieval

Help! My Facebook plugin doesn’t retrieve any data!

The problem may be you are trying to retrieve data from a Facebook profile rather than a Facebook page. Facebook puts much tighter restrictions on data its Graph API makes available to public profiles than it does for pages.

The reason you are not retrieving any data is because profiles limit data sharing to other profiles who are ‘friends’. Profile posts and photos have permissions that govern who can access them. This means the data on profiles is not necessarily available for public consumption. Meaning, when you post on your profile wall your friends can all see your post if they are logged into Facebook, but the rest of the Internet can not. Consider a website that the whole world can see, it doesn’t have permission to retrieve and display private posts that have been made between you and your friends on each others walls. There are exceptions to this rule. If you and your friends change a posts permissions to remove these restrictions, plugins and apps can use Facebooks Graph API to retrieve them.

But wait that’s not all!  Even with permissions set, outside sources still may not be able to retrieve posts. Consider an example post where multiple friends are mentioned or a photo where multiple friends are tagged. Just because the profile owner says it’s ok for the world to see does not necessarily mean all the other friends agree. If they have not also lifted the restriction by changing the post permissions Facebook will not all the data to be returned via the API.

To increase the data you can retrieve from your Facebook profile, you have a couple of options.

1) Change the permissions on each posts and photos you want to retrieve with your plugin. Follow these instructions for posts: and follow these instruction for photos

2) This is what I recommend. Change your Facebook profile to a Facebook page. Facebook pages are meant to be public facing so the whole world can see them. This means all the data is retrievable by the plugins and apps by default. To make this switch follow these instructions

Posted in jQueryFacebookWall, Uncategorized | Leave a comment

Javascript return focus to parent tab

This one took me a bit. I was creating a new tab on form submission. If a user clicks a button on the new tab, focus had to be shifted back to the parent tab. If the form was submitted again the child tab is deleted and replaced by a new child tab. Makes for a handy query and review results then modify query scenario but in separate tabs. The trick was in returning focus to the parent. One would think this would be possible with window.opener.focus(). But modern browsers don’t allow this because you can manipulate the users tabs. The work around is to name the parent window then use'','parent')

it to reset the tab focus.

Tested in chrome, but this trick doesn’t work in FF or IE. Hope this helps someone else.




// <![CDATA[
var i = 0;
var windows = []; = 'parent';
//handle child birth		  
function announceWindow(win){
   //if there is already a window open, close it and save ref to new one
       delete windows[0];
       i = 0;	
   //store a reference to the window
   windows[i] = win;
// ]]>

child tab
//markup for button that takes you pack to parent

<input type="button" />


// <![CDATA[
      //tell that parent that the child is born! so it can keep track of them and get rid of them as needed.
      if (window.opener) {
      	window.opener.announceWindow( window );
      //set the focus back to the parent window
      function focusParentWindow(){'','parent').focus();
// ]]>
Posted in Uncategorized | Leave a comment

JavaScript Reg-ex for sub-domain name

This one took me a bit so thought it might be worth writing it down.

If you need to validate a field for a valid subdomain name, ie the “” you have a couple of requirments:

1) Field value starts with an letter or number

2) Field value ends with a letter or number

3) All characters between first and last can be a letter, number, or a non-repeating – or .

so lorenzo.gangi-test would be valid.

lorenzo.-gangi..test1 is invalid

This regex should do the trick

<p id="demo">Click the button to display the matches.</p>
<button onclick="myFunction()">Try it</button>
<script type="text/javascript">
function myFunction()
var str = "b.o.b-obo123"; 
var temp = new RegExp(/^([a-zA-Z0-9](\w|[.-](?=\w))+[a-zA-Z0-9])$/)
var n=str.match(temp);
Posted in Javascript | Comments Off on JavaScript Reg-ex for sub-domain name

Sorry to all the fans

Ladies and gentleman all my blog posts have left the building. I used to use this thing as a way to remeber all the development stuff I couldnt remeber. I ditching that idea. Instead of  all the old unix commands, IDE snafus fixes, and complicated quries, I hope to post a bunch of how too’s. We’ll see how this goes.

Posted in jQueryFacebookWall, Uncategorized | Comments Off on Sorry to all the fans