Archive

Posts Tagged ‘html’

Quick Tip: The HTML5 Context Menu Attribute

February 13th, 2013 Comments off

In this quick tip I want to talk to you about one of HTML5s hidden beauties, the contextmenu. You have probably never heard of it before, but I assure you it is one of those attributes that could be really useful in certain situations.

What is the contextmenu attribute you may ask? Basically, it allows you to add different options to a browsers ‘right-click menu’ with just a few lines of HTML and will even work with Javascript disabled. Although, and very sadly, it currently only works in Firefox.

Let me show you how it works:

Context Menu Demo

Using contextmenu is a lot simpler than you may think. All you need is to add the contextmenu attribute like so:

As you can see you can add it just like you would add any id or class.

Next we create the menu:




As you can see the id of the menu must match the name of the contextmenu, this gives more flexibility allowing you to have more than one menu item on the page within different sections.

Next we will add the menu items. Firstly, I will add one menu item with just plain text and an icon, secondly I will add a link for sharing the current page on Facebook, and the third menu item will be a link for refreshing the page, creating a simple contextmenu with three menu items:


 
  
    
  

You can also create sub menus just by adding another menu tag inside the existing one, like so:


 



    
  

As you can see with basic HTML5 you can create something really useful. But please be very careful when using it, as it is currently only supported by Firefox.

Do you have a ‘Quick Tip’ you would like to share with our readers? If so, get in touch with us here: mail@speckyboy.com.

Original from: http://feedproxy.google.com/~r/speckboy-design-magazine/~3/GCcCSGdMkN0/

Categories: Web development Tags: ,

Improving Your Work-Flow – Separate Your Mark-Up From Your Logic!

January 4th, 2013 Comments off

In this tutorial I’m going to explain a technique that allows you to utilize a template file for all of your HTML needs! No longer will you need to ‘echo’ strings from inside your functions, or worry about dropping in and out of PHP just to output some mark-up.

I’ve spent many years utilising MVC frameworks (such as Zend and nowadays Laravel) where it’s a best practice to separate your ‘programming logic’ (functions or methods) from your ‘view’ (the resulting HTML mark-up). This always leads to a more maintainable code-base and it’s actually a lot easier to write. Having this background prompted me to come up with a similar solution when developing plugins for WordPress! It’s nothing too fancy – it’s just a little ‘helper’ that will allow you to remove all the HTML snippets and awkward ‘escaping’ from your functions and place them safely away in their own ‘template’ file.

So, I hope this tutorial sounds interesting to you and without further ado, let’s begin!

/>

Step 1 Understanding What We’re Going to Improve

Let’s kick this tutorial off by taking a look at exactly what we’re going to improve upon.

It’s very common to see something like this within a plugin : (this snippet actually comes from one of my own tutorials on this site :p)

add_shortcode( 'faq', function() 
	$posts = get_posts( array(  // Get the FAQ Custom Post Type
		'numberposts' => 10,
		'orderby' => 'menu_order',
		'order' => 'ASC',
		'post_type' => 'faq',
	));
	$faq = '
'; // Open the container foreach ( $posts as $post ) // Generate the markup for each Question $faq .= sprintf( ( '

%1$s

%2$s
' ), $post->post_title, wpautop( $post->post_content ) ); $faq .= '
'; // Close the container return $faq; // Return the HTML. });

What’s Wrong With It?

Well nothing, really. But it could be cleaner, easier to scale and more maintainable!

Running from top to bottom, we can see that all within a single function we are :

  1. Querying the database for posts of a certain type
  2. Assigning an HTML string to a variable
  3. Performing a loop and concatenating further markup to the string
  4. Returning the built-up string

Now you may very well be looking at this and thinking “Big deal! It’s only a few lines of HTML, what’s the problem?” In some respects you’re well within your rights to think like that. But remember, it’s only 17 lines of code at the moment – what happens when you expand/improve the plugin? What happens when your plugin grows to 50/100/1000 lines of code (or more!). Will you still be happy having HTML strings dotted around your function in various places? What happens when you want to output some HTML that needs some awkward ‘escaping’ to work properly within your PHP code?

Hopefully you can see that this approach to creating and outputting HTML Markup can get very problematic! Not to mention that it becomes very hard to maintain and improve the HTML when it’s just scattered around.

So, with all this in mind, I’ve taken it upon myself to change the way you think about outputting HTML in WordPress. Forever.

/>

Step 2 Building the View Renderer Plugin

Ok, let’s get cracking with this.

Create the Files & Folders

  1. Create a new plugin folder called View
  2. Inside that folder, create the plugin file view_renderer.php
  3. Now create a file called View.php – This will be our class

Include the Class

Our plugin is simple, it just includes the View class so that we can use it in any of our other plugins.

/* view_renderer.php */
include('View.php');

Ok, now that we’ve included the View class, it’s time to actually build it.

The View Class

Here we have a class called View with a single static function called render (this will allow us to use the syntax View::render( $template ) from anywhere within our plugins) and it takes two parameters:

  1. $filePath – The path to the template file. Don’t forget we are going to keep our templates within the View folder that we created earlier
  2. $viewData – Any variables that we would like to have access to within the template (much more on this later)

Copy the code below into View.php:


So What Exactly Is Going on Here?

  1. First of all we are checking if the $viewData varible has a value (i.e. did we send anything to be used in the template?). If it does, we extract the contents (more on this later)

  2. Then we are making use of PHP’s output buffer. It allows us to parse a PHP file and save the contents to a variable

  3. Finally we return the string

Note: Don’t forget to activate the plugin now from within the Admin panel

Seems pretty simple huh? Exactly! But whilst it appears to just be a very simple little function, it actually affords us the luxury of being able to write our plugins in a super-organized, scalable, maintainable fashion. Please, allow me to demonstrate…

/>

Step 3 A Real-World Example

Let’s create a simple plugin called Slider

** Note: This is for demonstration purposes only. Feel free to use your own plugin here.

  1. Create a folder called Slider
  2. In that folder, create a file called Slider.php
  3. Copy the code below into Slider.php

Add a Shortcode

OK, now we’re going to add a shortcode that will fetch the latest 5 posts and display them in a list with the title and content. (For the sake of brevity, we’ll be adding our plugin class and our action hooks into the same plugin file, but please don’t do this in ‘real-life’ :p )

/**
 * Add the Shortcode (PHP 5.3 and above)
 */
add_shortcode( 'slider', function() 
	return Slider::display();
 );

That will allow us to simply use [slider] in any post/page and it will output the result of Slider::display()

Add the Slider Class & display() Method

class Slider 
	public static function display() 
		// Return HTML HERE.
	
}

