Thursday, July 14, 2011

I Love Regex

regex is awesome. Its powerful, its fun, and it can make you extremely efficient. There are 2 places where regex is most needed.

1) fixing code.
You've seen maybe 3 videos on my youtube channel about using regex with text wrangler.  I don't know about you, but I have to fix code sometimes.  And sometimes, it requires replacing some text a thousand times.  Or say you have a long list of stuff, and you wanna make it into a comma list.  That regex is simply

Find:
\r
Replace with:
,

So, it's quite often that I need to replace a bunch of stuff in some HTML or PHP, or even CSS and knowing regex makes this task very simple.  If you didn't know regex, you would either have to pay some kid to do the same task 1000 times, or you would have to waste your time doing it.  Or, if you didn't know how to use regex in your text editor, you'd have to write a script to do the replacement for you.  So get to know your text editor. This function is also called "grep".

2) Pattern Matching
This is pretty generic.  This can mean anything from page scraping, to dom crawling, to email syntax checking, to curse word validation.  It's all pattern matching.
There are 2 extremely useful regex you should know about.

1) match until character.  This is great for DOM crawling.  But it's also great for email addresses.  The regex is [^c]+  Where "c" is the character your are matching until.  So to match every div on the page, you would do div[^>]+  That would match <div however many times it was on your page. If you wanted the closing > you would just add it on.  div[^>]+>  ta da.

2) match until string.  This is extremely useful, and a lot of people never know about it. Lets say you have a div of class "hello" and inside maybe 20 divs down, is a class "world"  You can't use the "match until character" to find "world".  You would use this awesome regex.

hello(?:(?!world).)+

Complicated right?  yea, well just copy and paste it when you need to use it.  Lets explain.

  1. We start with hello. Pretty simple.

  2. Then we first use a negated lookahead.  (?!world).  Which basically says "match one time the string "world" NOT followed by anything. (which is the .)  So again, were matching 1 time, the word "world" that is NOT followed by anything.

  3. Then, we need to not just match 1 time. That would just give us 1 character. We need to match everything until we get there. Just like the "match until character" had the +, we need a + here as well.

  4. But you can't just add a +.  And you can't wrap the whole thing in square brackets like a normal regex.  So we need to wrap in parentheses so we can use the +  ((?!word).)+

  5. BUT, we have a problem that we just used parentheses, which are going to capture the result.  So we now need to NON CAPTURE those parentheses so they stay out of the way.
    (?:(?!world).)+

And that is the "match until string".

You could also use another regex instad of a string.  say we wanted to find hello world or hello planet.
(?:(?!world|planet).)+

Heres a video explaining this if I didn't do a good job writing it.

Tuesday, July 5, 2011

Source Code Release - Load After Scroll / ForeverScroll

The video



Also to note:
You could pass in a number into the load function and load different content, you don't always have to load the same thing over and over, that was just for the example.

<html>
<head>
 <style type="text/css">
  #flickr {
   height:600px;
   overflow-x:hidden;
   width:800px;
  }
  .flickr_results, .loading {
   padding:10px;
   border-radius:5px;
   background:#eee;
   color:#555;
   margin:10px;
   font-family:helvetica;
   font-size:11px;
   font-weight:bold;
  }
  .loading {
   background:#000;
   color:white;
  }
 </style>
 <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
 <script type="text/javascript">
  
  var loading = true;
  
  function loadFlickr() {
   var url = "http://api.flickr.com/services/rest/?&method=flickr.photosets.getPhotos&api_key=4ef2fe2affcdd6e13218f5ddd0e2500d&photoset_id=72157619415192530&format=json&jsoncallback=?";
   $.getJSON(url, function(data) {
    var photos = data.photoset.photo;
    $.each(photos, function(i,photo) {
     var title = photo.title;
     $("#flickr").append("<div class='flickr_results'>"+title+"</div>");
    });
    
    // once we've loaded
    // kill the loading stuff
    loading = false;
    $(".loading").remove();
    
   });
  }
  
  $(function() {
   
   // load initial photos
   loadFlickr();
   
   // scroll event of the main div
   $("#flickr").scroll(function() {
   
    // get the max and current scroll
    var curScroll = $(this)[0].scrollTop;
    var maxScroll = $(this)[0].scrollHeight - $(this).height();
    
    // are we at the bottom?
    if( (curScroll == maxScroll) && loading == false) {
    
     // when you start, set loading
     loading = true;
    
     // add the loading box
     $("#flickr").append("<div class='loading'>Loading...</div>");
     
     // scroll to the bottom of the div
      $(this)[0].scrollTop = $(this)[0].scrollHeight - $(this).height();
     
     // load more photos
     loadFlickr();
    } 
   });  
   
  });
 </script>
