Sample Angular Website

Leave a comment Standard
AngularJS

So I’ve seen a lot of people using AngularJS but I see very few examples of a website made using it. That’s why I decided to post an example website to give you an idea of what a full website looks like using AngularJS. It has samples of some of the things you’ll commonly find in a website made entirely with Angular:

  •  Navigation & Routing
  • Providers & Directives
  • Controllers & Config Blocks
  • Data Calculations
  • Filtering

Sorry if you’re looking for Angular 2.0, this was made with Angular 1.5.8. View, fork and/or edit the files on Plunker!

HTML5 Tutorial: Simple Music Player

Leave a comment Standard
HTML5 Music Player

So this is a pretty simple example but I was playing around with flash for my chat room and this was byproduct of that experimentation. It’s funny how even when I’m trying to learn something new I do my best to make it useful for other situations which is a good habit to get into if you’re not doing it already.

Try out the working demo or download the code

Caveats

This will only work on a browser that is HTML5 compliant and has support for audio. That means older browsers and most versions of Internet Explorer are not supported. Firefox, Chrome and Opera work as well as the newest versions of Internet Explorer.

The Audio Tag

If you’re familiar with HTML then most of the index file below will look pretty familiar. The thing you really have to pay attention to is the new <audio> tag. It looks like this:

<audio id="rock" src="http://whiteoakstables.net/chat/audio/rock.wav" preload="auto"></audio>

You may notice that it looks a whole lot like a hyperlink with the src that defines the location of the file. Preload is an optional attribute, it tells your browser to start downloading the file as soon as the DOM, or page elements, have finished loading. In addition to setting preload to true I’ve added an ID attribute so I can reference this particular song in my music player.

The Index File

<!DOCTYPE html>
<html>
 <head>
 <script data-require="jquery@*" data-semver="2.1.3" src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
 <link data-require="bootstrap-glyphicons@*" data-semver="3.2.1" rel="stylesheet" href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/img/glyphicons-halflings.png" />
 <link data-require="bootstrap@*" data-semver="3.3.1" rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" />
 <script data-require="bootstrap@*" data-semver="3.3.1" src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>
 <link rel="stylesheet" href="style.css" />
 <script src="script.js"></script>
 </head>
 <body>
 <h1 class="text-center">Bootstrap HTML5 Music Player</h1>
 <audio id="rock" src="http://whiteoakstables.net/chat/audio/rock.wav" preload="auto"></audio>
 <audio id="blues" src="http://whiteoakstables.net/chat/audio/blues.wav" preload="auto"></audio>
 <audio id="electronica" src="http://whiteoakstables.net/chat/audio/electronica.wav" preload="auto"></audio>
 <audio id="classical" src="http://whiteoakstables.net/chat/audio/classical.wav" preload="auto"></audio>
 <audio id="latin" src="http://whiteoakstables.net/chat/audio/latin.wav" preload="auto"></audio>
 <audio id="indie" src="http://whiteoakstables.net/chat/audio/indie.wav" preload="auto"></audio>
 <div class="audiocontroller">
 <i class="audio-logo glyphicon glyphicon-headphones"></i>
 <i class="dynamiclink glyphicon glyphicon-play" id="play"></i></a>
 <i class="dynamiclink glyphicon glyphicon-pause" id="pause"></i>
 <select id="currentTrack">
 <option value="rock">Rock</option>
 <option value="blues">Blues</option>
 <option value="electronica">Electronica</option>
 <option value="classical">Classical</option>
 <option value="latin">Latin</option>
 <option value="indie">Indie</option>
 </select>
 <i class="dynamiclink glyphicon glyphicon-stop" id="stop"></i>
 </div>
 <p class="text-center">
 <a id="author" href="http://design1online.com" target="_blank">by Design1online.com, LLC</a>
 </p>
 </body>
</html>

The Javascript File

//Simple HTML5 Music Player by design1online.com, LLC

var currentTrack = null;
var paused = false;

$(document).ready(function() {
 currentTrack = $('#currentTrack').val();
 
 $("#play").click(function() { play(); });
 $("#stop").click(function() { stop(); });
 $("#pause").click(function() { pause(); });
});

function play() {

 //set the track back to the beginning
 if (!paused) {
 stop();
 currentTrack = $('#currentTrack').val();
 
 //make sure track starts from the begining each time
 document.getElementById(currentTrack).load();
 }

 //play the track
 document.getElementById(currentTrack).play();
}
 
//stop playing the current track
function stop() {
 if (currentTrack) {
 document.getElementById(currentTrack).pause();
 paused = false;
 }
}

//stop the track but don't go back to the beginning
function pause() {
 paused = true;
 document.getElementById(currentTrack).pause();
}

How It All Works

So now let’s talk about the javascript file. At first glance it looks relatively simple because it is! When you want to select a track you simply ask for it using getElementById and then you tell it to play or to pause. One thing that is sadly lacking is a stop() functionality. With html5 you can only pause an audio file — which does stop the playback but it also keeps the audio file at the same position as when you called pause on it. This means that if you wanted to play the audio file from the beginning again and you just called play() it would continue playing from where it left off. That’s where the load() function comes into play — this will tell the audio track to start loading if it wasn’t set to preload and it will reset the track back to the beginning.