Get the Latest 5 Posts.

/*
 * Get the latest 5 posts
 */
public static function display() 
	$posts = get_posts( array( 'numberposts' => 5 ) );

Now we have an array of post objects and we’re ready to be building up our HTML by looping through them. But we are not going to simply begin insert HTML strings into our function here! Instead we are going to pass the array of objects to a template file and have all the HTML generated out of harm’s way.

Create the Template

  1. Create a folder called templates
  2. Inside that folder, create a file called 01.template.php

This template will hold all of our markup and will allow us to access the data we send to it later.

Sending Data to the Template

Every time we want to use any variables within our templates, we can simply send them by setting a value in the $viewData array. Anyone familiar with using MVC frameworks will feel very at home with this approach.

	$viewData = array( 'posts' => $posts );

The array key here (‘posts‘) is important because that’s how we’ll refer to the data from within the template. (You can call this whatever you like, but stick to something that makes sense.)

Building the Template

Ok, so we’ve looked at how to retrieve the latest 5 posts and how to send that array of objects to the template, it’s now time to flesh out the template file.

	
  • post_title ?>

    post_content ?>

Ah! How nice does it feel to have all of that markup in its own seperate file, away from our data retrieval and programming logic? Great, I know! The most important part of this approach is that we are only ever ‘accessing’ data from variables within the template. All the ‘logic’ should be done within the method that calls the template. This leads to a very nice workflow as you have complete seperation of concerns.

Just imagine how easy it will be now when you’re ready to build upon this plugin. No more concatenating strings and escaping characters within functions.

Returning the Rendered Template

Ok, we’ve seen all the component parts, let’s see how it all fits together to allow us to render a template and get a string back (that we can then return to our shortcode):

  1. First we need to store a reference to our template in a static property
  2. Then we need to check that the View class exists
  3. Then we generate the full path to our template file by grabbing a reference to the current plugin directory and concatenating our static property $template
  4. Finally, we call our View::render() method and pass it the two parameters needed

In this case, we return the result of the rendered template because that’s how shortcodes work. But if you were needing to echo the results instead (for example, when you create an Admin page, the callback expects your output to be printed out directly), then simply replace return with echo.

The display() Method in Full

	class Slider 
		static $template = '/templates/01.template.php';
		public static function display() 
			if ( class_exists( 'View' ) ) 
				// Get the last 5 posts
				$posts = get_posts( array( 'numberposts' => 5 ) );
				// Set view Data
				$viewData = array(
					'posts' => $posts
				);
				// Get the full path to the template file.
				$templatePath = dirname( __FILE__ ) . static::$template;
				// Return the rendered HTML
				return View::render( $templatePath, $viewData );
			
			else 
				return "You are trying to render a template, but we can't find the View Class";
			
		}
	}

I hope you can appreciate the level of organization this approach will afford you! Now your display function is only responsible for collecting the data that it needs and returning the result of the rendered template.

/>

Taking it Further

Our example above is about as basic as it gets. Even so, it’s still a vastly improved work flow. Now let’s have a look at another example that shows how helpful it can really be.

Say, for example, your plugin makes use of a custom meta box. To do that we would need to:

  1. Add a constructor function to the Slider class
  2. Add a method to add the metabox to every post
  3. Add a callback method to render the HTML for the meta box
  4. Add the appropriate hook in the plugin file to instantiate the class only when adding/editing posts
  5. Finally, we would add a template file as we did earlier, and add it as a property at the start of the class
	class Slider 
		static $metaBox = '/templates/metabox.template.php';
		public function __construct() 
			add_action( 'add_meta_boxes', array( $this, 'add_some_meta_box' ) );
		
		/**
		 * Adds the meta box container
		 */
		public function add_some_meta_box() 
			add_meta_box(
				'some_meta_box_name',
				'Some Meta Box Headline',
				array( $this, 'render_meta_box_content' ),
				'post',
				'advanced',
				'high',
			);
		
		/**
		 * Render Meta Box content
		 */
		public function render_meta_box_content() 
			/** From the Codex **/
			echo '

