RSS
 

Posts Tagged ‘jQuery’

Quick Tip – jQuery Newbs: Stop Jumping in the Pool

07 Oct

As editor of Nettuts+, I get to review a lot of code from tutorial submissions. Despite the fact that jQuery has been available for years now, there is still one frequent mistake that I see more than anything else.


Example #1

Consider the following bit of code:

$('.nav a').click(function() {
  $(this).hide();
  $(this).css('color', 'red');
  $(this).show();

  alert('something else');

  $(this).hide();

  return false;
});

The code above is overly complicated for a variety of reasons. Don’t worry over what the code actually does (it’s gibberish). Instead, I want you to look at all of those references to $(this).

Think of the DOM as a pool.

Think of the DOM as a pool. Remember when you were a kid, and would dive into the pool for coins, while your parents acted like they were watching? That will be our real-world comparision.

Every time you use $('.someClass'), jQuery jumps into the pool (DOM), and searches for that coin (or nodes). So, when you reference it multiple times within a function, that’s a lot of diving. Or, to cut the real-world comparison, it’s wasteful and unncessary. Why call upon jQuery if you don’t require it? You should perform what we call “caching.”

$('.nav a').click(function(e) {
   var anchor = $(this);

   anchor
      .hide()
     .css('color', 'red')
     .show();

   alert('something else');

   anchor.hide();

   e.preventDefault();

});

This is much cleaner. While modern browser engines are incredibly fast these days, and will make up for your poor coding as best as possible, you should still strive to write efficient code, and keep from wasting all that energy jumping in the pool. Now, technically, if you pass jQuery a DOM node, like this, it doesn’t re-query the DOM. It simply returns a jQuery object.

Just because the performance difference between the two will honestly be negligible, we write clean code for ourselves.

Example 2

Let’s consider a slightly more complicated example: tabs.

$('.tabs li').css('position', 'relative');

$('.tabs li').click(function() {
   $('.tabs li').removeClass('active');
   $(this).addClass('active');
   $(this).load('someHref', function() {} ); // example
   $(this).css('top', '1px');
});

This code is all over the place. It’s ugly, and inefficient. Fix number one is to get rid of all that CSS. You’d only place styling in your JavaScript if the values were created dynamically. For example, if you need to calculate the precise location an element should be on the screen, you could use .css('left', calculatedValue). In this case, it can all be exported to an external stylesheet. That leaves us with:

$('.tabs li').click(function() {
   $('.tabs li').removeClass('active');
   $(this).load('someHref', function() {} ); // example
   $(this).addClass('active');
});

Next, again, why do we keep querying the DOM for .tabs li and $(this)? Stop jumping in the pool. Let’s “cache” the location of .tabs li.

var tabs = $('.tabs li');

tabs.click(function() {
   tabs.removeClass('active');
   $(this).load('someHref', function() {} ); // example
   $(this).addClass('active');
});

Better, but we’re still calling $(this) twice, which isn’t a huge deal. But, from my experiences, if you don’t nip it in the bud early, this number quickly increases.

var tabs = $('.tabs li');

tabs.click(function() {
   var tab = $(this);
   tabs.removeClass('active');
   tab.addClass('active')
     .load('someHref', function() {} ); // example
});

Filtering

Another (slightly less optimized) option would be to use filtering.

var tabs = $('.tabs li');

tabs.click(function() {
   tabs.removeClass('active')
       .filter(this)
       .addClass('active')
       .load('someHref', function() {} ); // example
});

The difference in this case, is that, rather than referencing $(this), we’re using the filter() method to reduce the collection of list items down to only the one that was clicked.


What You Should Take Away

