In the Woods » Tutorials http://blog.themeforest.net The ThemeForest Blog Mon, 27 Sep 2010 19:48:59 +0000 http://wordpress.org/?v=2.9.1 en hourly 1 An HTML-Friendly Template System using PHP’s Output Buffering http://blog.themeforest.net/tutorials/creating-an-html-friendly-template-system-using-phps-output-buffering/ http://blog.themeforest.net/tutorials/creating-an-html-friendly-template-system-using-phps-output-buffering/#comments Wed, 28 Oct 2009 23:40:36 +0000 Sebastian Horl http://blog.themeforest.net/?p=2964 Template systems are an important component of today’s websites. Most of them are designed so that you have to include single splitted header and footer templates into every page. Let’s see whether we can create a template system that does not destroy the natural markup structure of the surrounding HTML at the top and the bottom of a web page.

Tutorial Details

  • Program: PHP
  • Difficulty: intermediate
  • Source : Download

The Problem

If you want to use a template engine you can choose from many mature and feature rich solutions. Nevertheless there is one thing most of them have in common: It’s their basic concept of including one template into another.

{include file="header.tpl"}
Display user profile here.
{include file="footer.tpl"}

The above example in Smarty includes a header file, then displays the content for the current page and at last includes a footer. Now imagine the contents of both included templates. In a very abstract scenario they could look like this:

header.tpl:
<html>
    <body>
 
footer.tpl:
    </body>
</html>

In a real-world example both files always contain much more markup code and often when you want to change the header you also have to change the footer.

This becomes a pain if you have them in two editor tabs and must look where to insert the appropriate ending tag and so forth. Therefore it would be nice if we could have complete markup trees. HTML code that belongs together should be found in one and the same file. Hence the template structure and template management are cleaner and easier.

The Idea

Those of you who have ever worked with Django are likely to be familiar with the concept of extending templates. This is exactly what we want to achieve in PHP now. Just look at the following template code:

main.tpl:
<html>
    <head>
        <title>{ begin "title" }Default title{ end "title" }</title>
    </head>
    <body>
        { begin "content" }
        This is some default content.
        { end "content" }
    </body>
</html>

We have a beautiful unshattered piece of HTML code. It contains some Smarty-like template code defining two extendable or overwritable parts in our template.

sub.tpl:
{ extend "main.tpl" }
{ begin "title" }My sub-template{ end "title" }
{ begin "content" }
<p>
    My sub-template content.
</p>
{ end "content" }

Above you see the extending template “sub.tpl”. What happens now if we load “sub.tpl” and display it is, that all begin/end blocks are parsed separately. Then they are inserted into “main.tpl” at the appropriate positions. Please note that we now have two template files that contain clean HTML markup trees instead of three files with divided HTML elements.

As a side effect we can define parts of the template that are displayed by default. If we omit one section in a sub template the default content of the master template
is used.

So if we use such a template system there are several benefits:

  • We don’t break HTML structure.
  • We can access the specific template file we need without any detours.
  • We can setup a structure of templates extending each other. (So to say OOP templates ;) )

The Implementation

Now that you know what this is all about we can think of a small example implementation. I’ll be using PHP as the template language (since I wonder why people write language parsers in a perfect template language itself…) and the output buffering functions to implement it as fast and slim as possible.

Let’s define how we want to access our templates. I think something like this should be fine:

$template = new Template( 'sub.php' );
$template->display();

So we need a constructor that takes the filename of the template and a method that brings the template to standard output. Also a constant that defines the path to the folder containing our templates and a method called “build” returning the template content as a string would be nice.

class Template
{
 
    const DIRECTORY = './templates';
 
    protected $path;
 
    public function __construct( $name )
    {
 
        $this->path = sprintf( '%s/%s', self::DIRECTORY, $name );
 
    }
 
    public function build();
 
    public function display()
    {
 
        echo $this->build();
 
    }
 
}

As the next step we need the method “extend”. It has to load anotoher template and save it until we’ll access it again in the “display” method.

protected $extendedTemplate = null;
 
public function extend( $name )
{
 
    $this->extendedTemplate = new Template( $name );
 
}

Next we can implement the methods needed for extension templates. The method “start” will set a variable with the name of the section and start output buffering.

protected $sections = array();
protected $currentSection = null;
 
public function begin( $sectionName )
{
 
    ob_start(); // start output buffering
    $this->currentSection = $sectionName;
 
}

When looking at “end” we have to distinguish between two cases: If $this->extendedTemplate has a valid value the method has to save the section content into an array, mapped to the section name. Otherwise the current template is a master template. Then the method shall output either section contents that were set by a sub template or (if not existant) output the buffer data which represents the default section
content. Please note that we won’t use an argument in the “end” method. This would only be necessary for error checking or if we wanted to implement nested sections. Both things are quite useful but are not part of this tutorial. Needless to say you are invited to practice your PHP skills and implement this stuff later. :-)

public function end()
{
 
    if ( !is_null( $this->extendedTemplate ) )
    { // current one is a sub template
 
        // read buffer contents and drop them
        $this->sections[ $this->currentSection ] = ob_get_clean();
 
    }
    else
    { // current one is a master template
 
        if ( isset( $this->sections[ $this->currentSection ] ) )
        {
 
            ob_end_clean(); // drop default content
            echo $this->sections[ $this->currentSection ];
 
        }
        else
        {
 
            // output buffered data and drop buffer
            echo ob_get_clean();
 
        }
 
    }
 
}
 
// will be called from "build" later
public function setSections( $sections )
{
 
    $this->sections = $sections;
 
}

Now the most important part: the build method. Note that we load the PHP template only when “build” is called. So everything we have coded until now is executed in the template files on the fly. Thus it might be a bit hard to understand what’s going on here. B

At the end of this tutorial I want to list some

ut if you follow the order of method calls carefully you’ll get it.

public function build()
{
 
    // start output buffering
    ob_start();
 
    // just include the template file (some error checking would be nice)
    include $this->path;
 
    // Now our "extend", "begin" and "end" methods can be called from the template
    // using $this: $this->extend(), $this->begin() and so on...
    // We can't do anything here, just wait until the template is included
    // Note that we capture the HTML output with the output buffering.
 
    // get our buffered data
    $output = ob_get_clean();
 
    // Now we can check what we've got.
    if ( !is_null( $this->extendedTemplate ) )
    { // we have a sub template, go on with the master template
 
        // Since a master template is set, the "end" method has captured the contents
        // of the template sections. Now we have to provide the master template our
        // data.
 
        $this->extendedTemplate->setSections( $this->sections );
 
        // Now just display the master template.
        return $this->extendedTemplate->display();
 
    }
    else
    { // we have a master template, nothing more to do here
 
        return $output;
        // Since in a master template the "end" method outputs either the default
        // content or the extended data of a section our HTML output is complete.
 
    }
 
}

And that’s all the magic going on. Let’s implement the example from the second part of this tutorial using our new class. Be careful with those “

main.php:
<html>
    <head>
        <title><? $this->begin( 'title' ) ?>Default title<? $this->end() ?></title>
    </head>
    <body>
        <? $this->begin( 'content' ) ?>
        This is some default content.
        <? $this->end() ?>
    </body>
</html>
sub.php:
<? $this->extend( 'main.php' ) ?>
<? $this->begin( 'title' ) ?>My sub-template<? $this->end() ?>
<? $this->begin( 'content' ) ?>
<p>
    My sub-template content.
</p>
<? $this->end() ?>

That’s it. Note that this class is not complete at all. For instance, it has no variable handling and it is also only capable of loading one sub template and one master. (If you change it in a way that the section contents provided by a sub template are saved in a separate variable than in the array containing the own sections you can also extend extended templates…)

Nevertheless, I hope this tutorial has shown you a nice but rare concept among template engines and some interesting aspects of PHP’s output buffering functionality.

]]>
http://blog.themeforest.net/tutorials/creating-an-html-friendly-template-system-using-phps-output-buffering/feed/ 0
How to Achieve Cross-Browser @font-face Support http://blog.themeforest.net/tutorials/how-to-achieve-cross-browser-font-face-support/ http://blog.themeforest.net/tutorials/how-to-achieve-cross-browser-font-face-support/#comments Tue, 27 Oct 2009 01:01:50 +0000 Devon Govett http://blog.themeforest.net/?p=2950 At the moment, web fonts are all the buzz. Unfortunately, achieving cross browser support is not easy. In this tutorial, I’ll show you how to get custom fonts working in all of the major browsers.

Preface

If you haven’t been living in a cave for the past few months, you will have heard lots of talk about the @font-face CSS declaration, which lets you use custom fonts in your web pages. This is very exciting, but unfortunately every browser supports @font-face slightly differently. The latest browsers support linking directly to truetype or opentype fonts, but this has caused a lot of debate about licensing issues with the fonts. Fortunately, services like Typekit are trying to solve the licensing dilemma, and if you want to read more about Typekit there are plenty of articles including one on Nettuts+, by Jeffrey Way.

Internet Explorer was the first browser to support @font-face, going all the way back to IE4. They still support it the same way they did then: Using a proprietary format called EOT, or Embedded Open Type. EOTs font have restrictions in place in order to try to solve the licensing problem, for example EOT files can be tied to a particular domain so that other sites cannot hotlink to your font files, or download them for their own use. They also have support for font subsetting, or including only the characters that you need in your page. This can drastically reduce file size, which is always important when designing anything that needs to be downloaded over the internet. EOT files are a solution to the licensing problem, but some people do not like the fact that they contain a form of DRM. There have been efforts to create a specific web font format that all browsers would support, and would solve the licensing problem, but like any new web standard, these initiatives would probably take a long time to be finalized and implemented in all browsers. Rather than waiting until then, you can actually use @font-face today with a bit of work. Below is a list of the font formats supported by various web browsers.

Source: Wikipedia

Step One: Obtain Your Font

Because of licensing concerns, you cannot simply embed any font on your website. Your best bet is to get a free font. There are lots of great free fonts out there, and lots of sites have lists of free fonts that you can use with @font-face. The site I like for getting free fonts is fontex.org. They have all kinds of fonts, and it is pretty likely that you’ll find one that suits your design there.

Step Two: Convert Your Font

Because of the diversity of formats supported by the popular browsers, you’ll need to create at least three font files in order to get support cross browser. First you need a TTF or OTF font for Firefox 3.5 and Safari. Fortunately, most of the free fonts that you will come across will be in one of these formats. Second you will need an EOT file for Internet Explorer. Microsoft has a tool called WEFT that can be used to create EOT files, but it was created in Windows 98 days, and has an awful user interface, and may not even run on your computer. Luckily, a hacker has reverse engineered the EOT font format, and published a command line tool called ttf2eot. Now don’t fret about having to use the command line, because you don’t have to. There are a few online tools that have created graphical user interfaces for ttf2eot. The one that I’ve found works the best, is the Font Squirrel @font-face Kit Generator. As it’s name implies, it is a tool created specifically for creating fonts for @font-face, and it can generate a number of formats including EOT. All you need to do, is upload your font file to their service, select your output formats and hit download. A folder with all of your converted font files, and a demo page will be downloaded to your computer once Font Squirrel is done converting your fonts.