</head>
<body>
 <div id="flickr">
 
 </div>
</body>
</html>

Source Code Release - CSS3 Animation Menu

Here is the video



<html>
<head>
 <style type="text/css">
  body {
   background:#9cb4b3;
  }
  div.moving_arrow {
   width:640px;
   height:25px;
   margin:50px auto;
  }
  .moving_arrow ul {
   margin:0;
   padding:10px;
   border-radius:8px;
   height:inherit;
   width:inherit;
   background:-webkit-gradient(
    linear, 
    left top, 
    left bottom, 
    color-stop(0, #fff),
    color-stop(1, #e5e5e5)
   ) #e5e5e5;
   -webkit-box-shadow:0px 0px 6px #555;
  }
  .moving_arrow ul li {
   list-style:none;
   float:left;
   margin-right:11px;
  }
  .moving_arrow ul li a {
   display:block;
   float:left;
   padding:4px 8px 8px 8px;
   font-family:helvetica;
   text-shadow:0px 1px 1px white;
   color:#666;
   font-weight:700;
   text-decoration:none;
  }
  .moving_arrow li img {
   float:left;
   padding:4px 3px 8px 8px;
  }
  #arrow {
   width:12px;
   -webkit-transition:margin-left 400ms ease-out;
   margin-left:50px;
  }
  #arrow svg, #arrow polygon {
   width:12px;
  }
  #arrow.home {margin-left:54px;}
  #arrow.apps {margin-left:150px;}
  #arrow.blog {margin-left:233px;}
  #arrow.about {margin-left:339px;}
  #arrow.support {margin-left:457px;}
  #arrow.contact {margin-left:569px;}
  #arrow polygon {
   text-shadow:0px 1px 1px black;
   -webkit-box-shadow:0px 0px 6px black;
  }
  
 </style>
 <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
 <script type="text/javascript">
  $(function() {
   $(".moving_arrow ul li a").mouseover(function() {
    $("#arrow").removeAttr("class").addClass($(this).attr("class"));
    return false;
   });
  });
 </script>
</head>
<body>
 <div class="moving_arrow">
  <ul>
   <li>
    <img src="icon.png"/>
    <a class="home" href="">Home</a>
   </li>
   <li>
    <img src="icon.png"/>
    <a class="apps" href="">Apps</a>
   </li>
   <li>
    <img src="icon.png"/>
    <a class="blog" href="">Blog</a>
   </li>
   <li>
    <img src="icon.png"/>
    <a class="about" href="">About Us</a>
   </li>
   <li>
    <img src="icon.png"/>
    <a class="support" href="">Support</a>
   </li>
   <li>
    <img src="icon.png"/>
    <a class="contact" href="">Contact</a>
   </li> 
  </ul>
  <div id="arrow">
   <svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="12px" height="7px">
    <polygon id="arrow_thumb_shadow" points="0,0 6,7 12,0" fill="#333"/>
    <polygon id="arrow_thumb" points="0,0 6,6 12,0" fill="#e5e5e5"/>
   </svg>
  </div>
 </div>
</body>
</html>

Monday, June 20, 2011

How to Learn Web Programming