Yes, the world will not end if you reference $('.tabs) several times within a function. JavaScript engines are super fast these days. If you were to test the performance of doing so thousands of times, the difference in execution might be a couple hundred milliseconds. But still, the question remains: why would you?

Sometimes, when we use massive abstractions like jQuery, it’s easy forget that $('.tabs') is an actual function that runs a good bit of code. It should also be noted that these concepts apply to JavaScript in general – not just jQuery.

Use the caching techniques described above to write cleaner code…for yourself.

 
 

Quick Tip – jQuery Newbs: Stop Jumping in the Pool

07 Oct

As editor of Nettuts+, I get to review a lot of code from tutorial submissions. Despite the fact that jQuery has been available for years now, there is still one frequent mistake that I see more than anything else.


Example #1

Consider the following bit of code:

$('.nav a').click(function() {
  $(this).hide();
  $(this).css('color', 'red');
  $(this).show();

  alert('something else');

  $(this).hide();

  return false;
});

The code above is overly complicated for a variety of reasons. Don’t worry over what the code actually does (it’s gibberish). Instead, I want you to look at all of those references to $(this).

Think of the DOM as a pool.

Think of the DOM as a pool. Remember when you were a kid, and would dive into the pool for coins, while your parents acted like they were watching? That will be our real-world comparision.

Every time you use $('.someClass'), jQuery jumps into the pool (DOM), and searches for that coin (or nodes). So, when you reference it multiple times within a function, that’s a lot of diving. Or, to cut the real-world comparison, it’s wasteful and unncessary. Why call upon jQuery if you don’t require it? You should perform what we call “caching.”

$('.nav a').click(function(e) {
   var anchor = $(this);

   anchor
      .hide()
     .css('color', 'red')
     .show();

   alert('something else');

   anchor.hide();

   e.preventDefault();

});

This is much cleaner. While modern browser engines are incredibly fast these days, and will make up for your poor coding as best as possible, you should still strive to write efficient code, and keep from wasting all that energy jumping in the pool. Now, technically, if you pass jQuery a DOM node, like this, it doesn’t re-query the DOM. It simply returns a jQuery object.

Just because the performance difference between the two will honestly be negligible, we write clean code for ourselves.

Example 2

Let’s consider a slightly more complicated example: tabs.

$('.tabs li').css('position', 'relative');

$('.tabs li').click(function() {
   $('.tabs li').removeClass('active');
   $(this).addClass('active');
   $(this).load('someHref', function() {} ); // example
   $(this).css('top', '1px');
});

This code is all over the place. It’s ugly, and inefficient. Fix number one is to get rid of all that CSS. You’d only place styling in your JavaScript if the values were created dynamically. For example, if you need to calculate the precise location an element should be on the screen, you could use .css('left', calculatedValue). In this case, it can all be exported to an external stylesheet. That leaves us with:

$('.tabs li').click(function() {
   $('.tabs li').removeClass('active');
   $(this).load('someHref', function() {} ); // example
   $(this).addClass('active');
});

Next, again, why do we keep querying the DOM for .tabs li and $(this)? Stop jumping in the pool. Let’s “cache” the location of .tabs li.

var tabs = $('.tabs li');

tabs.click(function() {
   tabs.removeClass('active');
   $(this).load('someHref', function() {} ); // example
   $(this).addClass('active');
});

Better, but we’re still calling $(this) twice, which isn’t a huge deal. But, from my experiences, if you don’t nip it in the bud early, this number quickly increases.

var tabs = $('.tabs li');

tabs.click(function() {
   var tab = $(this);
   tabs.removeClass('active');
   tab.addClass('active')
     .load('someHref', function() {} ); // example
});

Filtering

Another (slightly less optimized) option would be to use filtering.

var tabs = $('.tabs li');

tabs.click(function() {
   tabs.removeClass('active')
       .filter(this)
       .addClass('active')
       .load('someHref', function() {} ); // example
});

The difference in this case, is that, rather than referencing $(this), we’re using the filter() method to reduce the collection of list items down to only the one that was clicked.


What You Should Take Away

Yes, the world will not end if you reference $('.tabs) several times within a function. JavaScript engines are super fast these days. If you were to test the performance of doing so thousands of times, the difference in execution might be a couple hundred milliseconds. But still, the question remains: why would you?

Sometimes, when we use massive abstractions like jQuery, it’s easy forget that $('.tabs') is an actual function that runs a good bit of code. It should also be noted that these concepts apply to JavaScript in general – not just jQuery.

Use the caching techniques described above to write cleaner code…for yourself.

 
 

Sliding Background Image Menu with jQuery

03 Jul



View demoDownload source
Today we want to share another jQuery menu with you. This menu will have several panels, each one corresponding to a different background image that will show on all panels when we hover over a panel label. Also, a submenu will slide out from the bottom. This menu comes with some configuration possibilities, such as the size of the image, the hover effect and custom default states.

The idea of this navigation is based on the Beautiful Background Image Navigation with jQuery, a tutorial that had a similar effect. Since it was very popular and a lot of our readers asked for some very useful additions, we decided to revamp it and make it easier to customize.

The beautiful gastronomy photography is by Manoel Petry:
Manoel Petry’s Flickr Photostream
Manoel Petry’s Website
The images are licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 2.0 Generic License.

Examples

Take a look at all the examples (you can also navigate from them to all the other demos):

The HTML structure consists of the “sbi_container” which will have all the panels inside:

<div id="sbi_container" class="sbi_container">
	<div class="sbi_panel" data-bg="images/1.jpg">
		<a href="#" class="sbi_label">About</a>
		<div class="sbi_content">
			<ul>
				<li><a href="#">Subitem</a></li>
				<li><a href="#">Subitem</a></li>
				<li><a href="#">Subitem</a></li>
			</ul>
		</div>
	</div>
	<div class="sbi_panel" data-bg="images/2.jpg">
		...
	</div>
	...
</div>

The “data-bg” attribute contains the path to the background image that will appear when hovering over the label of the respective panel.

Let’s take a look at an example for using the alternating vertical up/down sliding effect:

$('#sbi_container').bgImageMenu({
	defaultBg	: 'images/default.jpg',
	menuSpeed	: 300,
	border		: 1,
	type		: {
		mode		: 'verticalSlideAlt',
		speed		: 450,
		easing		: 'easeOutBack'
	}
});

The following parameters can be used/set:
defaultBg: the default image shown when no label is hovered
pos: if no defaultBg set, pos will indicate the panel that should be shown/open
width: the width of the container and the images (they should all be of the same size)
height: the height of the container and the images
border: the width of the margin between the panels
menuSpeed: the speed with which the menu should slide up

mode: the type of animation; you can use def | fade | seqFade | horizontalSlide | seqHorizontalSlide | verticalSlide | seqVerticalSlide | verticalSlideAlt | seqVerticalSlideAlt
speed: the speed of the panel animation
easing: the easing effect for the animation
seqfactor: delay between each item animation for seqFade | seqHorizontalSlide | seqVerticalSlide | seqVerticalSlideAlt

We hope you find this little menu interesting and useful, enjoy!

View demoDownload source

Share and Enjoy:Diggdel.icio.usFacebookLinkedInRedditRSSTwitterGoogle BookmarksStumbleUponTechnoratiDZoneemailblogmarksDesign FloatDiigoFriendFeedGoogle BuzzIdenti.caMisterWongNewsVinePing.fmPlurkPosterousSlashdotSuggest to Techmeme via TwitterTumblr

 
 

10 Useful Scripts of Calendar for Web Developers

17 Mar
Most popular blogs and personal websites decorated by beautiful calendars. A beautiful calendar in website is so essential to track back new, specified and important older information’s. This article will show you some useful scripts to use in your blog or website. Are you looking to contribute to our design community? Suggest a link to [...]
 
 

Quick Tip: Display Elements Sequentially with jQuery

13 Dec

In this video quick tip, I’ll teach you how to add a bit of flair to your page, by displaying a set of elements sequentially. While there are numerous ways to accomplish this task, today, we’ll review one technique that uses recursive functions.

// Wrapping, self invoking function prevents globals
(function() {
   // Hide the elements initially
   var lis = $('li').hide();

   // When some anchor tag is clicked. (Being super generic here)
   $('a').click(function() {
      var i = 0;

      // FadeIn each list item over 200 ms, and,
      // when finished, recursively call displayImages.
      // When eq(i) refers to an element that does not exist,
      // jQuery will return an empty object, and not continue
      // to fadeIn.
      (function displayImages() {
         lis.eq(i++).fadeIn(200, displayImages);
      })();
   });
})();

Conclusion

What makes this usage effective is the fact that, when lis.eq(i) refers to an element that doesn’t exist in the wrapped set, an empty jQuery object will be returned. When this happens, the subsequent methods in the chain (fadeIn) will never be called.

 
 

icelab.com.au

04 Nov

icelabcomau

This is a really beautiful website, the colors and light textures mixed in with some great illustration work make for a super great experience. Looking at the experience of the site there are lots of great little spots that just shine, like the mouse over on the logo and the “back to top” link in the footer area. The sub pages have enough variance to keep it interesting too. Really great site.

 
 

lostworldsfairs.com/moon/

12 Oct


This is the “Moon” website or page from the Lost World’s Fairs website project designed by Jason Santa Maria.

I love this design for “Moon”, the visual depth is really nice. I also love the movement as you scale your browser window down and then back up. The little illustrations are sweet too. It’s really hard to believe this is done with web fonts.

 
 

Useful Collection of Cheat-Sheet Desktop Wallpaper for Web Designers

07 Oct

Typical cheatsheets tend to be over-sized documents, far too large to be viewed in its entirety on a desktop and not too handy for the super-fast reference that is needed. To get the full benefit of any cheatsheat, your only real option is to print it out and keep it close at hand. Wouldn’t it be nice if there was an easier way, a quicker way. Of course there is – what good be handier than having a cheatsheet set as your desktop wallpaper? Always there for quick reference, no need to print it out and no need to scroll through an over-long document.

In this post we have rounded up a selection of cheatsheet wallpapers, in various sizes, covering various technologies, like CSS, HTML5, WordPress, Javascript and many more.

WordPress Help Sheet Wallpaper

WordPress Help Sheet Wallpaper
The WordPress Help Sheet Wallpaper is a simple desktop wallpaper listing Basic Template Files, PHP Snippets for the Header, PHP Snippets for the Templates, Extra Stuff for WordPress, based on the WPCandy WordPress Help Sheet.
Download: 2560x1600px.

Drupal Cheat Sheet Desktop Wallpaper

Drupal Cheat Sheet Desktop Wallpaper
The Drupal Cheat Sheet Desktop Wallpaper is a desktop wallpaper that features the most popular variables of the open source content management system Drupal.
Download: 1024x768px – 1280x800px – 1440x900px – 1680x1050px – 1920x1200px.

HTML5 Canvas Cheat Sheet

HTML5 Canvas Cheat Sheet
The information on this wallpaper is pretty much just a copy of what is found in the WHATWG specs, just condensed and a little bit easier to read. There are virtually no explanations, and no examples other than some graphics for compositing values. It's basically just a listing of the attributes and methods of the canvas element and the 2d drawing context.
Download: 1388x1027px.

CSS Cheat Sheet Wallpaper in Helvetica

CSS Cheat Sheet Wallpaper in Helvetica
This is the very popular CSS cheat sheet in Helvetica from styl.eti.me. Simplistic in appearance, but very useful for quick referencing. Unfortunately we can not find a working download link for this cool wallpaper, but the good news is they do have a PSD version available. So download it and resize.
Download: CSS Cheat Sheet Wallpaper in Helvetica.

TextMate Shortcuts Wallpaper

TextMate Shortcuts Wallpaper
Here is a TextMate wallpaper that will guide you through some of its powerful features and help you get a handle on all of the keyboard shortcuts. The PSD file is also available.
Download: 1280x800px – 1920x1200px.

Yahoo! UI (YUI) Cheat Sheets as Wallpaper

Yahoo! UI (YUI) Cheat Sheets as Wallpaper
Yahoo! provides a number of cheat sheets for their YUI library widgets however these are all in PDF format and not usable as wallpaper. However, here you will find all of those cheatsheets converted to PNG images of various sizes all for your desktop.
There are wallpapers available for Animation, Calendar, Connection Manager, Dom Collection, Drag & Drop Event, Utility & Custom Event Logger, Slider and TreeView. And all are available in the following desktop sizes: 1400x1050px, 1280x960px, 1165x900px and 1024x768px.
Download: Yahoo! UI (YUI) Cheat Sheets as Wallpaper.

jQuery 1.3 Cheat Sheet Wallpaper

jQuery 1.3 Cheat Sheet Wallpaper
Download: 1440x900px – 1680x1050px – 1920x1200px.

Prototype Dissected Wallpaper

Prototype Dissected Wallpaper
If you need a little help in getting to know Prototype a little better and some help in understanding how the code works, then this is the wallpaper for you. You have a choice of either a dark or white wallpaper, and are available in these sizes: 1280x960px and 1440x900px.
Download: 1280x960px (Dark) – 1440x900px (Dark) – 1280x960px (White) – 1440x900px (White).

Git Cheat Sheet Wallpaper

Git Cheat Sheet Wallpaper
Download: 1100x850px – 3300x2550px.

A Themer's Cheatsheet Wallpaper

A Themer's Cheatsheet Wallpaper
A Themer's Cheatsheet Wallpaper is a quick refresher of web design fundamentals directly on your desktop. It is available for download in several different colors and the original SVG has been released to the Public Domain.
Download: 1280x800px (Blue) – 1280x800px (Red) – 1280x800px (Black) – 1280x800px (Green).

Font Anatomy Wallpaper

Font Anatomy Wallpaper
Download: 1920x1200px.

SEO Wallpapers

SEO Wallpapers
Think of it as a desk reference checklist that is always at your fingertips. From pre-campaign to reporting, the basics (and more) are right here for you to put directly on your desktop.
Download: 1024x768px – 1280x960px – 1280x1024px – 1440x900px.

Periodic Table of Typefaces

Periodic Table of Typefaces
Download: 1024x768px – 1280x800px – 1280x1024px – 1440x900px – 1680x1050px – 1920x1200px.

Color Theory Quick Reference Poster

Color Theory Quick Reference Poster
The Color Theory Quick Reference Poster for Designers has all of the basics of color theory contained in one place – specifically, a cool infographic-esque poster. This way, you can quickly reference things that may have slipped to the back of your mind since design school.
Download: 1280x800px – 1440x900px – 1680x1050px – 1920x1200px.

Web Designer Wallpaper

Web Designer Wallpaper
Download: 1280x1024px (White) – 1280x1024px (Dark) – 1680x10050px (Dark) – 1280x1024px (White).

You might also like…

14 Essential WordPress Development and Design Cheat Sheets »
17 Productive Photoshop Cheatsheets and Reference Cards to Download for Free »
The Best Cheat Sheets for Web Designers and Developers (From CSS, Ajax, Perl, Vbscript…) »
CSS References, Tutorials, Cheat Sheets, Conversion Tables and Short Codes »
20 CSS3 Tutorials and Techniques for Creating Buttons »
50 Useful Tools and Generators for Easy CSS Development »
50 Essential Web Typography Tutorials, Tips, Guides and Best Practices »
The Blueprint CSS Framework – Tutorials, How-to Guides and Tools »

 
 

Microsoft Gets a Clue, Adopts jQuery

29 Sep

Could Microsoft be learning the way things work on the web? That big software company in Redmond will include JavaScript framework jQuery in its development environment. At the same time, Nokia announced that it will use jQuery for its mobile-browser development. That’s two more big companies to join Google, Amazon and thousands of other sites using jQuery.

Microsoft has long struggled to keep up with advances in JavaScript. In July the company announced an Ajax roadmap, which looked like Microsoft was going to eventually re-create all the features already in popular frameworks. Instead, Microsoft is going to incorporate someone else’s code, and it’s open source code at that.

How’s this for cool–Intellisense support for jQuery in ASP.NET:
Intellisense code includes jQuery

This is a great move by Microsoft to avoid creating its own jQuery-like framework. The company that seems to always require others to change is adapting to the way things already are on the web. It couldn’t have made a better choice in jQuery, which is a fast, nimble framework, two adjectives not often used to describe anything related to MS web development.

Scott Hanselman has a good overview of how jQuery/ASP.NET code looks. If you aren’t a .NET developer, but you’d like to use jQuery, check out my jQuery tutorial.

[Screenshot by Scott Hanselman]

See also:

 
Comments Off on Microsoft Gets a Clue, Adopts jQuery

Posted in Uncategorized

 

Load Content When Users Hit Page Bottom For Endless Scrolling

08 Sep

There’s a snazzy new feature we’ve seen a couple places that we just had to look into. When users reach the bottom of a page, more content is loaded. So, rather than users closing the window (or having to click a “next page” link), you can given them more to read. For sites with a significant amount of content, this makes for endless scrolling.

Example of endless scrolling

There’s a short delay, while an Ajax call, retrieves more content and pastes it below. Otherwise, it’s a smooth transition to the next bundle of blog posts, photos, or links. You can see endless scrolling in the wild at lifestreaming service Soup.io, link-sharing site DZone, Google Reader (if you have an account), or this demo of the technology. Just scroll to the bottom of any of those pages.

If this is something you want to implement there’s a JQuery implementation for endless scrolling. As with many snazzy JavaScript tricks, you’ll need a server-side component to send the next set of data.

See also:

 
Comments Off on Load Content When Users Hit Page Bottom For Endless Scrolling

Posted in Uncategorized