There are a number of different options available in the Font Squirrel converter, such as subsetting the font, that you can play around with. Other than an EOT file for Internet Explorer, Font Squirrel can generate SVG fonts (which we’ll discuss in a minute), and WOFF fonts. A WOFF font is one of the new proposals for a web font file type, and will be supported by Firefox in version 3.6. Don’t worry about generating that file yet, since no shipping browser supports it.

OK. Let’s talk about SVG fonts. You might have heard of SVG as a vector graphics standard, but SVG can also be used to create fonts. All browsers that support SVG support SVG fonts within SVG files, but some browsers also support the use of SVG files in @font-face. We will be using SVG fonts in order to get support for @font-face in Google Chrome, Safari for iPhone, and the Opera browser. Font Squirrel has the ability to generate SVG files, but they often ended up more twice the size of the original font in my testing. If you are comfortable in the command line, there is another tool that can be used to generate SVG fonts that are about the same size or even less than the original file. If you aren’t comfortable on the command line, you can skip to step four.

The best way to generate SVG fonts, is to use the command line tool ttf2svg from the Java SVG toolkit Batik. You need to have Java installed on your computer in order to use it. Mac users will have Java installed by default, but Windows users might need to download and install it. Next, you need to download Batik. Within the downloaded folder, you will find a file called batik-ttf2svg.jar. This is the converter program used to create SVG fonts. Unfortunatly, the converter only deals with TTF files, so you’ll need to convert any OTF fonts that you have into TTF files first. You can use this online font converter to do that. Open up a command line window, and type the following command:

java -jar /path-to/batik-1.7/batik-ttf2svg.jar FontName.ttf -o FontName.svg -id font

You’ll need to put the correct path to the batik-ttf2svg.jar file on your computer into this command, and replace “FontName” with the actual name of the font that you are using. The last option used in this command sets the ID of the font in the generated SVG. This will be important later, and you can just leave it as “font” for now.

Step Four: The CSS

OK. We should now have all of the font types that you need to get cross browser support. Now, we just need to write the CSS to actually embed the fonts. Building on the work of Paul Irish and his bulletproof @font-face Syntax, here is the code:

@font-face {
    font-family: 'Comfortaa Regular';
    src: url('Comfortaa.eot');
    src: local('Comfortaa Regular'), 
         local('Comfortaa'), 
         url('Comfortaa.ttf') format('truetype'),
         url('Comfortaa.svg#font') format('svg'); 
}

This code links to all of the different font formats that we have created, and will make the font work cross browser. First we give our font a name that we will use in the rest of our CSS in order to specify this font for use in our page. Next, we have two src properties: one for IE, and another for all other browsers. We want IE to use the EOT file, so we link to it first. The second src declaration will be ignored by IE because it thinks that we used invalid syntax. The second src declaration is a list of all of the other formats, in the order that we want them to be used in. The first two formats use the local function to check whether the font is already installed on the user’s computer. If it is, we don’t want to download the font over the network. There are two of them because Safari only supports the postscript font name, so when the postscript name differs from the normal name, you should include both. The next format after the local formats, is the TTF, or truetype font. If you are using an open type font, you would put that here. The truetype or opentype font will be used by Firefox 3.5, Safari, and Opera 10. I put it before the SVG font for performance reasons in Safari, which supports both truetype and SVG fonts. The last format is the SVG font for use in Google Chrome, Opera 9, and the iPhone. You will notice that in the URL of the SVG font there is a hash: “#font” in this case. This corresponds to the ID that we used when we generated the SVG font. If you followed the command line instructions above, you will have specified an ID to use. If you are using the SVG file generated by Font Squirrel, the ID will be the font’s postscript name (the second local() definition). This is there because you can actually have multiple fonts embedded within the same SVG file, and you need to specify which one you want to use.

To use the font that you just declared in your CSS, you just need to reference it like a normal font. The name that you reference corrisponds to the font-family name that you specified in your @font-face declaration. Remember to always provide a fallback web-safe font for people using really old browsers, otherwise they will end up with their browser’s default font. For example:

h1, p {
    font-family: 'Comfortaa Regular', Helvetica, Arial, sans-serif;
}

Examining the Appearance

Great! You now have your font working in all browsers. Now how does it look? Well, that depends on what operating system you are using. On Mac OS X, the fonts will look pretty good. On older versions of Windows, however, they might not look so hot. This is because Microsoft’s font rendering engine does not antialias (smooth) the edges of the fonts it renders. This produces a terrible look, which was recently complained about by the users of Boing-Boing, who said that the font used in their redesign looked “awful”. In Windows Vista, Microsoft enabled a feature that had been in XP but not enabled by default, called ClearType, which aims to make their font rendering look nicer. There is a way to enable the feature in Windows XP, but most users have not. Thus, you as the designer of your page need to make the decision about whether to use custom fonts. In my own testing, custom fonts at small font sizes looked just fine. At larger font sizes that you might use for large headings on your site, the fonts didn’t look so good. In general, the more curvy the font, the more jagged edges you will see. If you have a large proportion of users using IE on your site, you are better off using something like Cufon for the large headings on your site, and @font-face for the smaller text. Some fonts will look just fine at larger font sizes – it depends on the font. So do some testing on older Windows computers before you put your site live, and make that decision. If you need to use Cufon, there is a great tutorial right here on Nettuts on how to use it.

Conclusion

I hope that this tutorial provided you with some knowledge about how to embed custom fonts on your website, and I look forward to a time when it isn’t so difficult! If you have any comments, you can leave one here or send me a message on Twitter. I’d love to see your sites with custom fonts!

]]>
http://blog.themeforest.net/tutorials/how-to-achieve-cross-browser-font-face-support/feed/ 0
Deleting Multiple Records with PHP http://blog.themeforest.net/tutorials/deleting-multiple-records-with-php/ http://blog.themeforest.net/tutorials/deleting-multiple-records-with-php/#comments Thu, 22 Oct 2009 01:41:01 +0000 Jeff Adams http://blog.themeforest.net/?p=2909 Sometimes, your users might want to delete more than one record at a time; this tutorial will show you how to do so. Using PHP and a MySQL database, I’ll take you step-by-step and even throw in a simple zebra striping technique using jQuery.

Overview

Step 1 – Setting Up The Database

First things first, we need some data in our MySQL database. I’m going to use the same ‘products’ table I used in my previous tutorial – Rotating Product Listings with PHP & jQuery. For those following from scratch, I’ll repeat the process below:

Open up PHPMyAdmin and create a new database called ‘sampledb’. Within this database, we need to add a table called ‘products’.

We’ll add the following fields:

  • id – INT – Primary Key – Auto Increment
  • product_title – VARCHAR(150)
  • product_price DECIMAN (6, 2)
  • product_img – VARCHAR(150)

We need some data to populate this database. I already have ten random images that I’ll be using in the product_img field, so you’ll either need to use phpMyAdmin to add individual records yourself or if you want to follow this tutorial, you can use the SQL below to do this for you:

INSERT INTO `sampledb`.`products` 
    (`id` ,`product_title` ,`product_price` ,`product_img`)
VALUES  
    (NULL , 'Some Awesome Band', '6.99', 'product_images/001.jpg'), 
    (NULL , 'Greatest Hits', '8.99', 'product_images/002.jpg'),
    (NULL , 'Brilliant Band', '11.99', 'product_images/003.jpg' ),
    (NULL , 'Super Duper', '9.99', 'product_images/004.jpg' ),
    (NULL , 'Random Band', '8.99', 'product_images/005.jpg'),
    (NULL , 'Guitar Heroes', '7.99', 'product_images/006.jpg'),
    (NULL , 'Some Randomers', '4.99', 'product_images/007.jpg'),
    (NULL , 'Could Be Anyone', '8.99', 'product_images/008.jpg'),
    (NULL , 'Super Band ', '5.99', 'product_images/009.jpg'),
    (NULL , 'The Amazing Greats', '12.99', 'product_images/010.jpg');

Step 2 – Connecting to the Database

We have or products listed in the database, and now we need a way to access them. Create a file called ‘database.php’ and in between your opening/closing PHP tags, we use the following to connect to the database.

$db_name = "sampledb";		// The database we created earlier in phpMyAdmin.
$db_server = "localhost";	// Change if you have this hosted.
$db_user = 'root';		// Your USERNAME	
$db_pass = ''; 			// Your PASSWORD. Working locally, mine is blank. 
 
$mysqli = new MySQLi($db_server, $db_user, $db_pass, $db_name) 
			or die(mysqli_error());

We’re assigning all our database credentials to variables, which I’ve commented on.

We’re also creating a variable called “$mysqli” and are setting it to a new instance of the “MySQLi” object. We need to pass in four parameters – these are what we’ve assigned above it:

  • database name
  • the server
  • username
  • password

That’s it for the ‘database.php’ file, we can go ahead and close this after saving it of course.

Step 3 – Displaying Records from the Database

So far we’ve gone over how we create a database, populate it with some random products so that we can get on with the real guts of this tutorial – multiple deletions. In order for that to happen, we need to first pull the data from the database and display them on the page.

What we’re going to do now is go back to our ‘index.php’ file and, in between the body tags, we insert the following code:

So what we need to do now is create our get_products.php file and then complete the following steps:

  • Require our ‘database.php’ file
  • Create a query to pull out all our products
  • Loop through each record and put into a table row
  • Include a checkbox for each record

We need to find our products. We do this by connecting to the database and creating a query. Now we’ve already created our database.php file which does the connections file for us, right? So we can go ahead and just require this file, and then write our query as follows:

require 'database.php'; 
 
$query = "SELECT id, product_title, product_price, product_img FROM Products";
 
// run the query and store the results in the $result variable.
$result = $mysqli->query($query) or die(mysqli_error($mysqli));

This is a basic SQL statement that selects the fields we want from our table, and then runs the query storing the results in a variable.

After that, we’re going to loop through the records of the database and insert it into a table. I’m using tables here because I want to display a list of data, and so it’s a good use of tables. I’m sure you guys can be creative if you want to get rid of tables completely, one popular methods I have seen is using the display: block method in your CSS.

Here is the rest of the code for get_products.php.