TEST OUTPUT - this gets rendered inside the meta box.

'; } // class // add the action hook function call_Slider() return new Slider(); if ( is_admin() ) add_action( 'load-post.php', 'call_Slider' );

Take a look at the render_meta_box_content method there. It’s the perfect opportunity to use the View Renderer! Imagine a more realistic example like this:

	/**
	 * Render Meta Box content
	 */
	public function render_meta_box_content( $post ) 
		$name = get_post_meta( $post->ID, "name" );
		$fieldName = static::$fieldName;
		echo '

Your name:

'; echo ''; echo ''; echo '';

Urg! Sure, it gets the job done, but it’s so difficult to do it this way! How about we utilize our View Renderer instead.

	/**
	 * Render Meta Box content
	 */
	public function render_meta_box_content( $post ) 
		$viewData = array(
			'name'  => get_post_meta( $post->ID, 'name' ),
			'field' => static::$fieldName
		);
		$templatePath = dirname( __FILE__ ) . static::$metabox;
		echo View::render( $templatePath, $viewData );
	

And in the template file:

	

Your name:

It might only seem like a very small benefit in this example. But trust me, if you keep your concerns separate like this, you’ll become a far better WordPress developer pretty quickly.

/>

Conclusion

I think by now you probably have a good understanding of what we are trying to achieve here and I urge you to try using this technique when building plugins in the future. Hopefully you’ll find ‘separation of concerns’ to be of benefit to you.

Tutorial Notes:

  • Although we made the View Renderer into a plugin by itself, you could quite easily just add it into existing plugins instead. This will remove the extra step of having to ensure the plugin is activated before you use it anywhere.
  • You are not limited to the use-cases explained in this tutorial, it can be used wherever you would normally output HTML (How about using a template file to output some ‘in-line’ JavaScript? or how about some specific CSS rules based on options retrieved from the database?)

I’d be interested to know what uses you’ve found for this technique, so please share in the comments :)

Original from: http://wp.tutsplus.com/tutorials/creative-coding/improving-your-work-flow-separate-your-mark-up-from-your-logic/

Quick Tip: HTML in Image Captions

November 11th, 2012 Comments off

We will find out what this new media improvement means in practice!

Good news! For this functionality you won’t even need a plugin, because when WordPress recently released version 3.4.x, this feature was introduced.

You can read about other changes too in the Codex.

When you insert an image into a WordPress page or post you can make a caption for it. Each inserted image can have its own caption and can use standard HTML tags to format it (of course you can leave it empty then it won’t have a caption at all).

The tags you can use are by default the same as the ones available in comments.

For example you can have bold text with , italicized text with and crossed out text with .

Please note that WordPress uses a light gray style for the background and dark gray for text by default. These CSS class selectors are .wp-caption and .wp-caption-text.

If you want to use your custom styles then include them in the theme’s CSS (usually in style.css).

In our case the theme’s style is the following.

.wp-caption 
	background: #F1F1F1;
	line-height: 18px;
	margin-bottom: 20px;
	padding: 4px;
	text-align: center;

.wp-caption-text 
	color: #888;
	font-size: 12px;
	margin: 5px;

Note that you can always change the caption if you click on the picture in the post editor then clicking on Edit image.

The HTML code I’m using is this:

This text is italicized. And this is bold.
/>

Examples in Pictures

Insert image box in WordPress admin />Insert image box in WordPress admin
Caption look in editor />Caption look in editor
Caption look on the site />Caption look on the site

Original from: http://wp.tutsplus.com/articles/tips-articles/quick-tip-html-in-image-captions/

Connecting a WordPress Domain to Google Apps

May 13th, 2012 Comments off

At WP Engine, we are often asked for email hosting recommendations. Unless it’s an enterprise client with hundreds or thousands of accounts, we recommend Google Apps for email. Gmail has done email so well that it doesn’t make sense to get email anywhere else, especially when gmail is free.

This tutorial will help you set up Gmail for a unique domain name for your business, blog, or whatever you’ve built on WordPress: yourname@yourdomain.com.


Step 1 Specify the Domain for Google

To start out, visit the Google Apps c-panel at https://www.google.com/a/cpanel/standard/new3, and specify the domain you’d like to use for your email address. Type your domain into the field, and hit submit.

From here, you can fill out the rest of the form with information about your business and accept the terms and conditions. This is fairly straightforward information, including a physical address, and business size.

Note: Once you’ve submitted this page, if you’re signed into your normal Gmail account, you will be prompted to either cancel the request or to switch Gmail accounts using the Google Control Panel.

You want to switch accounts. Do not cancel the request. Once you’ve accepted it, you’ll go right on to Step 2.


Step 2 Express Install

First, you need to choose whether you want to do the Express Install, ideal for on person installs, or the Custom Install, where you can test out various apps for a few different users.

For our purposes, we’ll go ahead and do the Express Install. It takes about 30 minutes, and involves verifying domain ownership, setting up users and groups, and mobile access.


Step 3 Verifying Domain Ownership

This is the longest part of the tutorial, so bear with me and we’ll get through it.