There are a lot of different ways to learn anything.  Reading,  listening, watching, doing.  In programming, I find the best combination of learning is watching then doing.  Some people really like to read, but I think when it comes to programming, reading is the wrong way to go.

Why video?
The cool thing about video is that you get to see and hear at the same time. And its in the tone at which the trainer wanted you to hear it.  So you also get their inflection and emphasis on certain parts.  This is why I chose to produce a bunch of videos and why you won't really see tutorials on this blog.  I think programming, even straight code, needs to be seen, visualized and explained. Sometimes just watching someone type something out is way more helpful then reading a final code block.

Errors will also occur on video.  And thats not a bad thing.  One thing I've had to work on in doing these videos is being able correct errors really quickly and explain what went wrong. Honestly some of the best learning you can get is from watching someone else make errors.  I used to stop the video and correct it, or re make the video because of the errors. But now I think it's even more valuable to let people watch me debug on the fly and figure out how to fix whatever the problem may be.

Why not programming books?
"Books suck. Watch videos."  That was going to be my tagline for square bracket. Catchy no?  While I don't think books suck, I do think they aren't ideal for learning to program.  For a short period of time they are good as references, but the internet is fast enough now where that is even becoming irrelevant.  See, printed books lose their relevance very quickly.  Programming languages get updated all the time.  I mean just 3 years ago it was all about web 2.0, 2 years ago was all about html5, and this year is all about CSS3 transformations.  Not only that, the syntax for this stuff is changing all the time.  Of course if you buy books on languages that are frozen then you will be safer.  But still, you can't see a piece of code, then see it work, and interact with it at the same time.  You have to read the code example, type it in, then try it.  It's too many steps and leaves you too disconnected from the learning.

So what about online books or written tutorials?
So written tutorials online are good when coupled with other media.  That is if your able to provide an interactive example along with the tutorial you are halfway there.  So the person learning can get that hands on access to play with the code.  I think the perfect example of this is w3schools.com  I went to this site probably 10,000 times while learning CSS. I could never remember everything when I was 15.  But they provide examples of every single CSS class and selector.  That really helped.  That kind of "try it now" is a perfect way to learn.

What is most important?
Just do it™.  If you are trying to learn something, go with video first to get a good idea of what is going on, then dive right into code. That is THE best way to learn.


My learning process generally goes:
1) look for a "how to" on youtube.
2) look for some sample code online.
3) Launch the example and see if it works
4) try to change something about that example and not break it
5) try to apply new modifications specific for a project

And by then you should pretty much understand how it works, how it breaks, and how you can use it in your application.

Sunday, June 19, 2011

Javascript Before jQuery

I get asked all the time how I learned as much as I have about jQuery.  And then answer really consists of 2 things.

1) I already knew Javascript really well.
2) I do a lot of jQuery Projects.

I really want to focus on number one.  Because jQuery makes coding javascript a lot easier, I find more and more new javascript coders, or new coders in general strictly using jQuery.  They even refer to jQuery as a programming language.  This of course is not true, because jQuery is just a javascript library.  But it demonstrates an important point that people are starting to skip a huge step in front end development.

jQuery is the most popular javascript library.  And IMO for good reason. But when people want to start making some kind of front end project, they turn straight to jQuery.  Now I won't say that "there are things jQuery can't do". But I will say that you shouldn't do everything in jQuery.

There are 2 main purposes of jQuery.
1) Simplify otherwise tedious javascript processes.
2) Handle cross browser craziness.

Basically something like $.post() for ajax makes it both simple to use and handles IE's differences with the XHR object.  What is the XHR object? Well if you started with Javascript you would know.

At any rate, lets talk about a few cases where you would NOT want to use jQuery.