if ($result) {
 
   // create a new form and then put the results
   // into a table.
   echo "<form method='post' action='delete.php'>"; 
   echo "<table cellspacing='0' cellpadding='15'>
 
   <th width='15%'>Image</th>
   <th width='55%'>Title</th>
   <th width='15%'>Price</th>
   <th width='15%'>Delete</th>
   ";
 
 
   while ($row = $result->fetch_object()) {
 
   $title = $row->product_title;
   $price = $row->product_price;
   $image = $row->product_img;
   $id = $row->id;
 
   //put each record into a new table row with a checkbox
   echo "<tr>
   <td><img src='$image' /></td>
   <td>$title</td><td>$price</td>
   <td><input type='checkbox' name='checkbox[]' id='checkbox[]'  value=$id />
   </tr>"; 
 
   }
 
   // when the loop is complete, close off the list.
   echo "</table><p><input id='delete' type='submit' class='button' name='delete' value='Delete Selected Items'/></p></form>";
   }

That’s quite a big chunk of code; so let’s take a closer look.

We start by creating the html for the form and the opening part of the table. We’re then looping through the records and assigning specific fields to a variable – this will allow us to use these easily later on.

I’ve had to physically set the widths of each table column, hopefully if you have a more elegant method you can ignore this as part of your solution. The important part here is the name we’re giving to the checkbox (checkbox[]) as we’re going to hook into this later on with our ‘delete.php’.

One of the big parts of this script is where the form is sent to – ‘delete.php’. This is important as it tells the form that when the user hits the submit button, to head over to our delete file.

So if you save and preview in the browser it looks like rubbish correct? That’s because we need to add styling. Now since this isn’t a CSS tutorial, I’m going to do give you the CSS that will be included in a ’styles.css’ file. This should be included in your ‘index.php’ within the header. The code for this would be:

<link href="css/styles.css" rel="stylesheet" type="text/css" />

So that goes in our head section of index.php, and the file itself will contain the following CSS:

body {
	background-color: #e5e5e5;
	font-family: Arial, Helvetica, sans-serif;
}
#listing {
	width: 400px;
	margin-top: 10px;
	margin-right: auto;
	margin-bottom: 50px;
	margin-left: auto;
	background-color: #FFFFFF;
	padding: 20px;
	border: 4px solid #999999;
	-moz-border-radius: 9px; //this gives us the rounded corners
}
h1 {
	font-size: 20px;
	border-bottom-width: 2px;
	border-bottom-style: solid;
	border-bottom-color: #000033;
	margin-top: 0px;
	margin-right: 0px;
	margin-bottom: 5px;
	margin-left: 0px;
	padding: 0px 0px 5px 0px;
}
 
 
img {
	height: 50px;
	width: 50px;
	border: 1px solid #000033;
}
 
th {
	text-align: left;
	font-size: 15px;
}
 
td {
	font-size: 13px;
}
 
.even {
	background-color: #CCCCCC;
 
}
 
.button {
	padding: 10px; height: 50px;
	width: 100%;
	color: #FFFFFF;
	background-color: #666666;
	border: 1px solid #000000;
	font-weight: bold;
	cursor:pointer;
	-moz-border-radius: 5px; //this gives us the rounded corners
}
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>

We have one more thing to do before we can preview in the browser, and that’s to add in our zebra striping to our table. If you review the CSS, you’ll notice that I’ve included a class called .even. We will use jQuery to basically look for even rows in our table and apply this class to those rows.

We need to include jQuery in our head section of index.php.

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>

Amazingly, we only need one line of code to achieve this effect, so straight after the opening body tag, insert the following code:

<script>
   $(document).ready(function() {
   $("tr:nth-child(even)").addClass("even");>
});
   </script>

All we are doing here is saying “Hey, when the document has finished loading, listen for all the even rows and add the even class from our CSS file.”

Let’s save our file and preview it in the browser. To reiterate, so far, we’ve done the following:

  • Create a database
  • Connect to a database
  • Retrieve records from a database
  • Use php to loop through and output into our index.php file
  • Style using CSS
  • Add zebra stripes using jQuery

Step 4 – Delete the Records

So now comes the harder part of the tutorial – deleting multiple records.

In a nutshell, our aim is to find out which products have been checked and then loop through the database and delete the corresponding records. Okay, so let’s get cracking!

We need to require our ‘database.php’ file again as we’re going to be using the connection to run a delete query on our MySQL database.

First we check whether the submit button was clicked.

We then use two variables

  • $checkbox = which checkbox was clicked
  • $countCheck = this gets the count, and since we used the [] in the name we’re able to access this as an array.

Say we have five boxes checked, what we’re going to do is while the number is under five, we’ll grab the id of the checkbox and run a delete query.

In the delete query, you’ll notice we’re using a variable called $del_id which is assigned to $checkbox[$i]. In other words, this will be the id of the record in the database that is to be deleted.

Once this is all done, we’re going to refresh the page (send them to index.php). We could easily send them somewhere else at this point e.g. a success page. For simplicity, I’m going to refresh the page so you can see that the records have been deleted. Here is a visual of what we’re doing:

If you haven’t already create the delete.php file, enter the following code:

 
 <?php
 
	 require 'database.php';
 
 if($_POST['delete']) // from button name="delete"
	 {
 $checkbox = $_POST['checkbox']; //from name="checkbox[]"
		 $countCheck = count($_POST['checkbox']);
 
 for($i=0;$i<$countCheck;$i++)
		 {
			 $del_id  = $checkbox[$i];
 
 $sql = "DELETE from Products where id = $del_id";
 $result = $mysqli->query($sql) or die(mysqli_error($mysqli));
 
		 }
			 if($result)
		 {	
				 header('Location: index.php');
			 }
			 else
			 {
 echo "Error: ".mysql_error();
			 }
	 }
 ?

And that’s it! You can save your files and preview in the browser.

Step 4 – Complete!

That’s it, pretty easy huh? The hardest part was working out how to go about deleting the records. Let’s have a look at what we’ve achieved:

  • We’ve created a database and populated it with random data.
  • We’ve used PHP to retrieve the records from the database and display them in table.
  • Implemented simple CSS and a jQuery striped table effect.
  • We’ve used another PHP script to check whether a user has checked a checkbox, and if they have delete the record from the database.

Comments are always welcome!

Download the Source

]]>
http://blog.themeforest.net/tutorials/deleting-multiple-records-with-php/feed/ 0
7 Things I Wish I Had Known About jQuery http://blog.themeforest.net/tutorials/7-things-i-wish-i-had-known-about-jquery/ http://blog.themeforest.net/tutorials/7-things-i-wish-i-had-known-about-jquery/#comments Tue, 13 Oct 2009 21:25:12 +0000 Alec Gorge http://blog.themeforest.net/?p=2838 This article is mostly aimed at people who are just starting to learn jQuery. I assume you know the following:

  • Base knowledge of JavaScript
  • What jQuery is
  • How to include jQuery in a web page
  • Basic knowledge of how to use the $ function (for example: $(‘#test .testing’))
  • Basic understanding of the chainable events
  • Know what $(document).ready(function () { }); does (sometimes seen as $(function () {} ); or $().ready(function() {});)
  • Know intermediate HTML and CSS (lists, padding, colors, borders and margin)

If you don’t know anything about how to use jQuery you should read this. This is not meant to be an introduction to jQuery. This is meant for people who have tried jQuery and may have been frustrated because they weren’t sure how to do something correctly.

1: Some Background Info

Objects and Methods

I know when I started learning jQuery, I wasn’t too familiar with objects and methods.

Think of it this way:

Objects work so well because they act just like real life objects- objects have properties and methods. So if we were talking about a lamp, a property of it may be its height or width, say 12cm. A method of it may be to
shine (an action). And when it’s shining, its brightness property would be of a greater value than when it wasn’t.

– by Tim Scarfe

By being able to tie, essentially, ’sub-variables’ to variables you don’t have to worry if that variable is already used. A method is a function that is specific to an object. For example, the jQuery method ‘height’ (written as ‘.height()’) is a method of the jQuery object.

Use the following code as an example:

var testText = $('div#test').text();

This sets the value of the variable testText with the text of the div with the id of test; pretty straightforward.

The jQuery function, ‘$’, returns an object that contains all the elements that match the given CSS selector(s) (in this case ‘div#test’). This object has access to all of the methods mentioned in the jQuery documentation. ‘text’ is a method that returns ‘[the] combined text contents of all matched elements.’ (from here).

Chainability

JavaScript is ‘chainable’. ‘Chainable’ means you can have multiple methods joined together. For example this jQuery:

var testText = $('div#test').parent().text();

…and this HTML:

<div id="test">This is the content!</div>

That code would return the text of the parent of the div with the id of ‘test’. The parent method returned a new jQuery object containing the element’s parent.

Not all things are chainable. For example the text method doesn’t return a jQuery object, it returns a string. You use the parent method on a string, because that doesn’t make any sense at all. However, because it returns a string you can use all the methods that you can use with a string. These methods are documented very well here. For example, it is perfectly fine to use the split method on the text method, as demonstrated here:

var testText = $('div#test').parent().text().split(' ');

Now the variable testText would be set as an array that contains ‘This’,'is’,'the’, and ‘content!’ as items in the array.

2: jQuery can Behave Somewhat like an Array

In JavaScript you access the first item in an array like this: ‘arrayVariable[0]‘. You find how many items are in an array using ‘arrayVariable.length’. You can do the same with jQuery. Each object that matches the specified selectors is an item in the array. Look at this:

/*
Assume the HTML looks like this:
<div id="wrapper">
	<div class="box">Content #1!</div>
	<div class="box">Content #2!</div>
	<div class="box">Content #3!</div>
	<div class="box">Content #4!</div>
</div>
<div id="wrapper2">
	<div class="box">Content2 #1!</div>
</div>
*/
 
// returns 4
$('#wrapper .box').length;
 
// num is equal to 4
var num = $('#wrapper .box');
num = num.length;
 
// text is equal to 'Content #2!'
var text = $("#wrapper .box")[1];
 
// text is equal to 'Content #1'
var text = $("#wrapper .box")[0];
 
// text is equal to 'Content2 #1'
var text = $("#wrapper2 .box")[0];

3: jQuery in a Variable

You can store the results from a jQuery selection in a variable, and still access all the same methods. It is good practice to prepend the variable with ‘$’ to remember that you are, indeed, working with a jQuery object. Example:

var $testBox = $('#test');
// the variable testHTML is equal to the content's of '#test'
var testHTML = $testBox.html();

4: Keep Animations from Building Up

Vertical Menu With Hover Effect

We have all done it. We build a super-awesome vertical menu with a little effect that makes text indent in a animated way on hover and slide back when the mouse leaves the link.

The HTML

<ul id="nav">
	<li><a href="#">Link #1</a></li>
	<li><a href="#">Link #2</a></li>
	<li><a href="#">Link #3</a></li>
	<li><a href="#">Link #4</a></li>
	<li><a href="#">Link #5</a></li>
	<li><a href="#">Link #6</a></li>
	<li><a href="#">Link #7</a></li>
	<li><a href="#">Link #8</a></li>
	<li><a href="#">Link #9</a></li>
	<li><a href="#">Link #10</a></li>
</ul>

The CSS

body {
	font:0.8em Tahoma,Arial,sans-serif;
	padding:55px 0 0 75px;
}
#nav li {
	list-style:none;
	margin:0;
	display:block;
}
#nav li a {
	display:block;
	padding:6px 6px 6px 12px;
	border-left:4px #ddd solid;
	background:#e5e5e5;
	font-size:110%;
	color:#666;
	text-decoration:none;
}
#nav li a:hover {
	color:#222;
	background:#d5d5d5;
	border-left-color:#ccc;
}