In order to prove that you actually own the domain and have legal rights to send and receive email from the domain, you have to verify your domain. This prevents mischievous folks from registering email addresses like yourname@cnn.com, or thepresident@whitehouse.gov.

You can select various ways to prove ownership, including using FTP to upload an HTML file to your site, adding tags to the head of your site, and the way that we’re going to do it: using a plugin!

Before this plugin existed, it was cumbersome to validate your domain, because none of the above methods are straightforward for the average user. Plugins are part of what make WordPress so great for so many people.

Note: You don’t have to do anything else inside Google Apps at this point.

Log in to your WordPress Dashboard, and select Plugins -> Add New.

Then search for “Google Site Verification Plugin. Click “install now” to install the plugin to your site.

You’ll go to a status screen that tells you the plugin has been successfully installed. Now you have to activate the plugin. Select “activate plugin,” and you’ll be taken back to your installed plugins list.

In order to verify your domain, find the google site verification plugin, and click “Verify.”

You’ll arrive at the site verification start dialogue. Click “Start Verification.”

You’ll be taken to a Google page that explains a third party, WordPress, is requesting permission to access your account. Select continue.

Note: it doesn’t matter if you’re signed into the email account you wish to verify. Any Gmail account will suffice to validate the domain.

Then Google will ask you if you want to grant access to the plugin. Select “Grant Access.”

Awesome! You’re back in your WordPress dashboard, and should be looking at the screen telling you that your domain has been verified!

You now have access to webmaster tools for your site, and can manage a host of Google Apps from this dashboard, including analytics, and Google Docs.


Summary

From here, it’s a simple matter of signing into your new gmail account and setting up the account the way you want it. I have all my email sent to the same inbox, but you may want to separate them out, depending on how you organize your work and your life.

Original from: http://wp.tutsplus.com/tutorials/hosting/connecting-a-wordpress-domain-to-google-apps/

We have 10 Shock Bundles (value $129 each) to giveaway – Comment to Enter

March 25th, 2012 Comments off

For this weeks giveaway we have 10 Premium Shock Bundles, courtesy of the guys behind Theme Nation.

All you have to do for a chance of winning one of these books is leave a comment below telling us why you would like to win this bundle.

The Shock Bundle

The bundle (usual cost $129) includes a whopping 107 Premium WordPress Themes, 30,000 Iconshock icons, 28,577 additional icons (14,000 icons for Android, 14,000 iPhone icons, 427 credit card icons and 150 social icons), 75 XHTML templates, 50 web design sets, 25 vector mascots sets, 500 logo templates and much, much more! Its perfect for any web designer.

Here is a preview of the Bundle:

How to win a bundle

This competition will run for the next 7 days (ending on the 1st of April 2012) and all you have to do for a chance to win is leave a comment below telling us why you would like to win this bundle.

Winners will be selected completely at random and will be informed within a few days of the competition ending via email.

Good luck to everyone :)



Original from: http://feedproxy.google.com/~r/speckboy-design-magazine/~3/NMcY9eOYZ-c/

Website Speed Part 4 : PHP Programming for Speed

March 12th, 2012 Comments off

Programming for speed is not what most coders think of. What they tend to consider first, and usually only, is getting it working. Sometimes people will talk of refactoring to reduce the amount of code, but again this is usually only for those that suffer with the luxury of having too much money and time.

I wish I had that luxury, to be able to spend twice as long on a problem to make a perfect solution. In truth I don’t most of the time, as I am out there getting new clients, making other products or not in the fortunate position to have a client with very deep pockets.

To counteract these things I have a bunch of methods stored in my head that allow me to choose the best path first time (I hope!). I am going to share these best practices with you so you can maybe do the same, maybe even better. If you have any great speed suggestions for coding, please comment and I will append it to this post.

Also, please note that this is not an exhaustive list. This is more of a pointer to things you should consider in your favorite coding language. Although this is for PHP specifically, I’ve tried to keep it as generic as possible to make it possible for all coders, no matter the language, to benefit.

Making IF ELSE smaller

IF is possibly the most used statement from all the programming languages, and I think the most used by a noob programmer (hey I was one once, I remember my code).

Common IF ELSE usage

          if ( $something == true )
              $value = 'yes';
          else
              $value = 'no';
          

Now using only IF

          $value = 'no';
          if ( $something == true )
              $value = 'yes';
          

As you can see all that has been done is that value is pre-set to ‘no’ and only gets changed to ‘yes’ if something is true. Both bits of code have the same outcome, one has less code.

If you only have 1 command inside the if statement then you can take things a little further. PHP does not require that you have the curly brackets when there is just one line.

          $value = 'no';
          if ( $something == true )
              $value = 'yes';

Ternary operators

We can go a stage further and have Ternary Operators. These are mathematical instructions that allow for a yes/no answer, just like IF.

IF presented as ternary operation

          $value = ( $something == true ) ? "yes" : "no" ;

Again the same IF ELSE statement, made much smaller. What it does is check the if the statement inside the brackets is either true or false, if it is true it will set value to be “yes”, if it is false it will set value to be “no”

syntax of ternary operators

          output = ( true/false condition ) ? true-value : false-value ;

It is not essential to have an output, as the true or false value could call a function and not return a value.

Using Range to create an array of numbers

Often people will code an array with just a bunch of numbers in it so that they can loop through it.