1) Extreme speed without caring about browser compatibility.
Lets say you need to develop something for iPad.  Well you know there will only ever be 1 browser.  So you can write your javascript specifically for that, and not have to have jQuery do all it's extra stuff or if conditionals to check for IE and Firefox and opera and the rest. I'm not saying you have to, but if something in jQuery is being slow for you, maybe a loop is taking way too long, writing it in pure javascript can help.  Because with any javascript library there will always be SOME (maybe very small) latency because its not core  javascript, its a layer on top.

Its the same principal as, code will be faster in C than it is will be in PHP.

2) Element properties
This one I just found because I was doing something in jQuery I wasn't supposed to. This is actually correct behavior, but I really love this hack.  What I'm about to talk about is in this video http://www.youtube.com/watch?v=8G_i615QLCg

Basically this little plugin allows you set the "value" attribute on an html SELECT box (just like every other html input element) and it will select the correct OPTION in the drop down. So no need to load in PHP or anything, you can load the form data just like all its brothers and sisters. The problem though, is that jQuery's .val() and .attr("value") methods actually all call DOMElement.value.  Which, when set on a select box is actually the current value, not the value attribute.  Your not technically supposed to set a value on a select box because the OPTIONs  have the value, which is why jQuery isn't using the actual value attribute. So to get around this, you need to use plan javascript element.getAttribute("value") and that will work.  If I didn't know javascript I never would have gotten this hack to work.

3) Respect
You need to respect how much time you are saving by using jQuery instead of straight javascript.  Because it makes you appreciate the code more.  And I really believe that coding is an art form, and we are all artists.  Artist love their work and respect it, and understand it's roots. Take a look at this video I did on what doing AJAX looks likes WITHOUT jQuery. http://www.youtube.com/watch?v=e_AO04xlB1c Its actually from the first time I learned about jQuery and jQuery Ajax.  I used to write out 20 lines of code for ajax.  And now its just 1 or 2 lines.  You really do appreciate what jQuery has done, and it I think it helps make you as a web developer want to make your clients feel that way about your creations. Respect.

4) Debugging
jQuery is software.  Like all software there are bugs. (What you write bugless code?) So what happens when something isn't working right? Or you need to do something that jQuery didn't write a nice little function for?  Your out of luck.  Better start learning the entire javascript language real fast now.  Which is going to seem incredibly hard now that you are used to jQuery.  And lets say something you want to do isn't working right, or is slow.  You could easily write it in javascript if you knew how, and move on with the project.

So long story short.  Its important to understand the core of something before you start using layers on top.  But we can't expect too much, this is how the world is going now a days.  We use computers on a daily basis but how many of us know how they actually work inside?  As time goes on, we as people tend to ignore how things became how they are, and I think thats not a good thing. We should always learn from the past, respect it, and appreciate why things are the way they are now.

Friday, June 17, 2011

Chas-ification

Preface: This is an email I just received from Chas.  If you don't have a Chas, I suggest you get one.


Sean: A million thanks for covering the packing/shipping today. Despite what I hear, you're a stand-up dude.

I'll be studying in a coffeeshop like a hipster most all day today. Feel free to holler at me through one of the following approved methods:

1. SMS
2. electronic mail
3. telefon anrufen
4. telegram, stop.
5. homing pidgeon--i left one in the shipping room.

Stephen and Rob, same goes for you--let me know if you need anything. Stephen, I'll hammer out some CRM's today, too.

Suck it nerds, 

Chas.

#somanyhipstersinhereIfeelLikeIminPortland

Thursday, June 16, 2011

Debugging like a pro

I can't tell you how important it is to know how to debug code.  So as many of you know, I'm on the youtube making training videos.  Most of these videos are not geared towards beginners and assume some level of programming.  Time and time again I get hundreds of people asking me

"Whats wrong with my code"


Your failure to debug. Thats whats wrong. Lol.  I'm throwing that "lol" in there to be more lighthearted about it. I'm not mad, and not upset that people aren't debugging.  I'm able to fix 70% of peoples bugs with the following 2 steps.