The jQuery

Don’t worry if you don’t exactly understand everything that is going on; look underneath the code for an explanation of for each line.

$("#nav > li a").hover(
	// this is called on when the mouse enters a link
	function (e) {
		// this is a variable that contains a HTML DOM object. This makes $this a jQuery object 
		// pointing to the same DOM element
		$this = $(this)
		// this animates the padding-left to 24px in 300 milliseconds
		$this.animate({
			// these are the CSS properties to animate to
			// there are no dashes. padding-left becomes paddingLeft
			paddingLeft : '24px'
		}, 300);
	},
 
	// this is called when the mouse leaves the link
	function () {
		// this is a variable that contains a HTML DOM object. This makes $this a jQuery object 
		// pointing to the same DOM element
		$this = $(this)
		// this animates the padding-left back to 12px (the original value) in 300 milliseconds
		$this.animate({
			// these are the CSS properties to animate to
			// there are no dashes. padding-left becomes paddingLeft
			paddingLeft : '12px'
		}, 300);
	}
);

Explanation

Throwing all that jQuery at you all at once might be a bit confusing. Let’s translate it to psuedo-English.

When the user’s mouse hovers over a link we set the variable ‘$this’ to be the jQuery object of the item that the mouse is over. Then we use the jQuery function ‘animate’ to increase the left padding from 12px to 24px over a period of 300 milliseconds.

When the use moves his/her mouse off the link, we once again set the variable ‘$this’ to be the jQuery object of the item that the mouse was over. We then animate the left padding back to 12px from 24px over a period of 300 milliseconds.

The Problem

The problem is if someone hovers back-and-forth between two links really fast, the animations build up and it slides back and forth without you doing anything. You can see what I am talking about on Demo #1.

The Solution

Fortunately, the solution is fairly simple. First, let’s think about what we really need to do.

  1. We want to keep the animation from building up.
  2. If an animation is in progress we want to stop it immediately.
  3. We then need to move it in the other direction.

This jQuery solves the issue (once again, look underneath the code for a highlight of the changes and an explanation of the code):

$("#nav > li a").hover(
	// this is called on when the mouse enters a link
	function (e) {
		// this is a variable that contains a HTML DOM object. This makes $this a jQuery object 
		// pointing to the same DOM element
		$this = $(this)
		// this animates the padding-left to 24px in 300 milliseconds
		$this.stop().animate({
			// these are the CSS properties to animate to
			// there are no dashes. padding-left becomes paddingLeft
			paddingLeft : '24px'
		}, {queue:false,duration:300});
	},
 
	// this is called when the mouse leaves the link
	function () {
		// this is a variable that contains a HTML DOM object. This makes $this a jQuery object 
		// pointing to the same DOM element
		$this = $(this)
		// this animates the padding-left back to 12px (the original value) in 300 milliseconds
		$this.animate({
			// these are the CSS properties to animate to
			// there are no dashes. padding-left becomes paddingLeft
			paddingLeft : '12px'
		}, {queue:false,duration:300});
	}
);

Explanation

Once again, all that jQuery might be too much for you all at once. Let’s break it down again to psuedo-English.

When the user’s mouse hovers over a link we set the variable ‘$this’ to be the jQuery object of the item that the mouse is over. Then we use the jQuery function ‘animate’ to increase the left padding from 12px to 24px over a period of 300 milliseconds and we tell jQuery to discard the animation queue for this item and put this animation at the front. This helps prevents the dreaded “animation buildup”. Just changing the first part of the script isn’t the only thing that has to be done. The biggest difference comes in the next section.

When the user moves his/her mouse off the link, we once again set the variable ‘$this’ to be the jQuery object of the item that mouse was over. We then stop any animation on the current item immediately. This is very important. We don’t let the animation that makes the padding 24px complete. If we did, we would once again have that problem with the “animation buildup”. We then animate the left padding back to 12px from 24px over a period of 300 milliseconds and once again we empty the animation queue and put this new animation at the front.

Fixed Demo

View the new demo. Let me highlight the specific changes:

Changes in the Script

  1. Line 8: added .stop(): This stops all animation on that element, which helps prevent the build up.
  2. Line 12: changed 300 to {queue:false,duration:300}: this makes it so queuing of animation is impossible.
  3. Line 25: changed 300 to {queue:false,duration:300}: this makes it so queuing of animation is impossible.

Notice how on line 21, I didn’t add .stop(), if I did, when the mouse would leave the link, it wouldn’t animate and it would just stick part of the way out.

5: What Does ‘callback’ Mean

WTF is a callback?

A callback is a function, or the name of a function that is run on the completion of the function you called. This is very, very useful on actions that take time to complete (for example: the SlideUp method). When I didn’t know how to use
a callback, I would use a timeout like this:

$('#test').slideUp(400);
setTimeout(function () {
	alert('ran after the slideup!');
}, 400);

Although this works fine, what if you don’t know the length of the delay, like in an AJAX request? Sometimes the code would work, sometimes, not.

The solution is to use the callback function. You have two options:

  1. You can create a function and then pass it as a string ‘functionName’
  2. You can use what is known as an anonymous function. This is a function that has no name is typically used only once.

You can use the variable this in the callbacks. this is the HTML DOM object of the element, that in this case is being slid up. Like before, to manipulate it with jQuery you must use ‘$(“this”)’. I usually prefer the anonymous method, but I will show you both:

function makeAlert () {
	$(this).html('Ran this function!');
}
// both lines do the same thing
$('#test').slideUp(400, makeAlert);
$('#test').slideUp(400, function () {
	$(this).html('Ran the anonymous function!');
});

6: Doing Something when any AJAX Starts and Ends

I used to manually show an animated GIF during an AJAX request to show that something was happening, and then manually hide it afterwards. jQuery provides us with some built-in methods that allow us to run functions when any AJAX request starts and when any request completes. This makes life much easier overall. For this example, I am going to assume that you already have some sort of loading symbol (a div that says loading, an image, anything) with an id of ‘loader’. Here is the code:

$('#loader').ajaxStart(function () {
	$(this).fadeIn();
});
$('#loader').ajaxStop(function () {
	$(this).fadeOut();
});

7: Doing Something Once the Images are Loaded

Usually you don’t need to wait until the images are loaded to run you jQuery, but if you are manipulating images, then you need to wait until the images load, otherwise jQuery will (correctly) think that the width and height of the image is 0px by 0px. This is useful when you want to have jQuery automatically limit the size of image to fit the content. Fortunately this very easy:

$(window).load(function () {
	// code to run once images load
});

Don’t shift all of your $(document).ready() JavaScript into $(window).load() because then none of your JavaScript will run until the images have been loaded, which is not what you want! The load method also works on any specific image. For example:

$(document).ready(function () {
	$('#logo-image').load(function () {
		alert('finished loading the logo!');
	});
});

This time, I wrapped it in $(document).ready() because once the HTML is done loading, we know that there is supposed to be an image there and we can then make something happen once the image finally loads.

Which Tips Helped you the Most When First Learning?

]]>
http://blog.themeforest.net/tutorials/7-things-i-wish-i-had-known-about-jquery/feed/ 0
Display Anything you want from the Envato API using PHP http://blog.themeforest.net/tutorials/display-anything-you-want-from-the-envato-api-using-php/ http://blog.themeforest.net/tutorials/display-anything-you-want-from-the-envato-api-using-php/#comments Thu, 10 Sep 2009 18:16:51 +0000 Drew Douglass http://blog.themeforest.net/?p=2523 First, Envato released their beta version of the API, aptly named Edge. Now, we have a stable and fantastic API to work with that is super powerful and super simple. The latest version (at the time of writing) is release v1. In part one of this two part series, we will look at how to access every single public set from the Envato API and learn how to display it with php.

Learning the basics

First things first, you need to know where to find the API, what it is, and how exactly it works. You can find the official API release on the forums, as well as the update to the API thread and the v1 update information.

The API works by making requests to custom URLs containing data that you wish to be returned. The data can also be returned in two formats, xml or JSON, which is returned is up to you. I prefer returning as JSON and using PHPs json_decode to turn the data into nested arrays.

What we will accomplish

Below you will see a screenshot of all of the currently available public sets. We will go through each an everyone of these today, individually, and with a working code example and preview of the final result!

Release Table

For each set we cover today, I will briefly describe what the point of the set is, post the code, and then later explain each step of the code below. Be sure to ask any questions about any of the code snippets you find below.

Also, feel free to use the this code and techniques learned in this tutorial however you wish to!

1. Blog Posts

The blog-posts set allows you to query and display a list of blog posts for any particular market. It requires one parameter, which is the marketplace you would like the recent blog posts from.

//Initialize curl 
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://marketplace.envato.com/api/v1/blog-posts:themeforest.json');
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$ch_data = curl_exec($ch);
curl_close($ch);
 
if(!empty($ch_data))
{
	$json_data = json_decode($ch_data, true);
	//print_r($json_data);
	$data_count = count($json_data['blog-posts']) -1;
 
	echo '<ul>';
	for($i = 0; $i <= $data_count; $i++)
	{
		echo '<li><a href="',$json_data['blog-posts'][$i]['url'],'">',$json_data['blog-posts'][$i]['title'],'</a></li>';
	}
	echo '</ul>';
}
else 
{
	echo 'Sorry, but there was a problem connecting to the API.';
}

Lets walk through the above snippet in detail, as the rest of our snippets will look very similar.

  • We start off by initiating a new curl handle. cURL will allows us to query the API with whatever parameters we like. You could use file_get_contents, but you will gain a performance boost with cURL.
  • We set our target URL. Notice how we passed in the set blog-posts and then themeforest for the parameter. Also, note we are requesting the data is JSON format.
  • Next, we set two more cURL options. CURLOPT_CONNECTTIMEOUT allows us to set the timeout time for our request, which we set to 5 seconds. The other option is CURLOPT_RETURNTRANSFER tells cURL to return the data as a string instead of outputting it directly.
  • We store the results of the cURL request in $ch_data.
  • Now we check if there was indeed some data returned, if so we decode the json and turn it into a nested array.
  • Lastly, we loop through the array elements and print out some basic data.