The only other thing to mention is the currentTrack variable. I use this to keep track of which of the songs is currently selected and the user wasn’t to listen to.

Best Tools To Test Your Website’s Responsiveness

Comment 1 Standard
responsive websites

Since converting my game websites to be fully responsive and use HTML5 I’ve gone through a lot of different responsiveness testing tools. So far these are my favorites:

  1. Web Developer – addon for Firefox. This takes the cake for me because it’s already built into the right click menu on my browser so it’s really easy to invoke whenever and wherever. On top of that it’s designed to show you a number of different responsive views at one time and you can customize the views that it shows when it launches. Of course it comes with a whole host of other nifty tools to aid in your web development so it gets a raving 5 stars from me. It’s not as fully fleshed out in Chrome but there is a Chrome version as well. The only downside to this tool is that if you change something and you want to see an update of your changes you can’t just refresh the screen that pops up in a new tab. Instead you have to close the tab and launch the responsive view from the right click menu. Not a huge bother but it could be improved upon.
  2. http://quirktools.com/screenfly/ – simple, intuitive interface. Just enter your website and you’re well on your way for an easy experience to view your site on phones, tables and even televisions. The downside of this website is that you have to reload it every time you want to check what a different page of your website would look like.
  3. http://ipadpeek.com/ – the ipad and iphone emulator. It looks like an ipad and it does a pretty good job emulating an ipad and iphone — it will even show screen rotations. The only downside to this is that it doesn’t let you change version of the ipad because I believe the newest AIR 2 has a larger screen than the one in this emulator but I could be wrong.
  4. http://www.mobilephoneemulator.com/ – the multi-phone emulator. So this isn’t nearly as easy to use as the item in the number 2 spot which is why it’s bumped down a spot on my list even though it has a much wider array of phones you can test your site on including some of the popular android, htc and samsung phones. Just pick the make and model and enter your website and this site will render it to the proper screen size.
  5. http://ready.mobi/– last but not least. Although this doesn’t rank high in the visual department this is an excellent tool for evaluating what issues your markup may present to mobile users. Things like images exceeding certain file size and dimensions (which make for a slow mobile experience) and how your file sizes will impact your loading times are why this site makes my list. The downside is that it doesn’t visually show you what your responsive site will look like but it takes an analytical approach which is super helpful and informative regardless.

Now it looks like you’re ready to check out these 11 unconventional programming tips to improve your programming skills!

Angular UI Autocomplete Directive using Typeahead — NO JQUERY

Comments 10 Link

It always bugs me that everyone resorts to using jQuery to write their angular autocomplete directives so I’ve toyed around with it until coming up with a pure angular solution. Enjoy this Plunker!

PHP Tutorial: Dynamically Cache and Combine All CSS Files

Comments 10 Standard

Does your website use a lot of CSS files? If so did you know you can increase your website’s speed by caching and combining all of your CSS files into a single file?

Why Is It Useful?

Every time your browser loads a page on your website it has to make a request for all of the resources included or displayed on your page. Resources consist of things like image files, JS files, XML files and CSS files. If you find that you have more than one CSS file that you need to include on your website the requests required to load each of those files can sometimes take longer than a single request to load a single larger file. If you combine and cache your CSS files into a single file you can improve your website’s response time.

What’s a Cache?

A cache is a snapshot of a file at a moment in time. Typically you want to cache files that are static, meaning they don’t change often. If your file changes are fairly frequent then you end up generating a cache file too frequently for it to be of any use. That’s why this is a great technique to use with CSS files since they aren’t static but they don’t change that often either.

Setup

  1. Create two files, one called cache.css and another called cache.php.
  2. Place both of them in the same folder directory that you keep your style sheets in. We’ll use the CSS file to create a snapshot of all of our CSS files in our style sheet directory and we’ll use the PHP file to check generate and return the contents of our cache file.
  3. Change the permissions on the cache.php file to 0755. This will allow your PHP file to modify your cache.css file.
  4. Update the website page headers so instead of loading each of your individual .css files you’re now only loading your cache.php file

Before

<html>
     <head>
		<link href="stylesheets/filename1.css" rel="stylesheet" type="text/css" />
		<link href="stylesheets/filename2.css" rel="stylesheet" type="text/css" />
		<link href="stylesheets/filename3.css" rel="stylesheet" type="text/css" />
    </head>
    <body>
          This is what the header would look like before updating to the single file. Notice how you're making reference links to multiple .css files. Each of those requires your browser to make a request in order to load the three separate files.
    </body>
</html>

After

<html>
     <head>
		<link href="stylesheets/cache.php" rel="stylesheet" type="text/css" />
    </head>
    <body>
          This is what the header looks like. It now references our cache.php file which will give it the cached version of our CSS files.
    </body>
</html>

The Code

Inside of your cache.php file put the following code:

