Web Dev Q&A #1: Callbacks, LESS, and Floats
videos

Web Dev Q&A #1: Callbacks, LESS, and Floats

Tutorial Details
  • Topics: JavaScript, CSS, LESS
  • Difficulty: Moderate
  • Estimated Completion Time: 5 Minutes

Today marks the first entry in a new “Web Dev Q&A” series. I’m often emailed concerning various web development related questions. Though some are more specific than others, many of these, I’m sure, would appeal to all of our readers. As such, each week or so, we’ll post a new batch of question and answers from the community, in both article and video form, for your convenience.

This week, we discuss JavaScript callback functions, a LESS compiler, and those tricky CSS floats.


1. JavaScript Callback Functions?

“Hi Nettuts+: is there an easy way to create callback functions with regular JavaScript, similar to what we can do with jQuery?”

Of course. This is any easy one. For example, let’s create a generic function.

function doSomething(name) {
   alert('Hello, ' + name);
}

doSomething("John and Kate Plus 8");

When called, as expected, the browser will alert “Hello, John and Kate Plus 8.” Now, if we want to pass a callback function as well, as the second parameter of the “doSomething” function, we can simply pass an anonymous function.

function doSomething(name, cb) {
   alert('Hello, ' + name);
}

doSomething("John and Kate Plus 8", function() {
   alert('this callback function will only run after doSomething has');
});

Notice how we’ve added a second argument to the doSomething() function: “cb.” You’re free to label this how you wish, though it’s common to keep it as “cb,” which refers to “callback.” Now, that anonymous function will be represented via this variable.

The last step is to simply call it at the bottom of the function.

function doSomething(name, cb) {
   alert('Hello, ' + name);
  cb(); // now run the callback function
}

doSomething("John and Kate Plus 8", function() {
   alert('this callback function will only run after doSomething has');
});

2. LESS Compiler for Coda?

Dear Nettuts+: I loved your LESS.js video, but don’t want to use it for production. Is there an app for Coda that will automatically compile my code instead?

Sure thing. The best solution I was able to find is called LESS.app.

LESS APP

After you download it (free), you simply drag your project folder into the app, which instructs it to watch all .LESS files. At this point, you can continue working on your project, per usual. Every time you save, the compiler will run, which generates/updates an automatically created style.css file. When you’re finished developing your app, you only need to change your stylesheet references from style.less to style.css, accordingly. Easy! Now there’s no reason not to take advantage of LESS — unless you’re using a different solution, like Sass.

Generates CSS FIle

3. Where’s my Background?

“Hey Nettuts+: So I have a navigation menu with a list of horizontal links; but when I set a background color to the menu, nothing shows up? How come? Here’s my code:”

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
	"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>

	<title>Menu Problem</title>
	<style type="text/css">
		#nav {
			background: black; /* why doesn't this show up? */
		}

		#nav li {
			float: left;
			padding-right: 10px;
			list-style: none;
		}
	</style>	

</head>

<body>
    <ul id="nav">
		<li><a href="#">Link</a></li>
		<li><a href="#">Link</a></li>
		<li><a href="#">Link</a></li>
		<li><a href="#">Link</a></li>
	</ul>
</body>
</html>
Where is the background color

Okay, this is a common confusion. The reason why the background of “black” isn’t showing up is because you’ve floated all the list items to the left. When you do, it causes the parent element (#nav) to collapse. There are two solutions:

1. Set “overflow: hidden;”

“Overflow:hidden” is a nifty little trick that was only discovered in the last several years, around 2005. By applying a value of “hidden” or “auto” to the “overflow” property, it seems to remind the parent element that it’s supposed to be wrapping its children! The logic is a bit odd, I admit; however, none the less, it works.

#nav {
	background: black;
	overflow: hidden; /* ta da! */
}
Fixed

2. Clearfix

Setting “overflow” works 80% of the time, though, there might be times when we need to overlap the boundaries of the parent element, in which case “overflow: hidden;” will chop the image/element off. The second solution is to use the popular “clearfix” method. You’ll use this one often, so I recommend that you go ahead and save the code to your favorite snippet management tool, like TextExpander, Texter, or Snippets.

First, return to your mark-up, and apply a class of “clearfix” to the parent element.

<ul id="nav" class="clearfix">

Next, let’s add the appropriate styling for this class. The general functionality is that we use the “after” psuedo class on the parent element to apply content, and then subsequently clear that content — which essentially mimics adding <div style=”clear:both;”></div> to the bottom of your mark-up. However, this method is smarter, and doesn’t ruin our beautiful, semantic mark-up.