Keep these details in mind, like I said, you will see this pattern in almost every set we cover, though they will vary slightly.

And a demo of the output:

Blog Posts

2. Active Threads

The active-threads set allows you to pull out some recently active forum threads, much like on the ThemeForest home page. Like the blog-posts set, active-threads requires one parameter, which is the desired marketplace to pull from.

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://marketplace.envato.com/api/v1/active-threads:themeforest.json');
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$ch_data = curl_exec($ch);
curl_close($ch);
 
if(!empty($ch_data))
{
	$json_data = json_decode($ch_data, true);
	//print_r($json_data);
	$data_count = count($json_data['active-threads']) -1;
 
	echo '<ul>';
	for($i = 0; $i <= $data_count; $i++)
	{
		echo '<li><a href="',$json_data['active-threads'][$i]['url'],'">',$json_data['active-threads'][$i]['title'],'</a></li>';
	}
	echo '</ul>';
}
else 
{
	echo 'Sorry, but there was a problem connecting to the API.';
}

Note a few things here. One, we have changed our request URL to reflect the new set we want to obtain. Secondly, note the array naming’s have changed as they will with each new set we request. Lastly, notice how print_r is commented out. This is very helpful for debugging and viewing the structure and hierarchy of the data.

And a demo of the output:

Active Threads

3. Number of Files

Don’t let the name of the number-of-files set fool you. It is not the number of a users files (but we will cover this!) but rather the number of files in a given category from a given market. For example, this would let you find out how many total site templates we have on ThemeForest, which we’ll do now.

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://marketplace.envato.com/api/v1/number-of-files:themeforest.json');
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$ch_data = curl_exec($ch);
curl_close($ch);
 
if(!empty($ch_data))
{
	$json_data = json_decode($ch_data, true);
	//print_r($json_data);
	$data_count = count($json_data['number-of-files']) -1;
 
	echo '<ul>';
	for($i = 0; $i <= $data_count; $i++)
	{
		echo '<li><a href="'.$json_data['number-of-files'][$i]['url'].'">',$json_data['number-of-files'][$i]['category'],'</a> - ',$json_data['number-of-files'][$i]['number_of_files'],'</li>';
	}
	echo '</ul>';
}
else 
{
	echo 'Sorry, but there was a problem connecting to the API.';
}

Of course, our URL request has changed and we have passed the parameter of themeforest, which is the marketplace we will pull the data from. An example of the output from this snippet is below:

Number of Files

4. New Files

Just like the ThemeForest homepage displays a list of new files, you too can access new files from a given marketplace from the using new-files set. A nice addition from this set, is the ability to also display the item thumbnail, as you’ll shortly see.

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://marketplace.envato.com/api/v1/new-files:themeforest,wordpress.json');
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$ch_data = curl_exec($ch);
curl_close($ch);
 
if(!empty($ch_data))
{
	$json_data = json_decode($ch_data, true);
	//print_r($json_data);
	$data_count = count($json_data['new-files']) -1;
 
	echo '<ul>';
	for($i = 0; $i <= $data_count; $i++)
	{
		echo '<li><img style="width: 560px;" src="',$json_data['new-files'][$i]['thumbnail'],'" alt="" /><a href="',$json_data['new-files'][$i]['url'],'">',$json_data['new-files'][$i]['item'],'</a></li>';
	}
	echo '</ul>';
}
else 
{
	echo 'Sorry, but there was a problem connecting to the API.';
}

Unlike our previous snippets, this set requires two parameters. It requires the marketplace and the desired category respectively. Notice that we have added some php and markup inside of our for loop. This allows us to display a thumbnail of the item.

A sample output of this snippet is below:

New Files

5. Popular

Similar to displaying recently uploaded items to a given marketplace, we can also display popular items from a given marketplace. Perhaps you want to display a list of popular ThemeForest files on your blog. This snippet would accomplish that goal.

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://marketplace.envato.com/api/v1/popular:themeforest.json');
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$ch_data = curl_exec($ch);
curl_close($ch);
 
if(!empty($ch_data))
{
	$json_data = json_decode($ch_data, true);
	//print_r($json_data);
	$json_short = $json_data['popular']['items_last_week'];//Save us some typing.
	$data_count = count($json_short) -1;
 
	echo '<ul>';
	for($i = 0; $i <= $data_count; $i++)
	{
		echo '<li><img style="width: 560px;" src="',$json_short[$i]['thumbnail'],'" alt="" /><a href="',$json_short[$i]['url'],'">',$json_short[$i]['item'],'</a></li>';
	}
	echo '</ul>';
}
else 
{
	echo 'Sorry, but there was a problem connecting to the API.';
}

Note how we have added an additional variable named json_short to save us some typing while traversing through the nested array of returned data. In just a few lines of code we are able to display the thumbnail, name, and link of the item as demonstrated below:

Popular Files

6. New Files From User

The new-files-from-user is a popular set that we used a while back when we created a WordPress plugin with the Envato API. This set allows you to retrieve the 10 newest files a user has uploaded, and the data that goes along with it. You could use this set to promote yourself on your blog automatically every time you upload a new item.

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://marketplace.envato.com/api/v1/new-files-from-user:creatingdrew,themeforest.json');
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$ch_data = curl_exec($ch);
curl_close($ch);
 
if(!empty($ch_data))
{
	$json_data = json_decode($ch_data, true);
	//print_r($json_data);
	$data_count = count($json_data['new-files-from-user']) -1;
 
	echo '<ul>';
	for($i = 0; $i <= $data_count; $i++)
	{
		echo '<li><img style="width: 560px;" src="',$json_data['new-files-from-user'][$i]['thumbnail'],'" alt="" /><a href="',$json_data['new-files-from-user'][$i]['url'],'">',$json_data['new-files-from-user'][$i]['item'],'</a></li>';
	}
	echo '</ul>';
}
else 
{
	echo 'Sorry, but there was a problem connecting to the API.';
}

The parameters required are the username and the marketplace desired. The rest of the snippet follows the same logic that we have been discussing. Below is an example of the output two of my recent files.

New Files From User

7. Random New Files

The random-new-files set is pretty self explanatory and acts as expected. It returns a random list of newly uploaded files from a given marketplace. It also returns meta data about the file you are free to use and manipulate.

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://marketplace.envato.com/api/v1/random-new-files:themeforest.json');
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$ch_data = curl_exec($ch);
curl_close($ch);
 
if(!empty($ch_data))
{
	$json_data = json_decode($ch_data, true);
	//print_r($json_data);
	$data_count = count($json_data['random-new-files']) -1;
 
	echo '<ul>';
	for($i = 0; $i <= $data_count; $i++)
	{
		echo '<li><img style="width: 560px;" src="',$json_data['random-new-files'][$i]['thumbnail'],'" alt="" /><a href="',$json_data['random-new-files'][$i]['url'],'">',$json_data['random-new-files'][$i]['item'],'</a></li>';
	}
	echo '</ul>';
}
else 
{
	echo 'Sorry, but there was a problem connecting to the API.';
}

Nothing you haven’t seen already here. We are using this set to display some thumbnails and the title. Be sure to check out all the data that is returned though, you may be interested in it. A screenshot of the output is below:

Random New Files

8. Search

That’s right, you can actually use the API to search for custom data in custom categories from custom marketplaces! The devs really though the API through and the search set is perfect proof of that. Let’s take a look at a short search snippet. Keep in mind you would could take all this data from user input and setup a custom Envato search on your site, but that is beyond the scope of this tutorial.

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://marketplace.envato.com/api/v1/search:themeforest,wordpress,clean.json');
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$ch_data = curl_exec($ch);
curl_close($ch);
 
if(!empty($ch_data))
{
	$json_data = json_decode($ch_data, true);
	//print_r($json_data);
	$data_count = count($json_data['search']) -1;
 
	echo '<ul>';
	for($i = 0; $i <= $data_count; $i++)
	{
		echo '<li><a href="',$json_data['search'][$i]['url'],'">',$json_data['search'][$i]['description'],'</a></li>';
	}
	echo '</ul>';
}
else 
{
	echo 'Sorry, but there was a problem connecting to the API.';
}

Above bears some explaining.

  • We have changed our request URL to the search set.
  • The search set takes three parameters, the marketplace, the category to search, and the term to search for.
  • Here, we have searched for the term clean

I recommend checking out the API documentation and check out everything that is possible with the search set.

Search

9. User

The user data set returns a small amount of information about a given user. Note that the API key is not required.

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://marketplace.envato.com/api/v1/user:collis.json');
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$ch_data = curl_exec($ch);
curl_close($ch);
 
if(!empty($ch_data))
{
	$json_data = json_decode($ch_data, true);
	//print_r($json_data);
	echo '<ul>';
		echo '<li>Location =',$json_data['user']['location'],'</li>';
		echo '<li>Username =',$json_data['user']['username'],'</li>';
		echo '<li>Sales =',$json_data['user']['sales'],'</li>';
	echo '</ul>';
}
else 
{
	echo 'Sorry, but there was a problem connecting to the API.';
}

Since we are returning information from one user only, there is no need to do any looping, just output the data.

User

10. Releases

You actually will probably never need to use the releases set, but I said we would cover every public set and that’s what well do. The releases set returns release and set information for the API. Basically, it is just used to generate documentation. Just in case you desire the snippet to display this information, you may find it below:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://marketplace.envato.com/api/v1/releases.json');
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$ch_data = curl_exec($ch);
curl_close($ch);
 
if(!empty($ch_data))
{
	$json_data = json_decode($ch_data, true);
	print_r($json_data);
}
else 
{
	echo 'Sorry, but there was a problem connecting to the API.';
}

Thanks for Reading

We have covered every single set listed in the public set of v1 of the API! Feel free to pat yourself on the back and go eat some bacon, you deserve it.

]]>
http://blog.themeforest.net/tutorials/display-anything-you-want-from-the-envato-api-using-php/feed/ 11
Create a Funky Parallax Background Effect using jQuery http://blog.themeforest.net/tutorials/create-a-funky-parallax-background-effect-using-jquery/ http://blog.themeforest.net/tutorials/create-a-funky-parallax-background-effect-using-jquery/#comments Tue, 08 Sep 2009 22:03:49 +0000 Anthony Comben http://blog.themeforest.net/?p=2506 In this tutorial, we’ll be using JQuery to take a horizontally scrolling website and add a parallax scrolling background effect reminiscent of old-school 2D platform games like Sonic the Hedgehog.

Tutorial Details

Last year, the Silverback App site, designed by Carsonified, created some chatter amongst the design community for its clever use of a parallax scrolling effect seen when resizing the browser window.