<?php 
/**
* File: cache.php
* Author: design1online.com, LLC
* Purpose: updates and loads the current css cache file
**/
$path = "path_to_your_public_directory/";
$dir = "name_of_your_css_folder_directory/";
$cachefilename = "cache.css";
$files_to_cache = array(
 	"filename1.css",	//add all of your css file names
 	"filename2.css", 	//that are inside your_css_folder_directory
 	"filename2.css"		//that you want to cache
);

//check for file changes
if ($handle = opendir($path . $dir)) {
 	while (false !== ($entry = readdir($handle))) 
        {
 		//if any of the $files_to_cache have changed recently we need to update the cache file
                //to do this we compare the last modified times on the files to see if one of our
                //$files_to_cache was updated more recently than our cache file
 		if (is_file($entry) && is_readable($entry) && substr($entry, -3, 3) == "css" &&
 		date(date(filemtime($entry)) > filemtime($path . $dir . $cachefilename)))
                {
                        //we've found a $file_to_cache that was updated more recently than the cache file
                        //so open the cache file and prepare to overwrite the contents with the changes
			$cachefile = fopen($path . $dir . $cachefilename, "w");

			//write all of the $files_to_cache to the cache file
			foreach ($files_to_cache as $filename)
			{
				$copyfile = fopen($path . $dir . $filename, "r");
				fwrite($cachefile, fread($copyfile, filesize($filename)));
				fclose($copyfile);		
			}

                        //close the connection to the cache file - this also updates the last modified time
                        //on the cache file so that it won't try to re-generate the cache file again until 
                        //a $files_to_cache has been changed again
			fclose($cachefile);

                        //since we found one file that was changed and we've updated the cache file 
                        //we no longer need to look for other files that may have potentially been updated, so 
                        //this will tell the loop to stop running
			break;
		}
        }
}

//output the contents of the cache file
//the header content type will make sure the
//browser interprets the file contents as text/css
header("Content-type: text/css");

//clear the buffers to prevent overflows
ob_clean();
flush();

//open and return the contents of the cachefile
//you'll notice your cache file contains all of your
//$files_to_cache merged into one
readfile($path . $dir . $cachefilename);

Last But Not Least

Update the $path, $dir and $cachefile name as needed at the top of your new cache.php file. This will tell the file where to find your css stylesheets and which ones you want to cache. Since this script looks at the last modified dates on our $files_to_cache we need to make sure and update one of the files in our $files_to_cache list in order for it to generate our initial cache.css file. To do this I would recommend making a change to one of your $files_to_cache or using touch to update the last modified time stamp on one of your $files_to_cache. Once you’ve done that you can view any page you updated to use cache.php as it’s stylesheet (see setup step 4) in any web browser to view the results of your efforts.

PHP Tutorial: Mixing HEX Colors within a Range

Leave a comment Standard
file0001025429630

This seems to be coming up more often with the client games I’ve been working on. Now everyone wants  dynamic images and colors. This function will produce a random hexcode color within the range of the two hexcode colors given. It’s inclusive so you can also get the original colors returned.

<?php
/**
* Purpose: produce a color within a range of two hexcode colors
* Precondition: two hexcode colors, min/max range values optional
* Postcondition: one random color within the range returned
**/
function mixRange($color1, $color2, $MIN = 1, $MAX = 10)
{
    $range = rand($MIN, $MAX);
 
    $r = hexdec(substr($color1,0,2));
    $g = hexdec(substr($color1,2,2));
    $b = hexdec(substr($color1,4,2));
     
    $gr = (hexdec(substr($color2,0,2))-$r)/$MAX; //Graduation Size Red
    $gg = (hexdec(substr($color2,2,2))-$g)/$MAX;
    $gb = (hexdec(substr($color2,4,2))-$b)/$MAX;
     
    return str_pad(dechex($r+($gr*$range)),2,'0',STR_PAD_LEFT) .
        str_pad(dechex($g+($gg*$range)),2,'0',STR_PAD_LEFT) .
        str_pad(dechex($b+($gb*$range)),2,'0',STR_PAD_LEFT);
}
?>

jQuery Tutorial: Scroll UI dialog boxes with the page as it scrolls

Comments 14 Standard
jquery dialog box

Do you have a jQuery UI modal dialog box that you want to scroll down as the page scrolls? I tried searching for someone who’d figured out a way to do it but I couldn’t find anything so I did the grunt work myself and thought I’d share it with you. This will scroll the dialog and the modal overlay so they stay correctly positioned on the page even if the user moves the browser window scroll bar with their mouse pointer or a mouse scroll wheel.

Scroll UI Dialog With the Page

$(document).ready(function() {
    $(document).scroll(function(e){

        if ($(".ui-widget-overlay")) //the dialog has popped up in modal view
        {
            //fix the overlay so it scrolls down with the page
            $(".ui-widget-overlay").css({
                position: 'fixed',
                top: '0'
            });

            //get the current popup position of the dialog box
            pos = $(".ui-dialog").position();

            //adjust the dialog box so that it scrolls as you scroll the page
            $(".ui-dialog").css({
                position: 'fixed',
                top: pos.y
            });
        }
    });
});

Demo and Code

Want to see how it works? Try the working JSFiddle demo and see for yourself.