PHP code to create a select drop down list

          // selected item value
          $item = 12;
          // create array of numbers
          $array_of_numbers = array( 2,4,6,8,10,12,14,16 );
          // start the select
          echo "";

Now the same thing shorter with range

          // selected item value
          $item = 12;
          // start the select
          echo "";

Range is a really handy thing, as what it does is created an array of numbers (integers). It has the following syntax in php:

          range($start_number, $end_number, $increment);

The only needed compulsory items are the start and end number, the increment defaults to 1, but can be any number you like.

A range function is available in most languages but is unfortunately not available in Javascript out of the box, so to make this same saving in code you would be best to use a FOR loop

FOR loop version

          // selected item value
          $item = 12;
          // start the select
          echo "";

Turbo charging the FOR loop

Many people like to use a for loop as they believe that it is faster than a foreach. While this is often true, it does not offer the flexibility of foreach and with the wrong programming techniques can be slower

The slower FOR loop

            // some text as a string
            $text="We love SpeckyBoy";
            // loop through all the characters
            for($i=0; $i < strlen($text); $i++)
                // look for the o in the text string at the position of $i using a ternary operator
                // echo true or false value as needed
                echo ( substr($text,$i,1) == 'o' ) ? "its an o" : "no o here";
            

The faster FOR loop

            // some text as a string
            $text="We love SpeckyBoy";
            // get the length of the string
            $length = strlen($text);
            // loop through all the characters
            for($i=0; $i < $length ; $i++)
                // look for the o in the text string at the position of $i using a ternary operator
                // echo true or false value as needed
                echo ( substr($text,$i,1) == 'o' ) ? "its an o" : "no o here";
            

The 2nd for loop is faster as it does not need to re-check the string length each time the loop runs. The first loop will check the string length 17 times with the text used

Making your code easier to maintain, and faster

I often see the same problem with my noob code when I re-visit it. The code is all written on 1 line and very long. Check this bit of code as an example:

          $html = "";
          echo $html;

It works just fine, and will be ok for any implementation, but there are some problems with it. For example if the class is empty, it is wasteful to code the empty class setting. While this may not make so much difference to a Javascript implementation, as this is being generated on the server with PHP, you’d be sending extra bytes to the clients browser which are not required. This of course will make the most difference when making AJAX calls and waiting for the reply, where extra bytes can make much more of an impact.

An easier way to maintain

          $attributes = " name='" . $name  . "' ";
          $attributes .= " id='" . $id  . "' ";
          $attributes .= " value='" . $value  . "' ";
          $attributes .= ($theclass != '' )?  " class='" . $theclass  . "' " : "" ;
          $attributes .= ($selected == $value )?  " checked " : "" ;
          $html = "";
          echo $html;

As you can see, much easier to read, much easier to maintain, and used on the server side will produce less HTML code.

Don’t echo every line only the final output

It’s much easier to echo every line, or pass control back to HTML, than it is to write every line to a variable, yet writing the output to a variable first and only echoing at the end is the faster way to process

The easy way to do things, with a few variations

    echo "

" . $title . "

"; ?>

The more server friendly way to do things

    $output = "

" . $title . "

"; $output .= "" . date() . ""; echo $output;

OK, this is a very simplistic example of what you should do as it is only 2 lines and then output.

Rounding up

This is a very short list of things to help make your PHP coding faster and easier to maintain. There is of course many more things that you can do to reduce the amount of code that you do use, or the speed that it runs at.

Most of these techniques can be taken across to other programming languages, so when your coding in Javascript or .NET give it some thought and you will be making things much faster.

More from the Website Speed series…

Website Speed Part 1: Write More Efficient CSS →
Website Speed Part 2: Working With and Optimizing Images for the Web →
Website Speed Part 3 – Caching WordPress →



Original from: http://feedproxy.google.com/~r/speckboy-design-magazine/~3/CTFFkSg11qw/

Scroll to Internal Link with jQuery

March 7th, 2012 Comments off

One page scrolling sites have experienced a huge growth in popularity in web design in recent years. Although this type of site isn’t for everyone, it is still useful to know how they work. Today, I will teach you how to create a very simple one page scrolling site using jQuery.

Before we begin you can download the Source Files, or try the Demo.

This is what we will be building:

Scroll to Internal Link with jQuery

OK, lets get on with it…

The HTML

This page will have very basic HTML – just enough for a navbar and some content.

First off, let’s build the nav.


Here’s the idea behind this: the “nav” has a width of 100% to be the full width of the browser. This “nav” has the “position” property set to “fixed”, so that it scrolls with the user. We then hav a “ul” inside it to hold the navigation.

Take a look at the links – they all point to a particular paragraph.

This is useful in two ways:

  1. If the user has javascript disabled, the links still work.
  2. Using jQuery, we’ll read the “href” attribute off of each link.