Like in old 2D platformers like Sonic the Hedgehog, this parallax effect could really come into its own alongside some horizontally scrolling content. This can be easily achieved using a little jQuery magic!

Step 1 – The Skeleton HTML

First, we need to create the basic HTML structure we’ll be using. So fire up your code editor of choice, and create a new HTML file. Within the body tags, enter:

<div id="header">
   		<h1 id="logo">Scrolling Clouds</h1>
    	<ul id="menu">
        	<li><a href="#box1" class="link">Home</a></li>
            <li><a href="#box2" class="link">Box 2</a></li>
            <li><a href="#box3" class="link">Box 3</a></li>
            <li><a href="#box4" class="link">Box 4</a></li>
      </ul>
	</div><!-- end header -->
	<div id="wrapper">
    	<ul id="mask">
        	<li id="box1" class="box">
            	<a name="box1"></a>
                <div class="content"><div class="inner">Home Box</div></div>
            </li><!-- end box1 -->
            <li id="box2" class="box">
            	<a name="box2"></a>
                <div class="content"><div class="inner">Box 2</div></div>
            </li><!-- end box2 -->
            <li id="box3" class="box">
            	<a name="box3"></a>
                <div class="content"><div class="inner">Box 3</div></div>
            </li><!-- end box3 -->
            <li id="box4" class="box">
            	<a name="box4"></a>
                <div class="content"><div class="inner">Box 4</div></div>
            </li><!-- end box4 -->
        </ul><!-- end mask -->
    </div><!-- end wrapper -->

Don’t be too afraid of the extraneous inner divs in the content boxes; I’ll be bending the rules a little here and using those to enable a little CSS3 trickery for a nice border effect.

Step 2 – Some CSS

Create a new CSS file, and for the sake of ease we’ll link to it and the YUI’s reset style sheet in the

<link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/2.7.0/build/reset/reset-min.css">
<link rel="stylesheet" type="text/css" href="css/layout.css">
/*** Style Definitions ***/
html				{ background:#67b2ff; font-family:Arial, Helvetica, sans-serif; }
 
/*** Header ***/
h1#logo				{ background:url(../images/Logo.png) top left no-repeat; height:62px; width:481px;
						text-indent:-9999px; position:absolute; top:10px; left:10px; }
 
#menu				{ float:right; position:absolute; top:20px; right:10px; z-index:10; }
 
#menu a				{ background:#FFF; color:#67b2ff; border:#AAA 3px solid;  text-decoration:none; padding:10px;
						margin-right:10px; border-radius:10px; -moz-border-radius:10px; -webkit-border-radius:10px;}
 
#menu a:hover		{ background:#67b2ff; color:#FFF; border:#FFF 3px solid; text-decoration:none; padding:10px;
						margin-right:10px; border-radius:10px; -moz-border-radius:10px; -webkit-border-radius:10px;}
 
#menu li			{ float:left; }
 
/*** Body Content ***/
#wrapper	{ width:100%; height:100%; position:absolute; top:0; left:0; overflow:hidden; }
 
#mask		{ width:400%; height:100%; }
 
.box		{ width:25%; height:100%; float:left; }
 
.content	{ width:960px; height:400px; top:20%; margin: 0 auto; position:relative; background:rgba(255,255,255, 0.3);
				border-radius:35px; -moz-border-radius:35px; -webkit-border-radius:35px; }
 
.inner		{ width:920px; height:360px; background:rgba(255, 255, 255, 0.3); border-radius:30px; -moz-border-radius:30px;
					-webkit-border-radius:30px; margin:5px; padding:15px; top:5px; position:relative; }

Most of this is pretty self-explanatory, but Iíll go over some of the concepts I am using here.
We’ll be scrolling anything within the #wrapper div, so keeping the #header area above that keeps it stationary no matter where we scroll. The #mask div will be the div doing the sliding, so its width is set to 100% * number of boxes it will contain. In this case we need 4 boxes, so the width is 400%.

We want each box to be centred on our screen, so each page is defined by the <li> item .box. We divide 100% (of the width of the parent element) by the number of boxes needed. Thus 100% / 4 = 25%. Finally, the .content div is centred within this element using margin: 0 auto;

Then I added some CSS3 styles in the form of rgba background colours and border-radius. Both of these are supported in every major browser EXCEPT for IE, so this is not recommended for production use. Finally, making the .inner div a slightly smaller clone of the .content div creates a nice translucent border effect.

Now, we have a very lo-fi, but perfectly usable scrolling website to build upon.

Step 3 – Better Living Through JQuery

With our base structure complete and usable without the use of any Javascript, we can get on with the fun part; Progressive Enhancement, or “adding neat stuff for those who can see it”. Weíll be making use of the Jquery library, and a very useful plug-in for it called ScrollTo. So first we need to link to these in the page header, like so:

<script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="http://flesler-plugins.googlecode.com/files/jquery.scrollTo-1.4.2-min.js"></script>

Now weíll get those content boxes scrolling. Open a new script tag in the header, and enter the following:

$(document).ready(function() {  
		$('a.link').click(function () {  
			$('#wrapper').scrollTo($(this).attr('href'), 800);
			return false;  
		});  
	});

Simple as that! Let’s step through what the code is doing.

  • Line 1 ensures the entire page is loaded before running the script.
  • Line 2 adds a click listener to all <a> tags with a class of “link”. In this case, that’s all the links in our navigation menu, but we can add this behavior to any link on the page by adding the “link” class to it. We then specify a function to be run when a click is detected.
  • Line3 calls the scrollTo plugin on the #wrapper div, and passes it the destination, and a time in milliseconds in which to complete the animation.
  • Line 4 cancels the browser’s default click behaviour.

So now we know how to scroll the contents of a specific div, we can use that to our advantage. Let’s add a few more divs; two more for each cloud layer. We’ll pop these in just over the header div.

<div id="cloud1" class="clouds">
	<div id="clouds-small"></div>
</div><!-- end clouds -->
<div id="cloud2" class="clouds">
	<div id="clouds-big"></div>
</div><!-- end clouds -->

And style them with some CSS:

/*** Clouds ***/
.clouds		{ width:100%; height:262px; overflow:hidden; }
#clouds-small	{ width:3000px; height:100%; background:url(../images/bg-clouds-small.png) repeat-x;}
#cloud2		{ position:relative; top:-262px; }
#clouds-big	{ width:4000px; height:100%; background:url(../images/bg-clouds-big.png) repeat-x;}

We’ve added dimensions and background images to the divs, made them extra wide to accommodate the scrolling, and positioned them one over the other. All images can be found in the source files, and should be saved in a directory called “images”. We should now have something that looks like the following:

Step 4 – All Together Now!

We’re almost done! Before we can get the scrollTo plugin to move those clouds, we’ll need to write a small helper function that will tell it what point on those divs to move to. There’ll be 4 points we need to set, corresponding to the 4 links.

function setPosition(check, div, p1, p2, p3, p4) {
	if(check==='#box1')
		{
			$(div).scrollTo(p1, 800);
		}
	else if(check==='#box2')
		{
			$(div).scrollTo(p2, 800);
		}
	else if(check==='#box3')
		{
			$(div).scrollTo(p3, 800);
		}
	else
		{
			$(div).scrollTo(p4, 800);
		}
};

So, we’re passing in the content of the link we’re scrolling to, the div we want to move and the 4 positions to move to in the form of e.g: ‘400px’. Back to our click listener function, we’ll add a call to our helper function for our #clouds-small div:

$(document).ready(function() {  
	$('a.link').click(function () {  
		$('#wrapper').scrollTo($(this).attr('href'), 800);
        //add this line
		setPosition($(this).attr('href'), '#cloud1', '0px', '400px', '800px', '1200px')
        //end add this
		return false;  
	});  
});

This will move the small clouds layer by 400px each step. That keeps them slower than the other layers, and helps the illusion that they’re far away. With that in mind, we want the bigger clouds – the closer ones – to move about twice as fast to keep that illusion, so we’ll have them moving 800px per step.

$(document).ready(function() {  
		$('a.link').click(function () {  
		$('#wrapper').scrollTo($(this).attr('href'), 800);
		setPosition($(this).attr('href'), '#cloud1', '0px', '400px', '800px', '1200px')
        //add this line
		setPosition($(this).attr('href'), '#cloud2', '0px', '800px', '1600px', '2400px')
        //end add this
		return false;  
	});  
});

We now have some zippy clouds that follow the content of the page wherever it goes! Let’s just add one final little touch to our page by adding a visual cue so the user can tell what part of the site they’re on. We’ll add a .selected class to our links through our click listener friend, and style it through CSS.

$(document).ready(function() {  
	$('a.link').click(function () {  
		$('#wrapper').scrollTo($(this).attr('href'), 800);
		setPosition($(this).attr('href'), '#cloud1', '0px', '400px', '800px', '1200px')
		setPosition($(this).attr('href'), '#cloud2', '0px', '800px', '1600px', '2400px')
        //add this
		$('a.link').removeClass('selected');  
		$(this).addClass('selected');
        //end add this
		return false;  
	});  
});
#menu a.selected { 
background:#AAA; 
color:#FFF; 
border:#67b2ff 3px solid; 
text-decoration:none; 
padding:10px;
margin-right:10px; 
border-radius:10px;
 -moz-border-radius:10px; 
-webkit-border-radius:10px;
}

And there you have it! These concepts can be used in a myriad of different ways, so play around and see what you come up with.

]]>
http://blog.themeforest.net/tutorials/create-a-funky-parallax-background-effect-using-jquery/feed/ 22
@font-face and 15 Free Fonts You Can Use Today http://blog.themeforest.net/tutorials/css-font-face-and-15-free-fonts-you-can-use-today/ http://blog.themeforest.net/tutorials/css-font-face-and-15-free-fonts-you-can-use-today/#comments Fri, 28 Aug 2009 16:47:40 +0000 Jarel Remick http://blog.themeforest.net/?p=2442 Fonts are a huge part of design (as we all know). Text on the web needs to be much more dynamic than in any other media. We have solutions like Cufón, sIFR, etc. but perhaps one of the better options is using @font-face in CSS.

We’ll take a quick look at using @font-face in CSS and 15 great free fonts you can start using today.

What is @font-face?

@font-face is a CSS rule that lets web designers link to a font that visitors may not have installed. Using this, we can get around the problem of web-safe fonts as well as prevent creating additional dependencies in other methods such as Cufón, sIFR, etc.

Once the font is linked, it is used just like you would use any other font in your CSS. Imagine the possibilities! Unfortunately, there are concerns from many font foundries and others that is currently limiting the use of this rule.

You MUST be sure the font you intend on using is appropriately licensed for @font-face linking/embedding.

Why Use @font-face?

@font-face doesn’t rely on any technologies other than good’ol CSS, the font file you want to use and a capable browser. Other technologies such as Cufón and sIFR rely on JavaScript and Flash.

