PHP is what they call a “loosely” typed language. This means that if you have "105", it could mean you have the string “105” or you can use this as a number, adding and subtracting to your heart’s content. One thing that gets a little tricky in PHP because of this fact is the number 0. Since PHP tries its best to determine what you want from your variables, 0 can mean 0 or false…and sometimes this makes things a bit difficult. Luckily we have the ===.
Like other languages == is the comparative operator, but when comparing 0, often times PHP interprets it as false rather than an actual 0. This is where === comes into play. This operator compares not only a value but a type as well. So when you want to compare 0 and make sure it is comparing the integer 0, then it’s time to use the === operator.
$foo=false;
//true if($foo==0){}
//false if($foo===0){}
Is it isset?
One thing that is used a lot in PHP, but I always miss in other languages is the isset function. It is a very powerful and easy way to determine if something exists. What isset is useful for is to determine if a particular variable or element in an array has a value. This may seem a little odd and silly, but it comes in handle a lot. It takes a bit of getting use to, but this function comes in handy a lot.
function PFP($foo) { //Add a default value for bar, //if it is not set. if(!isset($foo[‘bar’])) $foo[‘bar’]="foo"; }
So…Empty
The single greatest function in PHP, and the one I miss the most in other languages, is the empty function. It is such a simple idea, it checks a variable to see it is empty, and returns true or false. It checks for several things, but it is most useful when you want to check a string or array, because no one likes an empty string or array. However, this function also checks for null, false, or 0…which are all considered empty. When developing in PHP, you never go without using the empty function.
function PassValue($foo) { if(empty($foo)) returnfalse; }
Calling Your Functions, The Fun Way
In PHP, it is extremely easy do complex things, like calling functions or class methods with a string… that’s right, with a string. At first this sounds like something a crazy scientist would want to do, but this actually comes in handy quite a bit. First of all, this makes building dynamic libraries very easy. For instance, you may want to pass in a string that references a function you want to call.
To achieve this, we use the function call_user_func, which takes in one argument and a set of parameters. That is, you give it the function to call followed by the parameters you want to pass to that function. Its usage is really best described by example:
function CallMe($param){}
call_user_func(‘CallMe’,$myParam);
So there are four useful PHP tricks that you can use. It’s true they are less tricky and more just things you need to know, but trust me when I say they can be used in a lot of different ways. This wraps it up for this tutorial, but just remember when you need coding help, all you have to do is Switch On The Code.
This is something that I expected to be straightforward – binding a DataTable to a WPF DataGrid. The problem is that DataTable doesn’t implement IEnumerable, and unfortunately that’s what the DataGrid’s ItemsSource property requires.
Fortunately for us, there’s a really simple workaround. DataTable has a property named DefaultView, which returns a DataView that can be used for binding purposes.
// Create a DataTable and populate it with // some example data. DataTable myDataTable =newDataTable();
// Add columns to DataTable.
myDataTable.Columns.Add("Column A");
myDataTable.Columns.Add("Column B");
// Add some rows to the DataTable.
myDataTable.Rows.Add("A1", "B1");
myDataTable.Rows.Add("A2", "B2");
myDataTable.Rows.Add("A3", "B3");
// Bind DataTable to DataGrid.
myDataGrid.ItemsSource= myDataTable.DefaultView;
The original purpose for the DataView is for custom sorting and filtering, but it works out great for a quick and easy way to make DataTables bindable. Hopefully this will save you some time and an unexpected compile error when you need to populate a DataGrid with a DataTable.
CSS is a powerful beast, and an essential part to any self-respecting website. With all this power, comes a lot of different tricks that one can employ to accomplish your tasks. Some of these tricks involve positioning your content, and today we are going to touch on that. For this tutorial we are going to reveal some of the best ways to center your content, wherever that content might be.
There are many different ways to center your content using CSS. Some are a bit more strait forward than others, but luckily they are all fairly simple to implement. By the end of this tutorial, you should be able to do something like this:
I’m Centered!
Centering Horizontally
One of the simplest ways you can center elements is using text-align: center on the contents wrapper. For example:
As you can see we are using the text-align property on both the content and the wrapper. This is because we center the text on the parent div which the inner div will inherent. So we have to realign our inner div text to the left. This is easy to implement, but not perfect.
We can actually use margins to horizontally center things as well. However, when using margins, we typically need to have a content container that has a set size. Sometimes you may even need to give your content wrapper an exact size as well. For this first example we are going with the worse case scenario:
As you can see we have to give both our wrapper and our container a width. However, since we know all the numbers, we can do a little bit of math to accomplish our goals. We take half of the width of the wrapper, which is 200 pixels, then subtract half of the content width. This gives us a margin of 150 pixels, which will center it completely. Though this is strait forward and guarantees that our content is centered no matter what width we make the wrapper, there is an easier way.
This method involves auto margins, which means that CSS will calculate the margins for us. In this case we still have to give our content container a width…but not our wrapper. This means that our wrapper can be any size we want. Also, we can us the top/bottom left/right margin shorthand as well.
This is typically the preferred method to center your content, but there is one issue. If you are looking for optimum compatibility, you will have to go with the text aligning method, as the automatic margins are not supported by every browser. Every modern browser supports auto margins, but just not older browsers.
If you really feel adventurous, you can try our last example of horizontally centering. It involves “relatively” positioning our content container, then shifting it a bit. Here is what it would look like:
Here we take our content and relatively position it. This allows us to use the left property to move our content around, which we do using left: 50%. This will move the content, but it will not be centered, as the top-left corner is centered rather than the center of the content container, shifting it to the right. To accommodate for this, like our first margin example, we calculated half our contents width, but this time we subtract it from our current position. The end result is centered content.
So these are the main ways to get thing horizontally centered using CSS. There are other tricks you can use to get things done, but these methods are the most common and in the case of the first two, the most dynamic. However, there is still the trick of getting things centered vertically.
Centering Vertically
Here is where the tricks come in. There are two main ways to center your content vertically on the page. However, before we start digging I should note that both of these methods require your content to have a set height. There are ways to center content without setting the height, but they have been proven to lack cross-browser compatibility. These two ways are your best bets.
The first way is exactly the same concept as our last horizontal example, except applied to the vertical position. It looks something like so:
As you can see, its the same basic concept. You relatively position the content in the center, then offset it by half its height. It works in pretty much any browser you will come across, and is simple to implement. A good solution, however, this is another way to do things.
This solution is a little odd at first, but it is the best solution to center your content vertically. That being said, it is a tricky one. It uses a floated div to force the content to the center of the page, and we all know floating things can be a pain sometimes. Luckily its implementation is fairly simple:
So now we have this new div, which we can call the floater, that basically pushes our content container to the vertical center of the page. As long as we remember to “clear” the content container everything will work as expected. To make things better, this method is said to be extremely compatible browser wise, with reports that it works in IE 5.
While there are all kinds for crazy ways to center content vertically, what about if you just want some plain text centered. Sure you could use one of the solutions above, but that seems like a little bit of overkill. Well this is were our secret third solution comes into play.
This will center a single line of text, and I stress single. I’m sure you noticed that the key to this method is the line-height, which makes each line of text a particular height. This means that if the text wraps, the next line of text will also be 50 pixels tall. This makes this solution good if you need a quick solution for one line of text, but otherwise something for a later time.
So this collection of techniques are your best solutions for centering your content, in both the x and y planes. They are simple to use and they get the job done. This will wrap up this tutorial, but just remember, when you need coding help all you have to do is Switch On The Code.
We have talked about jQuery a lot over the past months, and even more since the humble beginnings of Switch On The Code. There are many reasons for this, and I am sure we all can agree that jQuery is just awesome. From its simple way of grabbing DOM elements down to its powerful extensions that make the possibilities effectively endless. But there is one thing we have covered yet… jQuery Animations.
Speed:
None
Slow
Fast
10ms
100ms
200ms
400ms
800ms
Animation:
Show
Hide
Slide Up
Slide Down
Fade In
Fade Out
Move Left
Move Right
In past tutorials, we have looked at a few of the simple animations that you can do with jQuery, and more specifically the show and hide. We have also seen the slideUp and the slideDown a few times. However, in this tutorial we will go over all four, plus some more, just in case you missed those or forgot about them. So without further blabber, let’s get started.
Animations can be any number of fancy things, and most often we think of a complex string of frames that are played in rapid succession to give up the illusion of motion. Now, film school definitions aside, in jQuery a good portion of your animations will deal with showing and hiding your elements in some neat way. This could be throwing it from off screen onto the screen, or sliding it down from nowhere, or even making it appear out of thin-air. The fact remains, though, that most of the time you will be merely showing or hiding the elements in question.
Show/Hide
On the most basic level you have two functions that are technically not animations, but do “show” and “hide” your elements, and yep, you guessed it, they are called show and hide. All you have to do is call either on an element to perform the subsequent action:
$(‘#element’).show();
$(‘#element’).hide();
Pretty easy, right? I would get very use to seeing those two, because they are the foundation for advanced jQuery development. Showing and hiding are used in just about every rich application on the web.
The neat thing is that these two, normally not-so-animated functions, can become animation functions when a “duration” is passed into them. This duration can be a string (“slow” or “fast”) or a number representing the length of the animation (in milliseconds), and all animation functions can take a duration. When a duration is passed in, show and hide actually animate the width, height, and opacity of an element at the same time.
Take a close look here. This is what most of your animating will look like. Calling a function on an element and passing in a duration. All standard jQuery animation functions work in the same way, allowing you to use “fast”, “slow”, or a millisecond duration. However, unlike show and hide, all the other animation functions will default their duration and still animate without anything being passed in.
Sliding and Fading
Moving on to our first real animation, we have the “slide”. A slide animates the height to give the illusion that an element is “sliding” away or into existence. A very interesting animation indeed. Just like the example above, there are two functions for sliding, one to show and one to hide. slideUp hides an element by reducing its height until it reaches 0. slideDown increases its height until it reaches its calculated or given height. If the element is already shown, slideDown does nothing, and vise-versa for slideUp.
Simple enough. But sliding isn’t for everyone, and thankfully jQuery has another pair of functions to handle fading. Fading works by scaling the opacity to and from 0. The two functions for fading are, you probably guess them, fadeIn and fadeOut. It is probably also a lot more obvious which one hides the element (fadeOut) and which one shows it (fadeIn). Just like sliding, the syntax is extremely simple.
And that are the two quick-style animations that jQuery currently offers. However there is another function we can use…one that is all powerful…one that will allow us to become…..Masters of the Universe!
The Animate Function
Ok, so honestly there is a very slim chance that this jQuery function will fill you with all the power of Grayskull, but it sure does a lot of cool stuff when it comes to animation. If fact, it can do just about anything you want. To keep the scope of this tutorial less than a law briefing, we are going to go over just one way to animate with it.
The animate function takes in a lot of different combinations of things. However, the most important is the first argument, which never changes. The first argument that you pass into it is what you are animating. This could be its position, its color, its opacity, or even its size, the possibilities are endless. You actually pass in a map of css properties to animate, so if it’s in css, you can animate it. For this example we are going to nudge our element back and forth, i.e. its position.
The first thing to remember is that anytime you are modifying the position of an element, you have to change the css position property of the element in question. Even if you just change it to use the position of “relative”, it needs to be something you can apply a left and top property to. As long as you can position the element with css, you are good to go.
So the plan is to move our element left and right, by 50 pixels or so. In order to do this, we have to animation the left property by +/- 50 pixels. This is what our animation call would look like for a basic position shift:
As you can see, it is just as simple as our slide and fade calls, except we are missing our speeds. Of course jQuery is not going to leave us without a way to set that, and in fact it is the optional second argument for this function.
Thats right, you can specify speed just like the other functions we looked at. You can use “fast”, “slow”, or a number. Anywhere from 10 milliseconds to 100 seconds, it’s up to you.
So this is how you move an element left or right with the animate function. Remember, you can animate any css property, so the possibilities are truly endless.
Well, these are the basics to animating things in jQuery. If the built-in animations don’t do it for you, you can always use the versatile animate function. They are all fun to watch in action and they always add that needed flair. Just remember, we you need coding help, all you have to do is Switch On The Code.
For the past few years Switch On The Code has been bringing you tutorials and news in the world of programming. Last week we expanded our repertoire to include video games by launching Avoid The Grind. We’ve assembled an excellent team of writers to bring you the best video game news, guides, reviews, and media.
As for the technical side, Avoid The Grind was built on Drupal 7 and is hosted using Amazon’s Elastic Cloud Compute. Generally we’ve been very happy with both Drupal 7 and EC2. Eventually this site will migrate to both of these services as well.
We’re very excited about Avoid The Grind, probably because we all love video games so much, and I hope you guys find it a great resource.
For the last few years we’ve been using a dedicated server for all of our hosting needs, but recently we decided to choose something a little more flexible and extensible and Amazon’s EC2 seemed like a perfect fit. Amazon offers a free micro instance for a year, so off we went – building our latest project. It wasn’t until the server started getting a little use that we noticed something important – a micro instance could end up costing us a significant amount of money.
At first this doesn’t make any sense because the micro instance is by far the cheapest solution Amazon offers. The problem is how storage is handled on a micro versus other types of instances. The only available choice on micro instances is the Elastic Block Storage (EBS), which charges per 1 million I/O requests. You might think a million I/O requests is a lot, but when you have an operating system, database, and web server all reading and writing data, requests build up extremely fast.
We were charged about $0.54 the first month and didn’t think anything of it. It wasn’t until half way through the second month when we finally sat down and did the math. If five people using the site a few times a day are able to rack up half a buck, what happens if the site begins getting similar traffic to this site – 500K per month. That’s potentially 100,000 times more I/O requests, or $54,000. Of course we don’t expect that much traffic immediately, but even a fraction of that could be a shocking bill.
Only a couple of users for half a month
With this knowledge we have moved our site to a small instance, which includes 160GB of local storage. Local storage costs nothing to read or write to, and according to Amazon’s own documentation, is typically used for large websites. There’s definitely nothing wrong with EBS and I think it’s a great service – it’s just not the write solution for running a server that will being doing tons of I/O.
Our new project includes a lot of large images and when we run out of local storage, EBS will be used to dynamically expand our storage space. This solution makes sense, because if an image is requested a million times, it’ll only cost us 10 cents, and hopefully a million views earns us a bit more than that.
Hopefully this article doesn’t discourage anyone from using a micro instance – it was a fantastic (and free) way to build our new project. Just remember to choose the right solution for your product when the time comes to launch.
jQuery is no doubt one of the greatest javascript resources you can get your hands one. One of the reasons for this is, without a doubt, its cross-browser compatibility which no doubt takes a lot of work to maintain. An area that this becomes more apparent is keyboard events, and more specifically, capturing such events. In this tutorial, we will be going through the basics of capturing keyboard events, which like most things in jQuery, is pretty simple.
Here is an example of what we will be putting together together today:
Please type in “SOTC”, notice most other characters are blocked.
So at the heart of mastering keyboard events in jQuery is the magical event.which property, which is passed to an key event handler function. For example:
This would alert the key code for the button being pressed, no matter what browser you are in, which is not an easy task by any means. What the good fellas over at jQuery have done for us is merge the different ways your browser determines what the key code is, and given us the event.which to use. This makes things so much easier, and much simpler.
So, to start our simple example, we need some very simple HTML:
<div>Please type in "SOTC", notice most other characters are blocked.</div> <inputid="test-input"type="text">
That’s all the html we will need. And in this quick example, our jQuery is very simple as well. To start with, let’s set a few variables, one of which grabs the character which was pressed when typing inside the textbox:
$(document).ready(function(){
var str ="SOTC";
$(‘#test-input’).keydown(function(eve){
var charCount = $(this).val().length; var typedChar = String.fromCharCode(eve.which); }); });
So what we have here is a keydown event, which when fired sets two variables. One variable is the number of characters that has been entered in the textbox, and the other is the character that was pressed. We also have a variable that controls what the user has to type in (in this case, “SOTC”). All we have to do now is make sure the user types in the right characters, and to do this we just need a small if statement:
$(document).ready(function(){
var str ="SOTC";
$(‘#test-input’).keydown(function(eve){
var charCount = $(this).val().length; var typedChar = String.fromCharCode(eve.which);
/* If the key pressed is a letter and does not match the next
character in the test string. */ if(/\w/.test(typedChar)&& typedChar != str.charAt(charCount)) { /* Prevent the character from being added. */
eve.preventDefault(); returnfalse; } }); });
Like the steps before it, this step is very small and simplistic. We have an if statement that makes sure the typedChar is a word character, and if it is, tests it against the next character in the test string. Now the regular expression in this test will still allow you to type in other characters such as “.” or “>”, but for the scope of this example, it is not that important.
What is important is that inside the if statement, we prevent the default action of the keypress, which in turn prevents the character from being added to the textbox. So, besides the loophole that allows special characters, you have to type in the right string…otherwise what you type will not even be added to the textbox. Essentially we force the user to type what we want.
So that is the basic idea behind jQuery and keyboard events. With event.which, you have a portal to capturing key presses for just about any browser. That wraps it up for this one, just remember that if you need coding help, all you have to do is Switch On The Code.
Here’s a common scenario – you’ve got a WPF control bound to a property that doesn’t update when the value of the property changes. If the object you have access to doesn’t implement INotifyPropertyChanged or use Dependency Properties, this can be a very common problem.
Fortunately for us, there’s a fairly simple work-around to this issue. WPF gives us the ability to force an update to any binding. Let’s jump right in with an example class:
All right, now some code to change the value of the property:
_myClass.MyString="Some new text.";
What you’ll notice is that when the value changes, the Label bound to the property doesn’t update – this is because WPF has no way to know when the property changes. What we have to do is get a reference to the binding and tell it to update manually.
GetBindingExpressionBase will return the base class for all binding expressions. This means that if you’re binding is something complicated – like a MultiBinding, this will still work. We have to pass the function the target object and property where the binding is applied. We then simply call UpdateTarget, which forces the target to update with the source. Once this is called, our label will display the new value.
I hope this helps someone out there that has encountered this issue. If you’ve got any questions or comments, feel free to leave them below.
In part 1, we went over the creation of a basic jQuery popup plugin. While this is very useful in itself, it is not that flexible yet. This time around we are going to add a few new features that will make our popup plugin way more flexible and useful. So come on and find out what cool things we will make our popup do.
Before we get started, I am just going to note that we are going to be starting with the code we created in part 1. If you have not read it, you should, because you may get a little bit lost otherwise. So keep in mind we are building on part 1.
Here is a quick example of our new and improved popup:
Now that you have part 1 in mind, let’s get started. The first thing we will be adding is a title bar/drag handle that will provide a limited area for the user to click on to initiate dragging. Basically, we will turn our popup in to a normal window, that has a draggable title bar. To begin, we have some new HTML and CSS to implement, which looks like so:
<divid="main"> <divid="popup"> <spanid="handle"></span>
This is a popup… </div> </div> <scripttype="text/javascript"src="jquery-1.5.min.js"></script> <scripttype="text/javascript"src="jquery.popup.js"></script> <scripttype="text/javascript">
$(document).ready(function(){
$(‘#popup’).popup({ handle: "handle" });
}); </script> </body> </html>
AS you can see, we added three things here, all revolving around the “handle” we will be using. We added the HTML and CSS for the handle, and more importantly, we added our first parameter to our call to popup: handle: "handle". Now we have to use all this new stuff.
The parameter we pass into the function represents the ID of the element to use as the handle inside our popup. So what we have to do is search our popup for an element with that ID, then apply the mousedown event to the handle instead of the popup itself. Then we just add the close anchor to the handle as opposed to the popup. When it is all said and done, the changes will look like so:
var handle =this; if(params.handle!=null)
handle =this.find("#"+ params.handle);
var popupElm =this;
handle.mousedown(function(emd){
/* Get the mouses offset when you click the popup. */ var offset = popupElm.offset(); var mxOff = emd.pageX– offset.left; var myOff = emd.pageY– offset.top;
$("body").mousemove(function(emm){
/* Gets the x and y to set the
* popup to, taking into account
* the offset of the mouse position. */ var x = emm.pageX– mxOff; var y = emm.pageY– myOff;
popupElm.css({ ‘left’: x, ‘top’: y }); })
.addClass("no-select")
.attr(‘unselectable’,‘on’);
/* Add a close anchor. */
$(‘<a href="">close</a>’).click(function(e){
e.preventDefault();
popupElm.hide();
$(this).remove(); }).appendTo(handle);
/* Move the popup to the bottom of the document. */
popupElm.detach();
$(‘body’).append(popupElm);
popupElm.show(); }; })(jQuery);
The first thing you may have noticed is the check on params. This check sets all our params (in this case just one) to null when the params object is not passed in. This is just a simple way to make sure we don’t try to access any params that don’t exist, since checking for null still requires the params object to be defined.
The next logic we added finds the handle element, if one is provided, and sets the clickable handle to that element. By default the handle is set to the popup itself. Once we have the handle, it is just a matter using it for the mousedown event, and adding the close anchor to it. The only other addition was to change our closing anchor to popup itself, rather than referring to a parent.
If you ran this, exactly the way presented, you would have a popup that is draggable only by the handle, or title bar if you will. However, it is missing something else we need…a way to position it where we want.
Generally you want to have a way to position your popup when it is shown, before the user moves it. Luckily this can be done with only a few additions. Lets take a look at the updated code:
/* Set the x position. */ if(params.x!=null) this.css(‘left’, params.x–this.width()+"px"); else this.css(‘left’,($(window).width()/ 2) – (this.width() /2)+"px");
/* Set the y position. */ if(params.y!=null) this.css(‘top’, params.y+"px"); else this.css(‘top’,($(window).height()/ 2) – (this.height() /2)+"px");
var handle =this; if(params.handle!=null)
handle =this.find("#"+ params.handle);
var popupElm =this;
handle.mousedown(function(emd){
/* Get the mouses offset when you click the popup. */ var offset = popupElm.offset(); var mxOff = emd.pageX– offset.left; var myOff = emd.pageY– offset.top;
$("body").mousemove(function(emm){
/* Gets the x and y to set the
* popup to, taking into account
* the offset of the mouse position. */ var x = emm.pageX– mxOff; var y = emm.pageY– myOff;
popupElm.css({ ‘left’: x, ‘top’: y }); })
.addClass("no-select")
.attr(‘unselectable’,‘on’);
/* Add a close anchor. */
$(‘<a href="">close</a>’).click(function(e){
e.preventDefault();
popupElm.hide();
$(this).remove(); }).appendTo(handle);
/* Move the popup to the bottom of the document. */
popupElm.detach();
$(‘body’).append(popupElm);
popupElm.show(); }; })(jQuery);
So the first thing you will notice is that we now set a x and a y property in our params object if it is undefined. This is how we get the initial position, through the params object.
Next we check the x and y params, and if they are null, we use the middle of the screen, horizontally and vertically accordingly. However, if either a x or a y is provided, we set the position to those coordinates. This allows you to maybe provide a y (say 10 pixels down), but leave the x alone, centering it horizontally.
Well,this is about all for this tutorial. Keep an eye out, because we may just have a part three coming soon. Just remember, when you need coding help, all you have to do is Switch On The Code.
Have suggestions for improvements for the jQuery Popup? Let us know! Comment or go over the forums and tell us what you would like to see!
One of the most talked about technologies on the web right now is node.js, which is a server side implementation of JavaScript. That’s not really anything new, but what is new is how it’s built. The framework is built on top of Google’s v8 engine, which is lightning fast. It’s made to create “scalable network programs” by making nearly everything work asynchronously. I don’t want to bore you with all the little details, but basically it’s really fast and doesn’t use very much memory. If you feel like you need the nitty gritty details, check out the node.js About Page.
Today, we are going to build a simple application that is going to pull the rss feed from this site and display the raw xml in the browser. The first thing we need to do is get node.js installed, for me this was on Mac OSX. With that said, you need to download the latest version from the node.js Download Page. Once you have it downloaded, expand the contents to a directory of your choice. Now, open up a terminal and change the directory to where you put the node.js contents. Then, run the following commands:
./configure
make
make install
Once everything is installed we are ready to try out some code. The first thing we are going to create is a simple script to make sure everything is working as planned. Below you’ll see our starting script.
var http = require(‘http’);
http.createServer(function(req, res){
res.writeHead(200,{‘Content-Type’:‘text/plain’});
res.end("Switch On The Code Rocks My Socks Off!"); }).listen(5073,"127.0.0.1");
Now, save the code wherever you would like and go back to your terminal and change the directory to wherever you saved the script. In order to actually run the code you type in node name_of_script.js – replacing “name_of_script.js” with the name of your script. To check out the results open a browser and go to 127.0.0.1:5073 and you should see “Switch On The Code Rocks My Socks Off”. In my case I named my file “test1a.js”, therefore my command was:
node test1a.js
Okay, let’s walk through the first application. The very first thing we do is include a library. In node.js we do this using the require function, passing in the library to include. The http library allows you create and handle typical server functions. The next line of code creates an HTTP web server. A typical web server takes an anonymous function that will handle each request. Passed into the function are two parameters, the request itself and the response; the response is used to send a response to the client. At the end of the server declaration we call listen on the created server, passing in the port and host to listen on. Finally, inside our request handler we do two things. We first write the content type into the response header. Then, we respond to the client with the text “Switch On The Code Rocks My Socks Off!” ending our response.
Let’s move on to something a bit more complicated. The next application we are going to build will serve up a couple of static files. These files include an index HTML file and a CSS file. Basically we are serving up a webpage, not a very complicated one but the ideas used below can be expanded into a full fledged static file server. The following code sets up the server just like previously, except we are adding another standard library called fs. The new library, fs, takes care of file handling – reading and writing.
var http = require(‘http’),
fs = require(‘fs’);
http.createServer(function(req, res){
}).listen(5073,"127.0.0.1");
Next, we need to add code for handling the request, just like before this goes into our anonymous function. Below you find the rest of the code, which is explained after.
var http = require(‘http’),
fs = require(‘fs’);
http.createServer(function(req, res){ if(req.url=="/"|| req.url=="/index.html"){
res.writeHead(200,{‘Content-Type’:‘text/html’});
res.end(fs.readFileSync(‘index.html’)); }elseif(req.url=="/part1.css"){
res.writeHead(200,{‘Content-Type’:‘text/plain’});
res.end(fs.readFileSync(‘part1.css’)); }else{
res.writeHead(404,{‘Content-Type’:‘text/plain’});
res.end("Page Could Not Be Found"); } }).listen(5073,"127.0.0.1");
The handler function checks the incoming url and if it is either the root or “index.html” then the text in the HTML file is returned. If the url is for the CSS file then the contents of that is returned. For the most part it looks like the first program we created, but there are some differences. For one we return a different content type for the HTML file – which makes sense. Also, to write out the contents of a file we have to use the function readFileSync. That function reads the file synchronously and returns the contents, which is then written to the response.
That pretty much takes care of our intro into Node.js. Make sure to check back for more Node.js tutorials in the future. If you have any questions feel free to leave a comment below or check out the forums.
While the jQuery UI library is quite powerful, and mighty impressive, its footprint is sometimes a bit too much for the project at hand. The UI library also tends to “take over” your HTML, moving it, adding classes, and sometimes even changing attributes around. This can make styling and customizing your UI elements a bit of a pain, especially when you need a custom solution. This is why sometimes you need a UI solution, using jQuery, but without the jQuery UI. Today we are going to work on a draggable popup.
<divid="main"> <divid="popup">
This is a popup… </div> </div> <scripttype="text/javascript"src="jquery-1.5.min.js"></script> </script> </body> </html>
As you can see, we are wasting no time here and we already have jQuery added to our page. Now we can get started with the real fun part, the plugin. I am putting all my JS in a file called jquery.popup.js, but you are welcome to call the file whatever you like. To start with, we have the basic jQuery plugin structure:
As you can see, it’s not that complex. We are just adding a function called popup to the jquery object. The params we are passing in will be an object, which will allow us to pass in params like we normally would with a jquery call.
The first thing we need to do is move the popup from wherever it is to the very bottom of the body. This allows us to correctly gauge where the popup is at all times, without calculating a whole bunch of offsets. To do this, we will be using the detach function that jQuery provides:
(function($) {
$.fn.popup=function(params) { /* Move the popup to the bottom of the document. */ var popupElm =this;
popupElm.detach();
$(‘body’).append(popupElm); }; })(jQuery);
The real neat thing about the detach function is that it removes the object from the dom, but keeps the jQuery object. This allows us to move the popup very easily. Now that we have our popup positioned in the dom, let’s get this thing moving.
The next thing we will be adding to our plugin is a mousedown event on our popup. The this keyword can be used to access the jquery object referenced by the call to popup, so we will be setting up a variable to reference this.
In this mousedown event we need to capture the position of the mouse:
(function($) {
$.fn.popup=function(params) { var popupElm =this;
handle.mousedown(function(emd){
/* Get the mouses offset when the popup is clicked. */ var offset = popupElm.offset(); var mxOff = emd.pageX– offset.left; var myOff = emd.pageY– offset.top;
});
/* Move the popup to the bottom of the document. */
popupElm.detach();
$(‘body’).append(popupElm); }; })(jQuery);
We accomplish this task by getting the offset of the popup in relation to the document, then subtracting it from the mouse position. This gives us the mouse position inside the popup, which we will use to position to popup later on.
The next step in the process is to add a mousemove event, which will update the position of the popup whenever the user moves the mouse. However, we only want this to happen when you press down. Thankfully we already have a mousedown event to put this new event inside. So let’s get this new event put together:
(function($) {
$.fn.popup=function(params) { var popupElm =this;
popupElm.mousedown(function(emd){
/* Get the mouses offset when you click the popup. */ var offset = popupElm.offset(); var mxOff = emd.pageX– offset.left; var myOff = emd.pageY– offset.top;
$("body").mousemove(function(emm){
/* Gets the x and y to set the
* popup to, taking into account
* the offset of the mouse position. */ var x = emm.pageX– mxOff; var y = emm.pageY– myOff;
popupElm.css({ ‘left’: x, ‘top’: y }); }); });
/* Move the popup to the bottom of the document. */
popupElm.detach();
$(‘body’).append(popupElm); }; })(jQuery);
Here we have the needed logic, which will move the popup whenever we move the mouse anywhere in the body. We have to add this even to the body because if you drag the mouse too fast, and it actually leave the popup. This would cause the event to stop firing if we added it to the popup as opposed to the body itself. With this, even if we drag at light-speed, the popup’s position will always get updated.
But wait, how do we stop the dragging? The way it is set up now, once we click, the popup will follow the mouse position forever. Well, all we have to do is unbind the mousemove event on the mouseup event:
(function($) {
$.fn.popup=function(params) { var popupElm =this;
popupElm.mousedown(function(emd){
/* Get the mouses offset when you click the popup. */ var offset = popupElm.offset(); var mxOff = emd.pageX– offset.left; var myOff = emd.pageY– offset.top;
$("body").mousemove(function(emm){
/* Gets the x and y to set the
* popup to, taking into account
* the offset of the mouse position. */ var x = emm.pageX– mxOff; var y = emm.pageY– myOff;
/* Move the popup to the bottom of the document. */
popupElm.detach();
$(‘body’).append(popupElm); }; })(jQuery);
Thats it, just a few lines stops the movement event. But there is still something missing. Right now we have a draggable div, but not really a popup per se…
The first step to get the “popup” effect is to show the popup, which we can do with a simple call to show:
(function($) {
$.fn.popup=function(params) { var popupElm =this;
popupElm.mousedown(function(emd){
/* Get the mouses offset when you click the popup. */ var offset = popupElm.offset(); var mxOff = emd.pageX– offset.left; var myOff = emd.pageY– offset.top;
$("body").mousemove(function(emm){
/* Gets the x and y to set the
* popup to, taking into account
* the offset of the mouse position. */ var x = emm.pageX– mxOff; var y = emm.pageY– myOff;
/* Move the popup to the bottom of the document. */
popupElm.detach();
$(‘body’).append(popupElm);
popupElm.show(); }; })(jQuery);
Now comes the tricky part, closing the popup. In this tutorial, we are just going to add a link that closes the popup. We will add this right before we detach the popup. It is actually not too complicated:
(function($) {
$.fn.popup=function(params) { var popupElm =this;
popupElm.mousedown(function(emd){
/* Get the mouses offset when you click the popup. */ var offset = popupElm.offset(); var mxOff = emd.pageX– offset.left; var myOff = emd.pageY– offset.top;
$("body").mousemove(function(emm){
/* Gets the x and y to set the
* popup to, taking into account
* the offset of the mouse position. */ var x = emm.pageX– mxOff; var y = emm.pageY– myOff;
/* Add a close anchor. */
$(‘<a id="popupClose" href="" style="color: #fff;">close</a>’).click( function(e) {
e.preventDefault();
$(this).parent().hide();
$(this).remove(); }).appendTo(popupElm);
/* Move the popup to the bottom of the document. */
popupElm.detach();
$(‘body’).append(popupElm);
popupElm.show(); }; })(jQuery);
As you can see, the first thing we do is prevent the default functionality of the anchor. Once that is taken care of we close the parent of the anchor, which is going to be the popup in this case. We also must make sure to remove the link when we close the dialog to prevent adding more than one link to the popup. I also added a little inline style to the close anchor that pops it out a bit on our green popup. This can be removed or moved to an external style as you see fit.
Before we wrap up this tutorial, there is one last thing we must account for…text selection. As funny as that sounds, when you drag the dialog around at crazy speeds and directions, you will select body text and unwarranted flickering will occur. If you have a decent sized webpage, this could mean the whole screen will flicker, which we don’t want of course.
To account for this we have to do two things to the document body: add some css and add an attribute. That’s right, an attribute. To start things off we have to create a css class with what may be the strangest css properties I have ever seen:
<divid="main"> <divid="popup"> <spanid="handle">Something</span>
This is a popup… </div> </div> <scripttype="text/javascript"src="jquery-1.5.min.js"></script> <scripttype="text/javascript"src="jquery.popup.js"></script> <scripttype="text/javascript">
$(document).ready(function(){
$(‘#popup’).popup();
}); </script> </body> </html>
Thats right, five weird “user select” properties. The funny thing is, this prevents users from selecting things in almost every browser. This is the main way we are stopping the crazy selection flicker. The other way is adding an attribute to the body. For convenience, I will just show you all the changes to the plugin:
(function($) {
$.fn.popup=function(params) { var popupElm =this;
popupElm.mousedown(function(emd){
/* Get the mouses offset when you click the popup. */ var offset = popupElm.offset(); var mxOff = emd.pageX– offset.left; var myOff = emd.pageY– offset.top;
$("body").mousemove(function(emm){
/* Gets the x and y to set the
* popup to, taking into account
* the offset of the mouse position. */ var x = emm.pageX– mxOff; var y = emm.pageY– myOff;
popupElm.css({ ‘left’: x, ‘top’: y }); })
.addClass("no-select")
.attr(‘unselectable’,‘on’);
/* Add a close anchor. */
$(‘<a id="popupClose" href="" style="color: #fff;">close</a>’).click( function(e) {
e.preventDefault();
$(this).parent().hide();
$(this).remove(); }).appendTo(popupElm);
/* Move the popup to the bottom of the document. */
popupElm.detach();
$(‘body’).append(popupElm);
popupElm.show(); }; })(jQuery);
The careful observer will notice the first addition is an addClass and an attr call added to the body inside the mousedown event. This adds the css class and set the attribute we need to stop object selection in just about every browser. The careful observer will also notice the removal of the css class and the disabling of the attribute. This combination will disable selecting when you click on the popup and enable selecting when you release it. This eradicates any “selection flickering” that we have, without disabling object selection all the time.
And this is our popup. We can drag it, show it, hide it, all without nasty flickering. That sounds like a popup to me. Of course you can mold this to your needs. The good news is that its a jQuery plugin, so all we have to do is include the script. Keep an eye out for round two though, where we will be using some parameters to set up a few more features. This concludes this tutorial, but just remember that when you need coding help, all you have to do is Switch On The Code.
Everywhere I look now it’s Ruby, Ruby, Ruby and I think it’s about time I figure out what’s so great about this language. As a disclaimer, this tutorial will be pretty much the first thing I’ve ever done with Ruby, so the code might not be what a Ruby expert would consider the most efficient way to get things done. But I don’t care, we all gotta learn somewhere, and I decided to learn by using Ruby’s standard library to download and parse some XML.
I’ve already heard that no Ruby developer uses the standard library for stuff like this, but I’d rather start at the bottom before experimenting with Ruby Gems. All that aside, what I’m going to build today is a very basic Twitter reader, which we’ve done here at SOTC several times with several other languages. Twitter provides a very easy API and a fairly simple XML format that makes experimenting with it easy to do.
Downloading XML
The first thing we need to do is download some XML. After perusing Ruby’s Net::HTTP class, here’s the approach I decided to take:
require‘net/http’
# Build the feed’s URI
uri = URI.parse(‘http://www.twitter.com/statuses/user_timeline.xml?screen_name=SwitchOnTheCode’);
# Request the twitter feed. begin
response = Net::HTTP.get_response(uri); if response.code != "200" raise end rescue puts"Failed to request Twitter feed." exit1 end
The very first thing we have to do is require the Net::HTTP library. There seems to be a few million ways to make simple requests, but I liked this one the best because of the error handling that’s available. get_response will raise an exception if something generally bad happens – no internet connection, twitter.com is down, etc. Beyond that, Twitter’s web server can return several HTTP error codes that indicate a different problem. The code for OK is 200, so if the response contains a code other than 200, something bad happened. In that case, I then raise my own exception so both errors are caught by the same rescue block and the script exits. If everything succeeds, we’ve downloaded our Twitter feed – just that easy.
Parsing XML
I’m now going to modify the script to parse the XML returned by get_response.
require‘net/http’ require‘rexml/document’
# Build the feed’s URI
uri = URI.parse(‘http://www.twitter.com/statuses/user_timeline.xml?screen_name=SwitchOnTheCode’);
# Request the twitter feed. begin
response = Net::HTTP.get_response(uri); if response.code != "200" raise end rescue puts"Failed to request Twitter feed." exit1 end
begin
xmlDoc = REXML::Document.new response.body rescue puts"Received invalid XML." exit1 end
# Parse the data and print it in a friendly way.
xmlDoc.elements.each(‘statuses/status’){ |status| puts"%s – %s\n\n"% [
status.elements[‘created_at’].text,
status.elements["text"].text ] }
To parse the XML I’m going to use the REXML library. The first thing I do is create a new REXML::Document class and supply it with the body (the XML) of our HTTP response. The XML will be immediately parsed and if an error occurs and exception will be thrown and my script will exit.
If no error occurred, I then loop through every Twitter status and print the date of the tweet and the contents. I do this by defining a block that takes a status element, finds the created_at and text child elements and prints their text properties with a dash between them.
Believe it or not, that’s actually all there is to it. If we run this on Switch On The Code’s Twitter feed, we’d get something that looks like this:
Tue Feb 22 20:29:16 +0000 2011 – Redis 2.2 Released http://t.co/K5sJV0N via Redis #storedb
Tue Feb 22 19:50:55 +0000 2011 – Disqus: Scaling The World’s Largest Django Application http://t.co/1iJkWGh via @ontwiik #python #django #programming
Tue Feb 22 16:23:48 +0000 2011 – Kinect for Windows SDK to Arrive Spring 2011 http://sotc.me/65353 (via Microsoft) #kinect
Mon Feb 14 20:49:58 +0000 2011 – A Critical Deep Dive into the WPF Rendering System http://sotc.me/18327 (via Jer’s Hacks) #wpf
Sun Feb 13 23:00:44 +0000 2011 – 500,000 Strong http://sotc.me/32603
Sun Feb 13 22:56:18 +0000 2011 – jQuery Tutorial – Creating an Autocomplete Input Textbox http://sotc.me/29035 #jQuery #tutorial
…
Generally I found using Ruby to be an enjoyable experience. The issue I’m having currently is managing the shear number of ways to do the same thing – especially when it came to iterating and printing the contents of the tweets. I found the documentation to be adequate, but had difficulties knowing when an exception will occur versus when an error code or bool will be returned. All of these things come with experience, which hopefully I’ll gain over time. My next challenge is to pick a UI framework and begin making graphical apps. If you’ve read the example code and have some better approaches, feel free to leave them below.
While not quite as exciting as Reddit’s billions served announcement, Switch On The Code did pass a milestone we’ve been anxiously awaiting – 500,000 pageviews!
We started looking at ways to improve our performance and I think we’ll be ditching our dedicated server and moving into the cloud. This will give us a lot more freedom in terms of scalability and reliability.
We’ve also been tossing around some new design ideas that will eventually be implemented as part of our migration to Drupal 7.
Richard Key (a.k.a The Hairiest) has been brought on as a permanent member and will be contributing lots more tutorials.
Hopefully Switch On The Code and continue this momentum and I look forward to 1 million pageviews!
With jQuery 1.8 came a brand new widget – the autocomplete input field. If used correctly, like in the case of Google’s search suggestions, autocomplete can provide a major boost in productivity. Today’s tutorial is going to demonstrate how to build and populate one of these autocomplete inputs. We’re going to make two identical examples that get their data from two different sources – one will be client-side and the other will be server-side using PHP.
The example dataset will include all of the presidents of the United States. As you begin typing, the input field will automatically popup with suggestions that match your query. Feel free to play with the example below. Some good examples would be “George Washington” or “Abraham Lincoln”.
Client Side
The first example we’ll build today will be entirely client-side. This is by far the easiest approach to take, but obviously the least powerful. The jQuery demo page for autocomplete has a very nice example that we’re basically going to replicate with different data. Let’s start with the html.
Most of the code here is just getting jQuery included. The important part is the label and the input field. The input needs to have an id so we can reference it later and turn it into an autocomplete field.
Let’s jump into the javascript now – the source of presidents.js. The first thing we need is a datasource, which should be a simple array of values. jQuery does the work of iterating through these values to find the ones that match the text already in the input field.
$(function(){ var presidents =[ "George Washington", "John Adams", "Thomas Jefferson", "James Madison", "James Monroe", "John Quincy Adams", "Andrew Jackson", "Martin Van Buren", "William Henry Harrison", "John Tyler", "James Knox Polk", "Zachary Taylor", "Millard Fillmore", "Franklin Pierce", "James Buchanan", "Abraham Lincoln", "Andrew Johnson", "Ulysses Simpson Grant", "Rutherford Birchard Hayes", "James Abram Garfield", "Chester Alan Arthur", "Grover Cleveland", "Benjamin Harrison", "Grover Cleveland", "William McKinley", "Theodore Roosevelt", "William Howard Taft", "Woodrow Wilson", "Warren Gamaliel Harding", "Calvin Coolidge", "Herbert Clark Hoover", "Franklin Delano Roosevelt", "Harry S. Truman", "Dwight David Eisenhower", "John Fitzgerald Kennedy", "Lyndon Baines Johnson", "Richard Milhous Nixon", "Gerald Rudolph Ford", "James Earl Carter, Jr.", "Ronald Wilson Reagan", "George Herbert Walker Bush", "William Jefferson Clinton", "George Walker Bush", "Barack Hussein Obama" ]; });
Once we’ve got a datasource, it’s time to tell jQuery to turn our input field into an autocomplete input field.
We get the element with the id of “presidentsClientInput” and use the autocomplete function to convert it into an autocomplete field. The source property, in this case, points to our array of presidents. That’s all there is to it, the client-side autocomplete input field is done.
Server Side
Instructing the autocomplete field to get its data from a server is a little more complicated, but still not too bad. The first thing we need to do is add the field to our HTML and javascript.
<html> <linktype="text/css"rel="stylesheet"media="all" href="jquery-ui-1.8.9.custom.css"/> <scripttype="text/javascript"src="jquery-1.4.4.min.js"></script> <scripttype="text/javascript"src="jquery-ui-1.8.9.custom.min.js"></script> <scripttype="text/javascript"src="presidents.js"></script> <body> <labelfor="presidentsClientInput">Select President (client-side): </label> <inputid="presidentsClientInput"/> <br/> <labelfor="presidentsServerInput">Select President (server-side): </label> <inputid="presidentsServerInput"/> </body> </html>
All I did was add a new label and input with a different id. I then added another line to the presidents.js file to setup the new input as an autocomplete field. This time, instead of setting the source to a local array, I set it to a string, which means jQuery will use this as a callback URL. It will automatically append a GET argument called “term” with the value of what’s in the input field. So, in this case, my php file will be called as “presidents.php?term=George”.
Everything for the client is now complete. It’s time to move on to the PHP file. Just like with the javascript, the first thing we need is the datasource.
I immediately get the search term out of the GET arguments and then declare an array of presidents. Most applications will probably use some sort of database, but for clarity and simplicity, I went with a basic array.
Next we need to search the array for names that contain the text entered by the user, json encode the results, and return it back to the client.
function filter($president){ global$searchTerm; return stripos($president,$searchTerm)!==false; }
I use PHP’s array_filter function to filter the array of presidents. This function takes a callback that will be invoked on each element. If the callback returns true, the item will be added to the filtered array. To decide whether or not an item should be added to the filtered array I used stripos, which looks for an occurrence of a string using a case-insensitive compare.
The array_filter function creates an array with keys that are the index in the original array. The autocomplete field does not know how to use an array like that, so I use array_values to strip out the keys. The last thing I do is encode the array as json and print it.
That’s all there is to it for a fully functional server-side autocomplete input field. Hopefully you can use this as a starting point for some much more complicated and interesting scenarios. I didn’t show it here, but the autocomplete widget supports a more powerful callback that essentially gives you full control over how the results are returned. No matter what your system looks like, jQuery’s autocomplete widget should be able to accommodate it.
That does it for this tutorial. If you’ve got any questions feel free to leave them below or check out the forums.
I’m proud to announce that we just launched a new iPhone application called Image to Ascii. It’s a fun little tool that you can use to transform images into ascii pieces of art. We also launched the Image to Ascii Website, which has a little more information on the application and some great examples.
With Image to Ascii you can create an image from any picture on your phone or taken with the camera. Basically you can take an image like this:
and turn it into this:
You can also change the the size of the letters, change from color to grayscale to black and white. We built the application for pretty much the single purpose of having a little geeky fun with images. The lite version is free, so if you have an iPhone check it out and tell your friends.