Now that we have a simple navigation bar set up, we can do the main content of the page.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec luctus, dui nec porttitor rhoncus, magna mi adipiscing nisl, at laoreet nisl metus at leo. Maecenas bibendum, nibh ac blandit pharetra, eros tortor pretium lorem, ac posuere lorem leo imperdiet quam. Cras vitae eros libero, vel commodo sapien. Cras mauris dui, vulputate vel adipiscing pellentesque, mattis et ligula. Sed massa mauris, luctus sed feugiat at, bibendum vitae magna. Aenean pellentesque, purus non placerat fermentum, nibh ante posuere leo, eget vehicula nibh elit in elit. Proin aliquet aliquet odio vel auctor. Proin sed augue velit. Phasellus metus mauris, scelerisque vitae tincidunt eget, dignissim nec mi. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum eleifend, nisi et congue placerat, purus sem auctor magna, et cursus ante lectus a nulla. Vestibulum tempor, ipsum id congue accumsan, velit mauris rhoncus urna, et accumsan velit orci ac ligula. Vestibulum lobortis facilisis mauris, ut varius mi suscipit in. Donec lobortis diam id nisl tincidunt eget adipiscing mauris vestibulum.

In ut sapien sem, a convallis odio. Aenean consequat ornare egestas. Aenean adipiscing magna et ante varius viverra. Nullam hendrerit, augue et porta bibendum, est ante pretium nunc, quis euismod enim dui sed neque. Duis dictum odio quis lacus tempor a hendrerit elit laoreet. Nunc id nisl vel risus rutrum mattis. Sed fringilla ultrices eleifend. Curabitur mi sem, hendrerit et semper gravida, gravida eget ipsum. Ut sit amet magna elit, non viverra ante. Nulla ut lorem risus. Morbi ac iaculis sem. Maecenas accumsan arcu eu nulla aliquet non pharetra risus adipiscing. Suspendisse consequat justo a sapien dictum dapibus. Duis fermentum risus a neque bibendum quis malesuada erat tempus. Nunc sodales hendrerit porta.

Donec sodales diam et libero ultrices ornare. Aenean vel justo quis ligula facilisis rutrum ut at ante. Proin vitae vestibulum nisl. Sed lacinia dui aliquet orci sollicitudin in feugiat mi porta. Proin mollis tempor lectus, convallis sollicitudin est iaculis quis. Ut vel turpis et sem auctor suscipit sit amet non augue. Pellentesque pellentesque nisl sed metus consectetur et scelerisque ligula porttitor. Proin luctus luctus turpis quis pellentesque. Duis tempor est eget mi pellentesque pulvinar. Nullam euismod urna a sem faucibus vulputate. Aliquam erat volutpat.

Phasellus dolor sem, pharetra nec scelerisque sit amet, consequat quis dolor. Nullam vitae dui non leo faucibus laoreet nec ut nibh. Nullam eleifend pretium imperdiet. Donec et quam odio. Morbi non sem nunc, iaculis aliquam orci. Curabitur viverra consectetur nisi, eu consequat magna varius non. Aliquam odio lorem, imperdiet congue rutrum quis, lobortis at purus. Fusce placerat tempor arcu, congue bibendum diam sagittis ac. Suspendisse erat elit, sagittis vel lacinia ut, cursus ac velit. Suspendisse consectetur orci sit amet dui consequat quis eleifend nulla luctus.

Proin varius pellentesque velit, at consequat risus hendrerit quis. Nam interdum justo sem, quis porta magna. Nunc gravida, libero sed tempor molestie, nisi libero posuere nibh, quis vulputate nibh nibh sit amet nibh. Vivamus vitae erat sed nibh facilisis posuere sed sit amet metus. Quisque hendrerit fringilla elit, id fermentum ante sollicitudin eget. Ut eget arcu id tortor viverra accumsan nec sed dui. Nullam vehicula tortor et quam blandit lobortis. Duis gravida risus sit amet tortor convallis eu feugiat neque consectetur.

The markup here is very simple. There’s a “content” div that holds the paragraphs, and some “p” tags with IDs corresponding to the order.

The CSS

Before we do this, make sure to grab Eric Meyer’s CSS reset. This evens out all browser inconsistencies and lets us work without worrying if the design looks the same in all modern browsers.

We’ll style the main content of the page first, since it is the most simple.

body 
font-family: arial;
font-size: 15px;
line-height: 25px;
color: #515151;
background: #fdfdfd;


#content 
width: 500px;
margin: 0 auto;
padding-top: 40px;
height: 2000px;


#content p 
margin-bottom: 25px;

The body has some simple text and background-color styling, and the content has a width of 500px and is centered. The content div also has a padding-top set to 40px – this is so that the navbar doesn’t block the top 40px of the content. The height is set to 2000px so there is enough space for the content to scroll. This isn’t necessary most of the time. Each paragraph has a “margin-bottom” of 25px, so we can tell where one paragraph ends and the other starts.

Now, we can style the navigation:

nav 
width: 100%;
position: fixed;
height: 40px;
background: white;
border: 1px solid #CACACA;
border-top: none;
-webkit-box-shadow: 0px 0px 3px 1px #ebebeb;
-moz-box-shadow: 0px 0px 3px 1px #ebebeb;
box-shadow: 0px 0px 3px 1px #ebebeb;


nav ul 
width: 750px;
margin: 0 auto;


nav ul li
float: left;
width: 150px;
text-align: center;


nav ul li a 
line-height: 40px;
font-size: 16px;
text-decoration: none;
color: #515151;
border-bottom: 1px dotted #515151;


nav ul li a:hover
color: #000;