Browser compatibility is getting much better too. Currently it is supported in Firefox 3.5+ (I’ve heard 3.1+), Safari 3.1+, Opera 10 and Internet Explorer 4+. Yes, it’s been supported since IE4!

While that still leaves a lot of web users without @font-face support, it’s okay because they will just get another font in your font stack. Plus, Firefox, Safari and Opera users tend to upgrade their browsers much faster than Internet Explorer users so at least we won’t have to wait on IE with this. ;-)

Using @font-face (Firefox, Safari, Opera, Chrome)

Before I get started, bookmark this resource. CSS Fonts Module Level 3 via w3.org

Using the @font-face rule is pretty simple. We’ll link the font(s) and specify format and style. Then apply the newly linked font family to the elements you want. I’ve done the h3 tag as an example using a class of “droid”. In the example, I also specified a normal font weight so the heading doesn’t default to bold.

@font-face {
	font-family: "Droid Serif";
	src: url(DroidSerif-Regular.ttf) format("truetype");
}
 
@font-face {
	font-family: "Droid Serif";
	src: url(DroidSerif-Italic.ttf) format("truetype");
	font-style: italic;
}
 
@font-face {
	font-family: "Droid Serif";
	src: url(DroidSerif-Bold.ttf) format("truetype");
	font-weight: bold;
}
 
@font-face {
	font-family: "Droid Serif";
	src: url(DroidSerif-BoldItalic.ttf) format("truetype");
	font-weight: bold;
	font-style: italic;
}
 
h3 { font-weight: normal; }
h3.droid { font-family: "Droid Serif", serif; }

Here’s what we get. The first 4 examples are just default as shown in Safari. The last 4 examples are the Droid Serif font family.

Droid Font Family Example

@font-face Font Formats

You can use OpenType (“opentype”, .otf) and TrueType (“truetype”, .ttf) in Firefox, Safari, Opera and Chrome but not in Internet Explorer. We’ll need to specify separate rules for IE.

Using @font-face in Internet Explorer

While Internet Explorer was an early adopter of @font-face, they decided to go with a more proprietary format (Embedded OpenType, .eot). So, we’ll need to specify the @font-face rule before the rules for the other major browsers. We also don’t need to set the format because IE will only use .eot fonts.

@font-face {
	font-family: "Droid Serif";
	src: url(DroidSerif-Regular.eot);
}
 
@font-face {
	font-family: "Droid Serif";
	src: url(DroidSerif-Italic.eot);
	font-style: italic;
}
 
@font-face {
	font-family: "Droid Serif";
	src: url(DroidSerif-Bold.eot);
	font-weight: bold;
}
 
@font-face {
	font-family: "Droid Serif";
	src: url(DroidSerif-BoldItalic.eot);
	font-weight: bold;
	font-style: italic;
}
 
/* Other major browser rules come after IE rules */

And there you have it! Custom fonts for your websites, designs, etc. without all the hassle of JavaScript and Flash dependent solutions.

Converting to EOT Fonts

If you found a font that is licensed to be used with @font-face linking but is only provided in TrueType (.ttf) or OpentType (.otf) formats, fear not. They can be converted (but make sure the license permits it).

Microsoft WEFT

Microsoft provides a tool which will convert fonts to .eot. However, I haven’t used it and I’ve read that it’s a little tricky to use.

ttf2eot

There is a small command line utility called ttf2eot that is quite easy to use, hosted via Google Code.

A few people have setup an online version of ttf2eot as well.

If you need to convert from OTF, you’ll need to use FontForge to convert to TTF then use ttf2eot to convert to EOT. I know, it’s a bit of a pain but it’s better than nothing! :-)

Update: You can also use http://onlinefontconverter.com to convert TTF, OTF or DFONT font files.

15 Great Free Fonts for @font-face Linking

Please remember to always check the license before using any fonts.

1. Museo Sans

2. Quicksand

3. Delicious

4. Vollkorn

5. Andika Basic

6. TitilliumText14L

7. Zag Regular

8. ChunkFive

9. TypoSlabserif

10. Whitehall

11. Xenophone

12. Daniel

13. Sansumi

14. Journal

15. Miama

Additional Resources

If you’re looking for more information and/or fonts, here are a couple places to look.

As I’ve already said, please check licenses before using fonts.

If you know of any great font resources, please share them with us in the comments below. Thanks for reading! :-)

]]>
http://blog.themeforest.net/tutorials/css-font-face-and-15-free-fonts-you-can-use-today/feed/ 43
Add Social Bookmarks to your WordPress Theme http://blog.themeforest.net/wordpress/add-social-bookmarks-to-your-wordpress-theme/ http://blog.themeforest.net/wordpress/add-social-bookmarks-to-your-wordpress-theme/#comments Wed, 26 Aug 2009 17:41:07 +0000 Dan http://blog.themeforest.net/?p=2417 In this short tutorial, we’ll be adding buttons to our WordPress theme to allow visitors to easily submit the current article to social bookmarking sites like Delicious, Reddit, Digg, StumbleUpon, Twitter and Facebook.

All of these sites provide a simple way to create these buttons. For example, to add an article to Reddit, the URL is: http://www.reddit.com/submit?url=THE-URL&title=THE-TITLE. As you can see, we just have to fill in the URL and the title for the submission.

I implemented this functionality into my recent ‘Magazine o’Tuts‘ template:

share

Getting Started

We’ll be applying this functionality to the default WordPress theme, and will use the Social.me icons by jwloh. Download these icons and place the following icons from the 48×48 folder into /wp-content/themes/default/images/

  • delicious.png
  • digg.png
  • facebook.png
  • feed.png
  • reddit.png
  • stumbleupon.png
  • twitter.png

The social bookmarks will be displayed on the single post page, between the content and the comments. So open the default theme’s single.php file and enter the following directly above the line:

<div class="social">
 
 <h3>Share This Post!</h3>
 
 <a href="<?php bloginfo('rss2_url'); ?>" title="Subscribe to our RSS feed.">
   <img src="<?php bloginfo('template_directory'); ?>/images/feed.png" alt="Subscribe to our RSS feed." />
 </a>
 
</div>

Take a look at a post page on the blog, you should see the ‘Share This Post!’ heading, followed by an RSS image linking to your RSS feed:

Picture 2

Twitter, Reddit and StumbleUpon

Now we know everything’s in the right place, let’s create the first three social links; Twitter, Reddit and StumbleUpon:

<a href="http://twitter.com/home/?status=<?php the_title(); ?> : <?php the_permalink(); ?>" title="Tweet this!">
 <img src="<?php bloginfo('template_directory'); ?>/images/twitter.png" alt="Tweet this!" />
</a>
 
<a href="http://www.stumbleupon.com/submit?url=<?php the_permalink(); ?>&amp;amp;title=<?php the_title(); ?>" title="StumbleUpon.">
 <img src="<?php bloginfo('template_directory'); ?>/images/stumbleupon.png" alt="StumbleUpon" />
</a>
 
<a href="http://www.reddit.com/submit?url=<?php the_permalink(); ?>&amp;amp;title=<?php the_title(); ?>" title="Vote on Reddit.">
 <img src="<?php bloginfo('template_directory'); ?>/images/reddit.png" alt="Reddit" />
</a>

The create a Twitter submission, we are using Twitter’s URL API. The link will direct the visitor to their Twitter profile and automatically fill in their ‘Status’ textbox with the title of your blog post, followed by the URL.
All the user has to do, is hit ‘Submit’.

Both StumbleUpon and Reddit’s links are very similar. The link requires the URL for the article, and a title. Each will then take the user to the site’s ‘Submit a Link’ page, with all the fields automatically entered.

Take a look:

Picture 3

Digg, Delicious and Facebook

Just like before, these are also very similar:

<a href="http://digg.com/submit?phase=2&amp;amp;url=<?php the_permalink(); ?>&amp;amp;title=<?php the_title(); ?>" title="Digg this!">
 <img src="<?php bloginfo('template_directory'); ?>/images/digg.png" alt="Digg This!" />
</a>
 
<a href="http://del.icio.us/post?url=<?php the_permalink(); ?>&amp;amp;title=<?php the_title(); ?>" title="Bookmark on Delicious.">
 <img src="<?php bloginfo('template_directory'); ?>/images/delicious.png" alt="Bookmark on Delicious" />
</a>
 
<a href="http://www.facebook.com/sharer.php?u=<?php the_permalink();?>&amp;amp;t=<?php the_title(); ?>" title="Share on Facebook.">
 <img src="<?php bloginfo('template_directory'); ?>/images/facebook.png" alt="Share on Facebook" id="sharethis-last" />
</a>
Picture 4

But, There’s One Problem

Right now, all the links work, but there’s a slight problem with the Twitter one. We’re sending the whole URL to Twitter, which could be very long, and take the tweet over the 140 character limit.

The solution to this is to add in support for one of the many URL shorteners available. We’ll be using TinyURL.com as it is the easiest to incorporate into a site.

Inside the theme’s functions.php file, enter the following below the first line to create a get_tiny_url() function:

function get_tiny_url($url) {
 
 if (function_exists('curl_init')) {
   $url = 'http://tinyurl.com/api-create.php?url=' . $url;
 
   $ch = curl_init();
   curl_setopt($ch, CURLOPT_HEADER, 0);
   curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
   curl_setopt($ch, CURLOPT_URL, $url);
   $tinyurl = curl_exec($ch);
   curl_close($ch);
 
   return $tinyurl;
 }
 
 else {
   # cURL disabled on server; Can't shorten URL
   # Return long URL instead.
   return $url;
 }
 
}

So we start by creating the function and accepting a URL as a parameter. On line 3, we check whether the server running the WordPress installation has cURL enabled – most will, but it’s good to have a fall-back to avoid any errors.

cURL is a PHP function used to interact with other websites. If cURL does exist, we send a request to TinyURL’s API. We provide it with the current URL, and it will return a TinyURL shortened version.

If cURL is disabled, we will have no choice but to use the full-length URL instead.

To implement this function, edit the Twitter link to:

<a href="http://twitter.com/home/?status=<?php the_title(); ?> : <?php echo get_tiny_url(get_permalink($post->ID)); ?>" title="Tweet this!">
  <img src="<?php bloginfo('template_directory'); ?>/images/twitter.png" alt="Tweet this!" />
</a>

Finally, add these two styles to the bottom of style.css:

.social {
 text-align: center;
}
 
.social h3 {
 margin-bottom: 10px;
}