1) Paste into TextWrangler.
Literally the syntax highlighting alone will go "HEY LOOK AT ME.. IM A SYNTAX ERROR".  If you paste your code into your text editor and its all one color.. Chances are you have a syntax error. Better check that out.  Not using an editor that has syntax highlighting?  Get one.  For mac you have text wrangler, coda, netbeans, text mate.  For windows you have eclipse, notepad++, dreamweaver.

.click(function() should not be pink



2) Firebug's net tab.
So if the code checks out in the text editor, I just open firebug on their site and click the "net" tab.  What the net tab will do is simply highlight all the resources in red that failed to connect.  Whats a resource?  Its a javascript file, a css file or an image.  Basically anything you try to link to is a resource.  So if your getting "$ is not defined". Chances are your jQuery.js file is not connected. Click the net tab and see confirm that.



"I don't use firefox"
Don't care.  Get it, use firebug, deal with it.  YES you can use safari and chrome's inspector.  But honestly I think they are harder to navigate around.

OK, so thats 70% of the errors fixed. Whew. What about the other 30%? Well 10% of those are bad CSS selectors for your jQuery.  I can understand this one though. Sometimes you put a # instead of . and you get confused. The best way to debug these, are to use firebug's console and test your selector out.

So now that we've discussed the most common debugging techniques. Lets talk about more advanced ones.

"I feel like my changes aren't being saved"
Happens all the time. Sometimes you're editing the wrong file, or whatever.  There are times when you just have to CTRL A > Delete > CTRL S.  Yes, select all, delete, and save.  Just to see if your changes are even being made.  Chances are - you were editing the wrong file.


"I'm using an MVC but my URLs won't work"
So an MVC is a PHP framework model called "Model View Controller".  The basis for almost every MVC out there is the htaccess redirect everything to the index.php file thing.  So if your URL's aren't working, either you don't have this file, or its not enabled to work.  If your using apache, I made a tutorial on how to fix this. http://www.youtube.com/watch?v=9cLcmX3NcvM



"500 error!"
This means 1 of 2 things.  You have a syntax error in your htaccess, or a syntax error in your PHP.  So look at your htaccess first, but if you haven't recently made changes to it, its time to get into PHP.  First place to look is your error log.  This should be logging all your PHP errors.  Its normally located in /var/log/apache2/errors.log or phperrors.log.  If its not there, you need to enable it (or check the location) in your php.ini file.  If you can't do any of that then you need to display your errors. So turn on errors.

ini_set('display_errors',1); 
error_reporting(E_ALL);

If you are scared about doing this on a live site (which you should be) Check out this tutorial on how to style your fatal errors so its not THAT huge of a concern (for that 1 minute while you debug it)
Now load your error again, and you should be able to see exactly where it is.

NOTE: Coda (for mac) has a really handy PHP syntax checker as a plugin.  I highly recommend it.

"mySQL is giving me the wrong results"
Or you are giving mySQL the wrong query. :D
I suggest you echo out your query in full, paste it into a database app on your desktop and debug it in the console.  I use sequelPro for mac, and I think windows has some microsoft something.  You can use PHPmyAdmin as well, but I really got away from that a long time ago.



Basically you are just gonna look for the mysql error, and if you don't find one, you can quickly tweak your query to get your results, then look at your code and see why your input wasn't what you expected.


"Cannot access ___ property of undefined"
This is your favorite javascript error.  The debugging trick with these is to console.log() the main object, then look around in that object in the console. Firebug will print out the object in a nice neat cascading way in order traverse the object and its properties.  I use this a ton.  This will allow you to see what properties actually exist on that object, and where you might have messed up.

TIP!
The best tip I can give for debugging is this PHP function.

function debug($data,$die=0) {
echo "<pre>";
var_dump($data);
echo "</pre>";
if($die) die();
}

I use it everywhere.  Basically you call debug($myVar); and it prints it out nice and neat for you to read. You can even pass debug($myArray,true); and it will print then kill the script.  If your are using and MVC - put this function outside in your base controller and then you can use this without having to do $this->debug().