The “nav” has a width of 100% so it takes up the whole browser width. It also has “position:fixed” so that it stays on screen when the user scrolls. The height is set to 40px, which is reasonable size for a top navbar. There’s also some simple styling just to make it look nice.

The “ul” has a width of 750px so there is enough space for each link, and it’s centered. Each “li” is floated to the left so that all the links are on one line. Finally, there’s some simple link styling.

The jQuery

Here’s how this will work: There’s going to be a click function for each nav link, which will then execute a function to scroll to the div the link is pointing to.

As always, start off with a document.ready function.

$(document).ready(function()

);

Now, before we write the click function, we’ll write the “scrollToDiv” function that will (surprisingly) scroll to a div of our selection. There are going to be 2 parameters – the element to scroll to, and the height of the navigation at the top of the page.

function scrollToDiv(element,navheight)


We now declare 3 variables that we need to be able to scroll accurately.

function scrollToDiv(element,navheight)
	var offset = element.offset();
	var offsetTop = offset.top;
	var totalScroll = offsetTop-navheight;

The “offset” variable is the offset of the element, and the “offsetTop” variable uses the “offset” variable to withdraw the “top” value. As a result, we get the distance of an element from the top of the page. The “totalScroll” variable is how much the browser should scroll. Without a top navigation bar, the amount to scroll would just be the offset of an element. However, since we have a navigation bar that blocks the top 40px of the content from view, we have to edit the variable accordingly. This is what the “navheight” parameter is for.

Lastly, we scroll the page:

$('body,html').animate(
	scrollTop: totalScroll
, 500);

The jQuery “animate” function can also animate the scrollTop of a page, which allows us to smoothly scroll to a desired spot on the page. Here, the animation takes 500 milliseconds.

Here’s the complete “scrollToDiv” function:

function scrollToDiv(element,navheight)
	var offset = element.offset();
	var offsetTop = offset.top;
	var totalScroll = offsetTop-navheight;

	$('body,html').animate(
			scrollTop: totalScroll
	, 500);
}

Now, we can create the click function.

$('nav ul li a').click(function()

	return false;
);

This is just the skeleton of a click function, with a “return false” statement at the end so that the browser doesn’t actually follow the link.

Before we can pass an element to the function, we have to find the name of that element.

var el = $(this).attr('href');
var elWrapped = $(el);

The “el” variable is just the value of the “href” attribute. The “elWrapped” wraps the “el” variable so that jQuery can use it. jQuery can’t execute the following code:

#paragraph1.offset();

…But it can execute this:

$('#paragraph1').offset();

That’s the reason the “elWrapped” variable is neccesary.

So, here’s the complete “click” function:

$('nav ul li a').click(function()
	var el = $(this).attr('href');
	var elWrapped = $(el);

	scrollToDiv(elWrapped,40);

	return false;
);

That’s it – you should now have a simple page with links the make the page scroll.

Don’t forget you can download the Source Files, or try the Demo.

You might also like…

How to Build a Sliding One Page Portfolio with jQuery →
Hoverizr – An in depth view of the jQuery plugin →
Rubber Layouts – Combining Static and Fluid Layouts →
How to Build a Fully Functional CSS3-Only Content Slider →
Resize Images in a Post with jQuery, and turn it into a plugin →
Getting Started with WordPress Shortcodes (+Examples) →



Original from: http://feedproxy.google.com/~r/speckboy-design-magazine/~3/nevQC6gKz6o/

Weekly Design News – Resources, Tutorials and Freebies (N.123)

March 6th, 2012 Comments off

This is our weekly column were we share our favorite design related articles, resources and cool tidbits from the past week. Enjoy :)
If you would like to receive our daily updates and keep up to date with the latest and greatest articles and resources from the design community, you can follow us on Twitter, on Facebookor by subscribing to our RSS feed.

Our Weekly Design News has been sponsored by MediaLoot. Check them out for some seriously useful resources like icon fonts, UI kits, vectors and themes.

Android Design – Learning how to design Android apps

Android Design - Learning how to design Android apps

Replacing the -9999px hack (new image replacement)

Replacing the -9999px hack (new image replacement)

Build a Contacts Manager Using Backbone.js

Build a Contacts Manager Using Backbone.js

How to use FlexSlider with HTML5 Boilerplate, Initializr

How to use FlexSlider with HTML5 Boilerplate, Initializr

CSS3 Pseudo-Classes and HTML5 Forms

CSS3 Pseudo-Classes and HTML5 Forms

Preserving Vertical Rhythm with CSS and jQuery

Preserving Vertical Rhythm with CSS and jQuery

How to Keep Your CSS3 Code Markup Slim

How to Keep Your CSS3 Code Markup Slim

Design As A Commodity

Design As A Commodity

Contracts for Graphic Designers

Contracts for Graphic Designers

Facebook Page Fan Timeline Free GUI PSD

Facebook Page Fan Timeline Free GUI PSD

Leather Mac App UI Kit

Leather Mac App UI Kit

Free Candy UI Kit

Free Candy UI Kit

Freebies: Black & White Minimal Social Icons Pack

Freebies: Black & White Minimal Social Icons Pack

Free Line Chart (PSD)

Free Line Chart (PSD)

Metropolis 1920 Free Font

Metropolis 1920 Free Font

Neuton Free Font Family

Neuton Free Font Family

East Coast vs West Coast Designers (Infographic)