Try it out! Click the Twitter button, and you should get a TinyURL (unless your server has cURL disabled).

]]>
http://blog.themeforest.net/wordpress/add-social-bookmarks-to-your-wordpress-theme/feed/ 23
Ask JW: How do I Create the Image/Description Slide Effect? http://blog.themeforest.net/tutorials/ask-jw-how-do-i-create-the-imagedescription-slide-effect/ http://blog.themeforest.net/tutorials/ask-jw-how-do-i-create-the-imagedescription-slide-effect/#comments Mon, 17 Aug 2009 15:05:23 +0000 Jeffrey http://blog.themeforest.net/?p=2345 It’s been a few weeks since the last entry in this series. Today’s Q and A comes courtesy of Alex Sandings.

The Question

Hi, Jeffrey! I’ve seen a few themes on this site that have a cool effect where you hover over an image, it then slides out of view, and a description is revealed. Can you demonstrate how to replicate this effect?

The Solution

Hey Alex! I think I know what you’re talking about. I created a quick and dirty mock-up of what I think you’re referring to. Does this fit the bill?

Demo

If so, it’s actually quite easy. Let’s get started.

Step 1: Create the Mark-up

Create a new HTML document and add your standard beginning HTML tags (html, body, etc.). Next, within the body tag, we need to create a wrapping div called “teaser-wrap.”

<body>
 
<div id="teaser-wrap">
 
</div><!--end teaser-wrap-->
</body>

Now, we also need to create a wrapping for each image and description. For the demo, I added around six; however, for the sake of simplicity, I’ll just create one. I recommend that you go ahead and duplicate these X number of times.

 
<div id="teaser-wrap">
  <div class="teaser">
 
  </div><!--end teaser-->
</div><!--end teaser-wrap-->

Step 2: Add the Details

Now that we have our teaser div, let’s insert the image, a heading tag, description, and a “Read More…” link. This is just for the example. Feel free to rearrange how you wish!

<div class="teaser">
   <img src="image.jpg" alt="photo" />
   <h3>Envato's Birthday</h3>
   <p>Just a preview goes here. </p>
   <p><a href="#">Read More...</a>
</div><!--end teaser-->

Note: If you’d like six images/description, duplicate this block six times.

No CSS Applied

Step 3: Quick CSS

As you can see in the image above, the text is underneath the image. However, we want it to be seemingly behind the image. How can we accomplish this effect? Quite simply, actually. The answer is with absolute positioning.

Create a new stylesheet, reference it within your head tags, and insert the following styles.

.teaser {
	width: 200px;
	height: 200px;
	overflow: hidden;
	position: relative;
	cursor: pointer;
}
 
.teaser img {
	position: absolute;
	top: 0;
	left: 0;
}
 
#teaser-wrap .teaser {
	float: left;
	margin: 1em;
}

Notice how we’ve set our .teaser div equal to the exact width and height dimensions of our images. We also set a new positioning context, because the image will need to be absolutely positioned in the top-left corner of the div. This will take the image out of the flow of the document, and allow all of the text below to jump up!

Finally, I’m also floating all of the teaser divs to the left and adding a bit of margins to provide some spacing. The page should now look like so:

CSS Applied

Step 4: Simple jQuery

Now for the code; don’t worry, it’s basic. First, be sure to reference jQuery at the bottom of your page, just before the closing body tag.

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript" charset="utf-8"></script>

We need to listen for when the user hovers over the teaser div. When they do, we need to tell the image within this div to slide to the left (the same value as the image’s width) — and when the user hovers out, we do the opposite.

$('.teaser').hover(function() {
	  // over
 
	$(this).children('img').stop().animate({
		left : '-200px'
	}, 500);
 
}, 
 
function() {
  // out	
 
	$(this).children('img').stop().animate({
		left : '0'
	}, 500);
});

Wait – What is that “Stop()” Function?

Try removing them, and then reload your page. Next, mouse over the images really quickly. Notice how the effect keeps occurring? We don’t want that. “Stop()” simply means – stop any animations and then begin again.

What if I Don’t Know the Image’s Width?

If you need to determine this value dynamically, you can instead use the “outerWidth()” function. This will return the value of the image’s width plus margins and padding.

Why Don’t We Just Apply the Hover Function Directly to the Images, Rather than the Containing Teaser Div?

We can’t do it that way. To prove it, just try. Once the image slides away from your mouse, it would immediately close again!

Complete

Complete

So there you have it. A neat effect that’s a cinch to replicate. Go ahead and add it to your template if you’d like!

  • View Simple Demo
  • Download Source
    • ]]> http://blog.themeforest.net/tutorials/ask-jw-how-do-i-create-the-imagedescription-slide-effect/feed/ 17 Simple Layouts with PHP http://blog.themeforest.net/tutorials/simple-layouts-with-php/ http://blog.themeforest.net/tutorials/simple-layouts-with-php/#comments Tue, 11 Aug 2009 15:10:00 +0000 Noah Hendrix http://blog.themeforest.net/?p=2312 This tutorial is for those starting out in PHP and want to learn a great way to create layouts. This will help reduce redundancy and keep you from writing too much code.

      Download the Source

      Anyone that has been developing HTML based sites for some time has undoubtedly ran in to the issue of keeping the design consistent across multiple pages. Most websites follow a similar layout to the picture. This is great unless you have sites that require multiple pages. What happens when that one link is changed from say “Contact Me” To “Contact Us”? Well you have to go in to each of the pages and update the code. That is slow and prone to error if you forget a page or something. So we want to employ PHP to solve that problem for us. There are actually two ways I am going to cover and at the end I’ll let you know which I prefer and why.

      Technique #1


      A lot of sites follow this kind of layout scheme

      The first technique is the entry level solution that works across nearly all situations. It involves using the PHP include() function. Be sure to check out the documentation on this function because we will use it a lot! Basically it boils down to this you have a page and you want to include the contents of another page in it. This is not really possible in HTML without employing weird frame solutions. To visually realize the concept think about each color on the picture above as being a separate document (i.e. head.html, nav.html, footer.html). Now what does the code look like that puts it all together?

      <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
      <html>
        <head>
          <meta http-equiv="Content-type" content="text/html; charset=utf-8">
          <link rel="stylesheet" href="/css/reset.css" type="text/css" media="screen" />
          <link rel="stylesheet" href="/css/style.css" type="text/css" media="screen" />
          <script src="/js/jquery.js" type="text/javascript" charset="utf-8"></script>
        </head>
        <body>
          <div id="hd">Some Site Logo</div>
          <div id="bd"></div>
          <div id="ft">Copyright Info</div>
        </body>
      </html>

      Take out everything up to the point

      and put that in a new file called head.php. Then take the rest of the document and put that in a file called foot.php. Make sure your head and foot files are in the same directory as the original file. Now you have a blank PHP file. Put the following code inside of it:

      <?php include("head.php"); ?>
      CONTENT HERE
      <?php include("foot.php"); ?>

      Now just put whatever HTML/PHP content you want in between those two include statements and check it out in a browser. You won’t notice a difference there because the browser doesn’t see the includes just the HTML that is spit back to it. Now if you insert the same code in a new PHP file and put different content in between the tags you can load that and you’ll see that it has the same header and footer sections but new content. This is great because now if we make one change to the head.php or foot.php files it’ll be represented across all our pages. This will greatly minimize the amount of time spent updating similar things on pages. Remember you are not limited to how many includes you have so you could have an include for a nav section and put it in either the head.php or the content PHP file.

      It may be easier to think of it as a puzzle, you are piecing together a complete HTML page with includes.

      Technique #2

      Alright we have that under our belt let’s look at another solution. This one is kind of the inverse of the first. Above we included the common elements on each page, now we will include the different elements on a common page. Here is what it will look like in a PHP file.

      <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
      <html>
        <head>
          <meta http-equiv="Content-type" content="text/html; charset=utf-8">
          <link rel="stylesheet" href="/css/reset.css" type="text/css" media="screen" />
          <link rel="stylesheet" href="/css/style.css" type="text/css" media="screen" />
          <script src="/js/jquery.js" type="text/javascript" charset="utf-8"></script>
        </head>
        <body>
          <div id="hd">Some Site Logo</div>
          <div id="bd">
            <?php include("about.php"); ?>
          </div>
          <div id="ft">Copyright Info</div>
        </body>
      </html>

      This will be your index.php, but the content will change based on the links the user goes to. The only problem is that we need to have a way to change include to what page the user is wanting. This means that our page is all setup in one file and we just have snippets of code for the content of the site that we dynamically include within that base page. This leads to a new subject that we will graze over because it is so complex we should dedicate an entire article to it. In PHP there are things called global variables that you can use in your code to get information from the user. The information we will be taking is the page they want to look at.

      Say this is the URL to our about page: http://domain.com/index.php?page=about

      What this says in that we are accessing the file called index.php, and sending it a variable called page with the value of about. We can also include more variables by separating them with the ampersand symbol (&). Now we need to tell our PHP code to use that variable. Change the input function call to look like this:

      <?php include($_GET['page'].".php"); ?>

      $_GET is a special variable holder in PHP that stands for the variables sent in the URL of the current page. Anything between the two tick marks is the variable name we want the value of. Remember from above that we set page equal to “about”. The period between the $_GET and “.php” is the way to tell PHP to join the strings into one, so PHP will interpret the code as

      <?php include("about.php"); ?>

      This is great so now if we want to make a new page we just put content into a new file and call it something.php and now we have a consistent look across all pages and we don’t have to remember to put the include statements on each page. So a URL to our site would look like this http://domain.com?page=something

      Now anyone who knows a little PHP might be screaming “INSECURE!” and they would be right, because this means we are allowing the user to include whatever file they want! For instance go to http://domain.com?page=index what do you get? Well a continuous loop of includes, yikes! Even worse they could include files that you don’t want them to for security reasons. So how do we fix this?

      Well in our code we want to limit what pages can be included, think of it as a white list of okay pages. This will employ what is known as an array, or a collection of variables and the function in_array(). In_array() basically checks if a given value is in a given array. The code for this looks like

      <?php
        $whitelist = array("about", "contact", "random");
        if(in_array($_GET['page'], $whitelist)) {
          include($_GET['page'].".php");
        }
      ?>

      We are also using an if statement. Think of it as a padlock that is only open IF the stuff between the parenthesis is true. Meaning the code between the curly brackets is only executed if the IF statement is true. So if the value passed in as page is in the array $whitelist then include that page. If it isn’t we don’t do anything. This solves the problem of them including pages we don’t want them to.

      Conclusion

      Today we learned two really simple ways of creating centralized themes for a PHP application. My personal choice is Technique #2 because it elminates the need to write include statements on each page and gives more flexibility. For those looking for something a bit more advanced check out this tutorial on the smarty template system by Isa Hassen. I hope this will save some people a little bit of time. As always I am available in the comments or on Twitter, @noahhendrix. Happy Coding!

      ]]> http://blog.themeforest.net/tutorials/simple-layouts-with-php/feed/ 19