.clearfix {
	*zoom: 1; /* triggers has haslayout in older versions of iE
}
.clearfix:after {
	content: " ";
	display: block;
	clear: both;
	visibility: hidden;
	font-size: 0;
	height: 0;
}

“hasLayout is important because it forces the element to have a rectangular shape.”

As you can see, we use “:after” to add a blank space after all of the floated content. We then set the display to block, and clear it, which forces the parent to wrap the floated children. Lastly, we set some general visibility, font-size, and height rules to ensure that this code doesn’t affect our layout in some browsers.

Worth noting is the “*zoom: 1″ declaration at the top. The “zoom” property allows us to trigger IE’s proprietary “hasLayout” property. hasLayout is important because it forces the element to have a rectangular shape. This means that the content of the element cannot flow around other boxes, which will often cause major layout issues with your website. When Microsoft’s proprietary property “hasLayout” is equal to true, the element “has layout.” Luckily, we can trigger this by adding specific properties to our selectors, including “zoom.” Other hasLayout triggers, to name only a handful, are:

  • float: left/right
  • display: inline-block
  • position: absolute
  • height: any value (not auto)
Fixed

Conclusion

That’ll do it for this flagship “Web Dev Q&A” entry. If you have a “not-too-complicated” web development question for us, you can:

  1. Email net@tutsplus.com, and write “Web Dev Q&A” as the subject of the email.
  2. Tweet us @nettuts, and hash “#askNettuts”.
  3. Leave a comment under any “Web Dev Q&A” posting with your new question.

Thanks for reading and watching!

Add Comment

Discussion 52 Comments

  1. Brandon says:

    Great idea for a series Jeff :) Looking forward to seeing more of these as each of the three sections in this were pretty useful. The clearfix trick was especially interesting and I’ll have to include it from now on!

  2. Nice article :) like to see more of these!

  3. Nice Jeff, but why just 3 questions, why not more ;)

  4. w1sh says:

    Sweet! LESS App looked so awesome! Too bad my mom and dad don’t pay for my college, frappes, and Macs..

    • w1sh says:

      For those not cool enough to have a Mac and stupid enough to still use PHP, you can accomplish the same thing with WAMP, and LESSphp.

      MOAR PYTHON!!!!!!!!!! (God I’m starting to sound like my mom)

      • I agree: More Python stuff. I’d be glad to write some stuff myself. Jeffrey, are you intending on having Python stuff on Nettuts?

      • DED says:

        Python is a great language. I wish more web developers liked it as much as regular programmers do.
        It would be great to see more Python / Django ( or other py framework) tutorials.
        Something a long the lines of ‘Codeigniter from scratch’. But, using PHP isn’t stupid, PHP 5.3 is a great language with a lot of OOP built in.

  5. Xbox says:

    Serious question Jeff, what happened to the diving into PHP? and the other PHP related thing i forgot on theme forest.. you keep starting series and randomly leaving them unfinished?

    • Jeffrey Way says:
      Author

      The Diving into PHP series completed. I think Burak might have one more entry in the CI from Scratch series coming though.

      • Yeah Jeffrey, ‘sup with unfinished series’?

        Also, wasn’t CI From Scratch supposed to build a custom CMS at the end?

        And with your Simple Login System tutorial, did you mention a follow-up?

        DB

      • Norguad says:

        And I would like to ask, if you also finish the Javascript from Null video screencast serie?

        Thank you so much for your work you do for us!

      • Jeffrey, sorry if I was a bit, umm, abrupt.

        I was just wondering, quite sincerely.

        :) DB

      • Mathias says:

        It would be great if you could finish the CI from Scratch series and show us how to put it all together and make a CMS!

        Im looking forward to see more of Web Dev Q&A!

  6. If you are using the Kohana PHP MVC Framework, I have a simple, easy-to-use module for including and using LESS in your projects. See http://github.com/jeremeamia/kohana-less.

  7. Kent says:

    This is definitely a cool new feature on NetTuts. That overflow: hidden trick is a gem!

  8. Giovanni says:

    Great idea! Looking forward to this series.

  9. Crysfel says:

    Hi Jeffrey, nice idea and very usefully :)

    In answer number one, what if the user doesn’t pass a callback? there’s going to be a runtime error, the solution is, before calling the “cb” function you should do something like this:

    cb = cb || function(){};
    cb();

    This way if “cb” function is null the empty function is executed.

    Just my two cents :)

  10. Sam Bowler says:

    If you use TextMate then the LESS extension is really great (http://github.com/appden/less.tmbundle). It will automatically compile whenever you save the LESS file providing you have the Ruby gem installed.

  11. This is great perfect idea since forums are always a pain to flip through.

  12. Oh freakin awesome. This is a great idea…now I just have to think of questions. I haven’t watched your video on LESS yet, but what are the differences between LESS and Sass 3 (besides the fact that LESS can now be implimented with javascript)…does one do more than the other? As far as I can tell the both have mixins, variables and such, but beyond that?

  13. Xcellence IT says:

    Hi, Just wondering if there is something similar like Less.app for Windows OS?

  14. Heam says:

    Hey Jeffrey,
    Could you please explain how to make rounded corner input for web search forms ? (using css with IE support)

  15. Flo says:

    @ Jeffrey:
    First of all -> great tipps and tricks (as always). My question (maybe a bit off-topic):

    At 3:39 (screencast) you resize the Coda window and this window and the live window fit perfectly side by side. How did you do that? What’s the name of this app?

    Thank’s!
    Flo

  16. Bali says:

    @ Jeffrey:

    In Where’s my Background? section.

    You set “overflow: hidden;” to show the background color in nav. We can also set “height: value” to show background color in nav.

    My Question is “what is different between overflow and height. Who is the better property for clearing float(left/right)”.

    • Jarryd C. says:

      I’d say setting a height value for the #nav ul element would be the way to go. If you set an overflow and then you want to add drop-downs later, they will either not show up or the whole ul will expand to fit the drop-down.

      Setting an overflow is still a viable option, none-the-less.

  17. Bryan says:

    Hi guys,

    My name’s Bryan. I wrote Less.app at http://incident57.com/less

    Version 2.0 is just around the corner and it’s awesome — rewritten to use LESS.js instead of Ruby, so it’s insanely fast. With options to ignore certain files, automatically compress outputted CSS, and preserve comments. Plus, a whole new, sexy UI.

    Should be out just about the same time Less.js goes live itself. I’m looking for beta testers, so if you’d like to give it a whirl, please shoot me an email: bryan at incident57 dot com.

    And Jeffery: thanks for the shout-out. I tried to find an email address for you, but you’re a hard guy to track down.

    • Jeffrey Way says:
      Author

      Thanks for the update Bryan — and thanks for the app. It’s very helpful. :) If you need to, you can email me at net@tutsplus.com.

    • Shane Parker says:

      Hi Bryan,

      I’ve been using the Less.app Coda plugin for two days now. I’ve been keeping track of Less applications for a while, but was never convinced that they’d save me time and it seemed like a hassle to settle on one and then get it working. Well, after two whole days of use, I can say this will save me boatloads of time.

      Can’t wait for the new version!

      -Shane

      • Bryan says:

        Hi Shane,

        Development on the Coda plugin is actually frozen. I made that before I built Less.app, which is a standalone application that does a lot more than just the plugin. I recommend you switch! Check it out at http://incident57.com/less

        The plugin won’t see any updates moving forward.

  18. Nathan says:

    Hi Jeffrey,

    In regards to the float. Couldn’t you set a width and a height to #nav? or is that bad practice?

    • Jeffrey Way says:

      It’s generally a bad practice to hard-code a height for your containers. If, for example, you added one two many navigation links, and it fell to its own line, this would break your layout.

      • Evan says:

        One other thing to note is that using overflow:hidden to clear floated elements won’t work in ie6 unless the wrapper element hasLayout.

        In the example above you can trigger hasLayout by using zoom:1
        #nav{ overflow:hidden; zoom:1; background-color:black; }

  19. Brandon says:

    Love all these new series’ you’re bringing us, Jeffrey. But please don’t forget about the older ones like Javascript from Null!

  20. Paishin says:

    I’ve been looking for a solution to the background problem for a while now. But I cant seem to find a proper one. While this solution is very good it depends on clear:both; attribute to achieve it. This in turn screws up the layout in case you have more elements next to the menu (i.e. the search bar).

  21. Zach Curtis says:

    Jeffery,
    Great screencast. I had a comment about the callback piece. It is important to note that you may have to chain callback’s if your first function runs another function and the callback relies on that first function to complete. In this case you use alert which is fine, but if doSomething() runs another function before cb that cb relies on, it will not work. I have found this to be a roadblock in templating and it gets confusing fast! Thanks again!

  22. matt says:

    this is great stuff! keep em’ coming jeff!!!!

  23. Sunny Singh says:

    HTML5 isn’t released yet, so I wouldn’t recommend saying to people to “clean your markup” by converting it to HTML5. Don’t get me wrong I have nothing wrong with it, but on many sites XHTML is still a better option (both doctype and markup).

    • Jeffrey Way says:
      Author

      If you can tell me one negative about using that cleaner markup, I’d be happy to advocate differently.

      • Shane Parker says:

        Hi Jeffrey,

        I have wondered if there are any disadvantages to this and the only thing I could come up with as a possible issue (although not tested) is the IE Box Model problem. Does shortening the DOCTYPE put IE6 into quirks mode? If so, the box model would revert to the ‘broken’ version (ie, height/width calculations not including padding/margins). Or is “” enough for IE6?

  24. I hacked together a command line version of Less.app for Windows, allowing Windows users to instantly compile less files on save in production instead of at run time.

Add a Comment

To add a code snippet to your comment, please wrap your code like so: <pre name="code" class="html">YOUR CODE</pre>. You can replace the class name with "js," "css," "sql," or "php." If there are any "<" or ">" within your code, please search and replace them with: &lt; and &gt; respectively.