East Coast vs West Coast Designers (Infographic)

This Week on CodeVisually

Here are our favorite webdev resources from the past week:

Previous Weekly Design News…

Design News Roundup Archives →



Original from: http://feedproxy.google.com/~r/speckboy-design-magazine/~3/szAZ9zVMLj8/

HTML & CSS – Design and Build Websites Book Competition – The Winners

March 2nd, 2012 Comments off

An unbelievable 411 comments! That is how many comments last weeks HTML & CSS – Design and Build Websites Book Giveaway generated. Its been by far and away our most popular competition ever and clearly underlines how good the book is.

It is just a pity we only have 3 copies to giveaway.

Anyway, the competition ended yesterday and it is now time to annouce the winners.

Thanks to everybody for their comments and if you are not one of our winners, remember you can buy the book here: HTML & CSS – Design and Build Websites.

The Winners

The winners should have by now received their winning emails, if not please get in touch with us here.

Winner Name: Ruben Rojas
Comment: Comment URL

Winner Name: Claudio
Comment: Comment URL

Winner Name: Jorian
Comment: Comment URL

About the Book: HTML & CSS – Design and Build Websites

HTML & CSS - Design and Build Websites

Computer books often look rather like manuals. They can be dense and intimidating (they may even send you to sleep), but this book proves that they do not need to look like that.

HTML & CSS - Design and Build Websites

Each page of this book introdues a new topic in a simple, visual way with straightforward explanations accompanied by bite-sized code samples. At the end of each chapter there is an in-depth example that puts together the techniques it has covered. No previous experience is necessary.

HTML & CSS - Design and Build Websites

One of the key things that makes this book different from other titles is that it teaches the same subject with a completely new design approach. The full-color pages are packed with diagrams and photos that make the code easier to learn. Check some of them out:

You can also download a sample chapter here.



Original from: http://feedproxy.google.com/~r/speckboy-design-magazine/~3/5_nNYVHmtGw/

Categories: Web development Tags: , , , , , ,

40 Examples of Brilliant Responsive Website Layouts

February 29th, 2012 Comments off

Responsive web design become a very popular trend in 2011. It’s likely something we’ll see continuing well into 2012 as designers are beginning to support a myriad of mobile devices. Building layouts for the web can be tough, but inspiration is a huge factor.

In this gallery I’ve collected 40+ amazing responsive website layouts. These designs are built to support a set of different resolutions and re-size accordingly. It’s tricky building this functionality in HTML5, even advanced web developers may not understand responsive design trends. But check out some of our examples below and you’ll pick up techniques very quickly. Additionally let us know your thoughts or questions in the post discussion area.

Fork CMS

Full View:

Mobile View:

SimpleBits

Full View:

Mobile View:

White Lotus Aromatics

Full View:

Mobile View:

1140px CSS Grid

Full View:

Mobile View:

Atlason

Full View:

Mobile View:

10K Apart

Full View:

Mobile View:

Cognition

Full View:

Mobile View:

Reverse Buro

Full View:

Mobile View:

Sunday Best

Full View:

Mobile View:

Dustin Senos

Full View:

Mobile View:

Clear Air Challenge

Full View:

Mobile View:

Owltastic

Full View:

Mobile View:

320 and up

Full View:

Mobile View:

Yaron Schoen

Full View:

Mobile View:

Build Guild

Full View:

Mobile View:

Do Lectures

Full View:

Mobile View:

Trent Walton

Full View:

Mobile View:

Food Sense

Full View:

Mobile View:

Sparkbox

Full View:

Mobile View:

ribot

Full View:

Mobile View:

Sweet Hat Club

Full View:

Mobile View:

A Different Design

Full View:

Mobile View:

Teixido

Full View:

Mobile View:

Sasquatch Music Festival

Full View:

Mobile View:

Electric Pulp

Full View:

Mobile View:

Stephen Caver

Full View:

Mobile View:

Social Marketer’s Summit

Full View:

Mobile View:

Sleepstreet

Full View:

Mobile View:

Porcupine

Full View:

Mobile View:

Interim

Full View:

Mobile View:

Tileables

Full View:

Mobile View:

CalebAcuity

Full View:

Mobile View:

Simon Collison

Full View:

Mobile View:

Spigot Design

Full View:

Mobile View:

Forefathers Group

Full View:

Mobile View:

Deren Keskin

Full View:

Mobile View:

Robot… Or Not?

Full View:

Mobile View:

Arrrcamp Conference

Full View:

Mobile View:

Thirst Studios

Full View:

Mobile View:

Visua Design

Full View:

Mobile View:

Made by Splendid

Full View:

Mobile View:

Five Simple Steps

Full View:

Mobile View:

Ryan O’Rourke

Full View:

Mobile View:

dConstruct 2011

Full View:

Mobile View:

Diablo Media

Full View:

Mobile View:

Asbury Agile Web Conference

Full View:

Mobile View:

You might also like…

15 Free WordPress Themes with a Responsive Layout →
25 jQuery Plugins to help with Responsive Layouts →
15 Responsive CSS Frameworks Worth Considering →
10 HTML5-Ready Blank, Bare-Bones and Naked Themes for WordPress →



Original from: http://feedproxy.google.com/~r/speckboy-design-magazine/~3/4IPRHQdtYCg/