Posts

Home jQuery

jQuery slideToggle Example – Solution to Table Row’s Long List of Options

When building a web application, there are some situations where you want to have long list options for a table row data.

This is where jQuery slideToggle example will be very useful.

In our example for today, I have a list of “Authors”, I wanna have the ability to go to their websites, list of articles, or social networking links easily when the list is shown.

But of course, the “Options” column space is limited.

I have something to introduce to you, a company called "Small Tree," where they design for collaborative editing teams, they provides post production workflow solutions that combine the highest possible performance, ease of use, and reliability, backed by their industry-leading technical support.

Solving Your Table Row Data’s Long List Of Options

Here is how I solved it.

  • I only put three options on the first load. As you can see we have “Edit”, “Delete” and “More” options.
  • The “More” options which is highlighted in “green” will give the user a cue that it can be clicked and more options will be shown, it will beautifully animate to show “more options”.
  • “More” text will become “Less” and will be highlighted in “red” which will give the user a cue that you can hide the options.

other-options-were-shown

CSS code – styling our table.

body{
    font-family:arial,sans-serif;
}

table a{
    color:#039;
    font-weight:bold;
    text-decoration:none;
}

table a:hover{
    color:#000;
    font-weight:bold;
}

th {
    background-color:#b9c9fe;
    color:#039;
    padding: 10px;
}

td {
    background-color:#e8edff;
    padding: 10px;
}

.verticalOption{
    margin:8px 0;
}

.moreOptionsLink{
    background-color:green;
    color:#fff;
    padding: 0 2px;
}

.moreOptionsLink:hover{
    color:#fff;
}

.moreOptions{
    display:none;
}

HTML code – we are using static HTML in this example, in the real world, this HTML should be generated dynamically.

<!-- our example table -->
<table border='0' cellpadding='2'>
    <tr>
        <th>Firstname</th>
        <th>Lastname</th>
        <th>Email</th>
        <th>Username</th>
        <th>Options</th>
    </tr>
    <tr>
        <td>JM</td>
        <td>Dalisay</td>
        <td>jm@gmail.com</td>
        <td>dalisay</td>
        <td>
            <!-- It is important to understand our "Options" HTML structure. -->
            <a href="">Edit</a> / 
            <a href="">Delete</a> /
            <a href="" class="moreOptionsLink">More</a>
            
            <!-- 
                Here are the hidden "moreOptions" 
                    which will be shown when "More" was clicked 
                    and hidden when "Less" was clicked 
            -->
            <div class="moreOptions">
                <div class="verticalOption">
                    <a href="https://codeofaninja.com/" target="_blank">Articles</a>
                </div>
                <div class="verticalOption">
                    <a href="https://codeofaninja.com/" target="_blank">View Online</a>
                </div>
                <div class="verticalOption">
                    <a href="https://codeofaninja.com/" target="_blank">Website</a>
                </div>
                <div class="verticalOption">
                    <a href="https://www.facebook.com/CodeOfANinja" target="_blank">Facebook</a>
                </div>
                <div class="verticalOption">
                    <a href="http://twitter.com/ninjazhai" target="_blank">Twitter</a>
                </div>
                <div class="verticalOption">
                    <a href="https://plus.google.com/103126728967620382717" target="_blank">Google+</a>
                </div>
                <div class="verticalOption">
                    <a href="https://codeofaninja.com/" target="_blank">LinkedIn</a>
                </div>
            </div>
        </td>
    </tr>
    <!-- more table rows should be here -->
</table>

jQuery code – the animation and magic. :)

<!-- include our jQuery -->
<script src="js/jquery-1.9.1.min.js"></script>
<script>
$(document).ready(function(){

    // when "More" or "Less" (class moreOptionsLink) was clicked.
    $(".moreOptionsLink").click(function(){
    
        var txt = $(this).text();
        
        if(txt=='More'){
            /*
             * change the text to "Less"
             * change the background color to "red"
             * which means it shows all the options
             */
            $(this).text('Less');
            $(this).css("background-color","red");
        }
        
        else{
            /*
             * change the text to "More"
             * change the background color to "green"
             * which means it hides other options
             */
            $(this).text('More');
            $(this).css("background-color","green");
        }
        
        /*
         * to animate the container of other options
         * we use jQuery "next" to select the "moreOptions" of the current row
         */
        $(this).next(".moreOptions").slideToggle("fast");
        
        // so that it won't refresh the page
        return false;
    });
});
</script>

Codes combined:

<html>
<head>
    <title>A Way To Solve Long List Of Options Of Your Table Row Data</title>
    
    <!-- just some styling -->
    <style>
    body{
        font-family:arial,sans-serif;
    }
    
    table a{
        color:#039;
        font-weight:bold;
        text-decoration:none;
    }
    
    table a:hover{
        color:#000;
        font-weight:bold;
    }
    
    th {
        background-color:#b9c9fe;
        color:#039;
        padding: 10px;
    }

    td {
        background-color:#e8edff;
        padding: 10px;
    }

    .verticalOption{
        margin:8px 0;
    }
    
    .moreOptionsLink{
        background-color:green;
        color:#fff;
        padding: 0 2px;
    }
    
    .moreOptionsLink:hover{
        color:#fff;
    }
    
    .moreOptions{
        display:none;
    }
    
    </style>
</head>
<body>

<!-- our example table -->
<table border='0' cellpadding='2'>
    <tr>
        <th>Firstname</th>
        <th>Lastname</th>
        <th>Email</th>
        <th>Username</th>
        <th>Options</th>
    </tr>
    <tr>
        <td>JM</td>
        <td>Dalisay</td>
        <td>jm@gmail.com</td>
        <td>dalisay</td>
        <td>
            <!-- It is important to understand our "Options" HTML structure. -->
            <a href="">Edit</a> / 
            <a href="">Delete</a> /
            <a href="" class="moreOptionsLink">More</a>
            
            <!-- 
                Here are the hidden "moreOptions" 
                    which will be shown when "More" was clicked 
                    and hidden when "Less" was clicked 
            -->
            <div class="moreOptions">
                <div class="verticalOption">
                    <a href="https://codeofaninja.com/" target="_blank">Articles</a>
                </div>
                <div class="verticalOption">
                    <a href="https://codeofaninja.com/" target="_blank">View Online</a>
                </div>
                <div class="verticalOption">
                    <a href="https://codeofaninja.com/" target="_blank">Website</a>
                </div>
                <div class="verticalOption">
                    <a href="https://www.facebook.com/CodeOfANinja" target="_blank">Facebook</a>
                </div>
                <div class="verticalOption">
                    <a href="http://twitter.com/ninjazhai" target="_blank">Twitter</a>
                </div>
                <div class="verticalOption">
                    <a href="https://plus.google.com/103126728967620382717" target="_blank">Google+</a>
                </div>
                <div class="verticalOption">
                    <a href="https://codeofaninja.com/" target="_blank">LinkedIn</a>
                </div>
            </div>
        </td>
    </tr>
    <tr>
        <td>Edward</td>
        <td>Morden</td>
        <td>edward_cullen@yahoo.com</td>
        <td>edward</td>
        <td>
            <a href="">Edit</a> / 
            <a href="">Delete</a> /
            <a href="" class="moreOptionsLink">More</a>
            <div class="moreOptions">
                <div class="verticalOption">
                    <a href="https://codeofaninja.com/" target="_blank">Articles</a>
                </div>
                <div class="verticalOption">
                    <a href="https://codeofaninja.com/" target="_blank">View Online</a>
                </div>
                <div class="verticalOption">
                    <a href="https://codeofaninja.com/" target="_blank">Website</a>
                </div>
                <div class="verticalOption">
                    <a href="https://www.facebook.com/CodeOfANinja" target="_blank">Facebook</a>
                </div>
                <div class="verticalOption">
                    <a href="http://twitter.com/ninjazhai" target="_blank">Twitter</a>
                </div>
                <div class="verticalOption">
                    <a href="https://plus.google.com/103126728967620382717" target="_blank">Google+</a>
                </div>
                <div class="verticalOption">
                    <a href="https://codeofaninja.com/" target="_blank">LinkedIn</a>
                </div>
            </div>
        </td>
    </tr>
    <tr>
        <td>Vanessa</td>
        <td>Hudgens</td>
        <td>vane@yahoo.com</td>
        <td>vanessa</td>
        <td>
            <a href="">Edit</a> / 
            <a href="">Delete</a> /
            <a href="" class="moreOptionsLink">More</a>
            <div class="moreOptions">
                <div class="verticalOption">
                    <a href="https://codeofaninja.com/" target="_blank">Articles</a>
                </div>
                <div class="verticalOption">
                    <a href="https://codeofaninja.com/" target="_blank">View Online</a>
                </div>
                <div class="verticalOption">
                    <a href="https://codeofaninja.com/" target="_blank">Website</a>
                </div>
                <div class="verticalOption">
                    <a href="https://www.facebook.com/CodeOfANinja" target="_blank">Facebook</a>
                </div>
                <div class="verticalOption">
                    <a href="http://twitter.com/ninjazhai" target="_blank">Twitter</a>
                </div>
                <div class="verticalOption">
                    <a href="https://plus.google.com/103126728967620382717" target="_blank">Google+</a>
                </div>
                <div class="verticalOption">
                    <a href="https://codeofaninja.com/" target="_blank">LinkedIn</a>
                </div>
            </div>
        </td>
    </tr>
    <tr>
        <td>Michael</td>
        <td>Jackson</td>
        <td>mike@gmail.com</td>
        <td>michael</td>
        <td>
            <a href="">Edit</a> / 
            <a href="">Delete</a> /
            <a href="" class="moreOptionsLink">More</a>
            <div class="moreOptions">
                <div class="verticalOption">
                    <a href="https://codeofaninja.com/" target="_blank">Articles</a>
                </div>
                <div class="verticalOption">
                    <a href="https://codeofaninja.com/" target="_blank">View Online</a>
                </div>
                <div class="verticalOption">
                    <a href="https://codeofaninja.com/" target="_blank">Website</a>
                </div>
                <div class="verticalOption">
                    <a href="https://www.facebook.com/CodeOfANinja" target="_blank">Facebook</a>
                </div>
                <div class="verticalOption">
                    <a href="http://twitter.com/ninjazhai" target="_blank">Twitter</a>
                </div>
                <div class="verticalOption">
                    <a href="https://plus.google.com/103126728967620382717" target="_blank">Google+</a>
                </div>
                <div class="verticalOption">
                    <a href="https://codeofaninja.com/" target="_blank">LinkedIn</a>
                </div>
            </div>
        </td>
    </tr>
</table>

<!-- include our jQuery -->
<script src="js/jquery-1.9.1.min.js"></script>
<script>
$(document).ready(function(){

    // when "More" or "Less" (class moreOptionsLink) was clicked.
    $(".moreOptionsLink").click(function(){
    
        var txt = $(this).text();
        
        if(txt=='More'){
            /*
             * change the text to "Less"
             * change the background color to "red"
             * which means it shows all the options
             */
            $(this).text('Less');
            $(this).css("background-color","red");
        }
        
        else{
            /*
             * change the text to "More"
             * change the background color to "green"
             * which means it hides other options
             */
            $(this).text('More');
            $(this).css("background-color","green");
        }
        
        /*
         * to animate the container of other options
         * we use jQuery "next" to select the "moreOptions" of the current row
         */
        $(this).next(".moreOptions").slideToggle("fast");
        
        // so that it won't refresh the page
        return false;
    });
});
</script>

</body>
</html>

Download Source Code
You can download all the code used in this tutorial for only $9.99 $5.55!

Related Tutorials

Thank you for learning from our post about jQuery slideToggle Example - Solution Row's Long List of Options!

Home Facebook

How Do You Start A Facebook Page?

Hi guys! Most of the top posts here in my blog is related to web development with Facebook. Many asks beforehand how to create a Facebook page where we will pull our data. So here’s a step by step tutorial on how to do such task.

How Do You Start A Facebook Page?

Our final output.

Photos are kinda small, you have to click each photos below to enlarge.

Step 1

Go to Facebook “Create A Page” section that can be found in this link: Create a Page. You should see this page:

Create a Facebook page.

Create a Facebook page.

Step 2

In this example, we are going to create a “Brand or Product” for our website. Click “Brand or Product” box and fill up the required filled.
On the “Category” dropdown, select “Website”.
On the “Brand or Product Name” field, I’ll enter “Mike Dalisay Works” for example.
Check “I agree to Facebook Pages Terms” checkbox.
It should look like this:

Creating a brand or product Facebook page.

Creating a brand or product Facebook page.

Step 3

Click the “Get Started” button. It will make you set up some information for your Facebook page such as profile picture, about, Facebook web address, and enable ads option. Just follow the flow.

Facebook page info set up.

Facebook page info set up.

Facebook page profile picture.

Facebook page profile picture.

Facebook page “About” info

Facebook page “About” info

Facebook web address.

Facebook web address.

Enable ads. You can click the skip button.

Enable ads. You can click the skip button.

Step 4

At this stage, you already have successfully created your Facebook page! Congrats! Now Facebook will give you some guidelines on how to use your Facebook page.

Like your own page.

Like your own page.

Invite others to like your page.

Invite others to like your page.

Do your first post!

Do your first post!

Home Lists+

How To Make Responsive Web Design CSS Code?

In today’s tutorial, I’m going to show you a systematic and very simple way to create a responsive website with CSS3 media queries and HTML5.

Responsive web design has been around for few years now and is widely accepted as a new standard when building a modern website.

Coding A Responsive Website Design

For the “live demo”, please try to resize your browser to see the page’s responsiveness.

I want to give you a brief definition of what a responsive web design is, if you already know what it is, you may skip this part and jump to the “Let’s code” section below. Well, for me, responsive web design is a way to show your web site’s content in an easy-to-understand manner regardless of what device views it.

For example, a visitor of your website must feel comfortable when viewing the same website for any type of devices (with different screen sizes) he has. Example of those devices include:

  • Android phones
  • iPhones
  • 7″ tablets
  • 10″ tablets
  • iPads
  • Desktop computers
  • and many more devices that can view a web page.

Other points to consider…

  • Your website should not have a horizontal scrollbar.
  • Users must not use the zoom tool to view your site’s contents.

By the way, if you want to test the live demo on different devices easily, you can use the tools described on this link: Responsive Web Design Testing Tools.

Let’s code.

Step 1: It is important to build your website for the smallest device possible first. Build the website for smart phones. You can view a live demo of our step 1 here.

<!DOCTYPE HTML>
<html>
     <head>
          <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
          <meta name="viewport" content="width=device-width">
         
          <title>Your Website</title>
         
          <style>
              
          /* misc start */
          *{
               margin:0px;
               padding:0px
          }
         
          body{
               font-family:"Lucida Sans Unicode", "Lucida Grande", sans-serif;
          }
         
          .media1140px{
               background-color:#CE9429;
          }
         
          .media768px{
               background-color:#EDD49A;
          }
         
          .media480px{
               background-color:#EFEF34;
          }
         
          .media300px{
               background-color:#82EAFF;
          }
         
          .media1140px, .media768px, .media480px, .media300px{
               padding:15px;
          }
         
          p{
               margin:0 0 20px 0;
          }
         
          .clearb{
               clear:both;
          }
          /* misc end */
         
         
         
         
         
         
          /* header start */
          #mainHeader{
               background-color:#82EAFF;
               padding:0.5em;
               overflow:auto;
          }
          
          /* to make our logo resize automatically */
          #responsiveLogo{
               width:100%;
          }
         
          #responsiveLogo img{
               max-height: 100%;
               max-width: 100%;
          }
          /* header end */
         
         
         
         
         
          /* navigation start */
          nav{
               float:left;
               width:100%;
          }
         
          nav ul{
               list-style-type:none;
               padding:0;
          }

          nav ul li{
         
          }

          nav ul li a{
               background-color:green;
               border:thin solid #fff;
               color:#fff;
               display:block;
               height:3em;
               line-height:3em;
               text-align:center;
               text-decoration:none;
               width:100%;
          }
         
          nav ul li a:hover{
               background-color:yellow;
               color:#000;
          }
          /* navigation end */
         
         
         
         
         
          /* middle section start */
          #mainSection{
               background-color: #D9F8F2;
               float: left;
               width: 96%;
          }
         
          #sideBox1{
               background-color: #C9A449;
               width: 96%;
          }
         
          #mainSection, #sideBox1{
               overflow: auto;
               padding:2%;
          }
          /* middle section end */
         
         
         
          /* footer start */
          footer{
               background-color:orange;
               height:50px;
               line-height:50px;
               text-align:center;
               width:100%;
          }
          /* footer end */
              
          </style>
         
     </head>
<body>

     <header id='mainHeader'>
    
          <div id='responsiveLogo'>
               <img src='images/logo4.png' />
          </div>
          <nav>
               <ul>
                    <li><a href="#home">Home</a></li>
                    <li><a href="#news">News</a></li>
                    <li><a href="#contact">Contact</a></li>
                    <li><a href="#about">About</a></li>
               </ul>
          </nav>
     </header>
    
     <section id='mainSection'>

          <article>
               <header>
                    <h2>About The Code Of A Ninja</h2>
                    <p>Posted on <time datetime="2003-01-01T16:31:24+02:00">January 1st, 2013</time> by <a href="#">Mike</a> - <a href="#comments">173 comments</a></p>
               </header>
               <p>
                    <div class='media1140px'>@media 1140px</div>
                    <div class='media768px'>@media 768px</div>
                    <div class='media480px'>@media 480px</div>
                    <div class='media300px'>@media 300px</div>
               </p>
               <p>
                    My name is Mike Dalisay, a 22 year old Software Developer (<a href="http://en.wikipedia.org/wiki/Web_developer">Web</a> and
                    <a href="http://developer.android.com/index.html">Android</a>) from The Philippines.
                    My posts here are mainly notes to self and for <i>anyone else</i> that may find them useful.
               </p>
               <p>
                    This blog contains programming tutorials, codes, demos, scripts, how-to's, tips, tricks, code downloads and other fun stuff
                    related to web and android apps <a href="http://en.wikipedia.org/wiki/Software_development">development</a>.
               </p>
               <p>
                    Most of my time is spent with PHP, MySQL, AJAX, HTML, CSS, jQuery, JavaScript, XML, Web Design, Android, JAVA and some
                    other Open source software projects related to Web and Android apps development.
               </p>
               <p>
                    You can leave a comment, <a href="http://twitter.com/ninjazhai">follow</a> or <a href="https://www.facebook.com/pages/the-code-of-a-ninja/107786425949934">subscribe</a>
                    to this blog. Take care. :) 
               </p>
          </article>

     </section>

     <aside id='sideBox1'>
          <h2>The Blogger</h2>
          <p>This is your side bar. You can add your information or links here.</p>
     </aside>

     <div class='clearb'></div>
    
     <footer>
          <p>Copyright 2013 - Game Note</p>
     </footer>

</body>
</html>

After doing the code above, our webpage is not yet responsive. You won’t see the magic even if you resize your browser. By the way, you can also include the CSS code as external file.

Step 2: Now let’s create the website layout for a type of device next to a smart phone, maybe we can consider a 7″ tablets as one. You can view a live demo of your step 2 here.

We’ll just add the following CSS:

/* 
-can be for 7 inch tablets
-This CSS will apply for devices with the minimum width of 480 pixels
 */
@media only screen and (min-width: 480px) {
     #mainHeader {
          background-color:#EFEF34;
     }
    
     nav ul li{
          float:left;
          width:25%;
     }
}

Now if you’ll resize your browser, you can see that your website is already responsive in two ways.

Step 3: Now we will create the website layout for another type of screen next to 7″ tablets, we can consider the iPad or 10″ tablets in portrait mode. Our step 3 live demo is here.

Please add the following CSS:

/*
-10 inch tablets
-This CSS will apply for devices with the minimum width of 768 pixels
*/
@media only screen and (min-width: 768px) {
     #mainHeader {
          background-color:#EDD49A;
     }
    
     #mainSection{
          float: left;
          width: 61%;
     }
    
     #sideBox1{
          float: right;
          width: 30%;
     }
    
}

Now our website is responsive in three ways. Try to re-size your browser again.

Step 4: Now we will create the website for desktop computers, laptops or 10″ tablets in landscape mode.

/*
-Desktop computers
-This CSS will apply for devices with the minimum width of 1140 pixels
*/
@media only screen and (min-width: 1140px) {
     #mainHeader {
          background-color:#CE9429;
     }
    
     #responsiveLogo{
          float:left;
          width:30%;
     }
    
     nav{
          float:left;
          width:70%;
     }
    
     nav ul{
          margin:1.5em 0 0 0;
     }
}

Complete web page code:

<!DOCTYPE HTML>
<html>
     <head>
          <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
          <meta name="viewport" content="width=device-width">
         
          <title>Your Website</title>
         
          <style>
              
          /* misc start */
          *{
               margin:0px;
               padding:0px
          }
         
          body{
               font-family:"Lucida Sans Unicode", "Lucida Grande", sans-serif;
          }
         
          .media1140px{
               background-color:#CE9429;
          }
         
          .media768px{
               background-color:#EDD49A;
          }
         
          .media480px{
               background-color:#EFEF34;
          }
         
          .media300px{
               background-color:#82EAFF;
          }
         
          .media1140px, .media768px, .media480px, .media300px{
               padding:15px;
          }
         
          p{
               margin:0 0 20px 0;
          }
         
          .clearb{
               clear:both;
          }
          /* misc end */
         
         
         
         
         
         
          /* header start */
          #mainHeader{
               background-color:#82EAFF;
               padding:0.5em;
               overflow:auto;
          }
         
          #responsiveLogo{
               width:100%;
          }
         
          #responsiveLogo img{
               max-height: 100%;
               max-width: 100%;
          }
          /* header end */
         
         
         
         
         
          /* navigation start */
          nav{
               float:left;
               width:100%;
          }
         
          nav ul{
               list-style-type:none;
               padding:0;
          }

          nav ul li{
         
          }

          nav ul li a{
               background-color:green;
               border:thin solid #fff;
               color:#fff;
               display:block;
               height:3em;
               line-height:3em;
               text-align:center;
               text-decoration:none;
               width:100%;
          }
         
          nav ul li a:hover{
               background-color:yellow;
               color:#000;
          }
          /* navigation end */
         
         
         
         
         
          /* middle section start */
          #mainSection{
               background-color: #D9F8F2;
               float: left;
               width: 96%;
          }
         
          #sideBox1{
               background-color: #C9A449;
               width: 96%;
          }
         
          #mainSection, #sideBox1{
               overflow: auto;
               padding:2%;
          }
          /* middle section end */
         
         
         
          /* footer start */
          footer{
               background-color:orange;
               height:50px;
               line-height:50px;
               text-align:center;
               width:100%;
          }
          /* footer end */
         
         
         
         
         
         
         
          /* @media start */
         
          /* we don't need to specify for smartphones, that's our default layout */
         
          /*
          -7 inch tablets
          -This CSS will apply for devices with the minimum width of 480 pixels
          */
          @media only screen and (min-width: 480px) {
               #mainHeader {
                    background-color:#EFEF34;
               }
              
               nav ul li{
                    float:left;
                    width:25%;
               }
          }
         
          /*
          -10 inch tablets
          -This CSS will apply for devices with the minimum width of 768 pixels
          */
          @media only screen and (min-width: 768px) {
               #mainHeader {
                    background-color:#EDD49A;
               }
              
               #mainSection{
                    float: left;
                    width: 61%;
               }
              
               #sideBox1{
                    float: right;
                    width: 30%;
               }
              
              
          }
         
          /*
          -Desktop computers
          -This CSS will apply for devices with the minimum width of 1140 pixels
          */
          @media only screen and (min-width: 1140px) {
               #mainHeader {
                    background-color:#CE9429;
               }
              
               #responsiveLogo{
                    float:left;
                    width:30%;
               }
              
               nav{
                    float:left;
                    width:70%;
               }
              
               nav ul{
                    margin:1.5em 0 0 0;
               }
          }
         
          /* @media end */
              
          </style>
         
     </head>
<body>

     <header id='mainHeader'>
    
          <div id='responsiveLogo'>
               <img src='images/logo4.png' />
          </div>
          <nav>
               <ul>
                    <li><a href="#home">Home</a></li>
                    <li><a href="#news">News</a></li>
                    <li><a href="#contact">Contact</a></li>
                    <li><a href="#about">About</a></li>
               </ul>
          </nav>
     </header>
    
     <section id='mainSection'>

          <article>
               <header>
                    <h2>About The Code Of A Ninja</h2>
                    <p>Posted on <time datetime="2003-01-01T16:31:24+02:00">January 1st, 2013</time> by <a href="#">Mike</a> - <a href="#comments">173 comments</a></p>
               </header>
               <p>
                    <div class='media1140px'>@media 1140px</div>
                    <div class='media768px'>@media 768px</div>
                    <div class='media480px'>@media 480px</div>
                    <div class='media300px'>@media 300px</div>
               </p>
               <p>
                    My name is Mike Dalisay, a 22 year old Software Developer (<a href="http://en.wikipedia.org/wiki/Web_developer">Web</a> and
                    <a href="http://developer.android.com/index.html">Android</a>) from The Philippines.
                    My posts here are mainly notes to self and for <i>anyone else</i> that may find them useful.
               </p>
               <p>
                    This blog contains programming tutorials, codes, demos, scripts, how-to's, tips, tricks, code downloads and other fun stuff
                    related to web and android apps <a href="http://en.wikipedia.org/wiki/Software_development">development</a>.
               </p>
               <p>
                    Most of my time is spent with PHP, MySQL, AJAX, HTML, CSS, jQuery, JavaScript, XML, Web Design, Android, JAVA and some
                    other Open source software projects related to Web and Android apps development.
               </p>
               <p>
                    You can leave a comment, <a href="http://twitter.com/ninjazhai">follow</a> or <a href="https://www.facebook.com/pages/the-code-of-a-ninja/107786425949934">subscribe</a>
                    to this blog. Take care. :) 
               </p>
          </article>

     </section>

     <aside id='sideBox1'>
          <h2>The Blogger</h2>
          <p>This is your side bar. You can add your information or links here.</p>
     </aside>

     <div class='clearb'></div>
    
     <footer>
          <p>Copyright 2013 - Game Note</p>
     </footer>

</body>
</html>

Download Source Code

You can download all the code used in this tutorial for only $9.99 $5.55!

Some screenshots of our output:

Page header smartphone screenshot – landscape mode

Page header smartphone screenshot – landscape mode

Footer screenshot from my smartphone in landscape mode.

Footer screenshot from my smartphone in landscape mode.

Header screenshot from my smartphone  in portrait mode.

Header screenshot from my smartphone
in portrait mode.

Body section screenshot from my Smartphone in  portrait mode.

Body section screenshot from
my Smartphone in portrait mode.

Footer screenshot from  my smartphone in portrait mode.

Footer screenshot from
my smartphone in portrait mode.

Screenshot from my 10.1 Android tablet in portrait mode.

Screenshot from my 10.1 Android tablet in portrait mode.

Credits: Image from Game Note.

Home jQuery

FbAlbumPreview jQuery Plugin

Hi there guys! Today I want to share with you a jQuery plugin that I made.

This jQuery plugin will enable your users to preview your web albums instantly.

My inspiration here is the Facebook albums, if you have a Facebook account (I’m sure you have, haha!) and wanted to view the list of albums, you can experience this functionality:

For me, above is a very simple Facebook feature and yet, it’s awesome. It is very convenient for a user to have an album preview just by doing a hover.
Here’s our index.html code:

<html>
    <head>
        <title>FB Album Preview jQuery Plugin by https://codeofaninja.com/</title>
        <!– add some styles –>
        <link rel=‘stylesheet’ type=‘text/css’ href=‘css/style.css’ />
       
    </head>
<body>

<h3>
    Demo of FB Album Preview jQuery Plugin by <a href=‘https://codeofaninja.com/’>The Code Of A Ninja</a>
</h3>


<!– -You can generate all these HTML and JS codes using your server side script -The number of photos or thumbnails to be previewed depends on you –>

<div id=‘mainContent’>

    <!– album # 1 –>

<div class=‘albumDetails’>

<div class=“fbAlbum”>
            <!– the first image is the album cover photo –>
            <img class=“active” src=“images/1.jpg” />
            <img src=“images/2.jpg” />
            <img src=“images/3.jpg” />
            <img src=“images/4.jpg” />
            <img src=“images/5.jpg” />
        </div>


<div class=‘albumTitle’><a href=”>Profile Picture</a></div>


<div class=‘photosNum’>5 photos</div>

    </div>

   
    <!– album # 2 –>

<div class=‘albumDetails’>

<div class=“fbAlbum”>
            <!– the first image is the album cover photo –>
            <img class=“active” src=“images/6.jpg” />
            <img src=“images/7.jpg” />
            <img src=“images/8.jpg” />
        </div>


<div class=‘albumTitle’><a href=”>Mobile Uploads</a></div>


<div class=‘photosNum’>3 photos</div>

    </div>

   
    <!– album # 3 –>

<div class=‘albumDetails’>

<div class=“fbAlbum”>
            <!– the first image is the album cover photo –>
            <img class=“active” src=“images/9.jpg” />
            <img src=“images/10.jpg” />
            <img src=“images/11.jpg” />
            <img src=“images/12.jpg” />
        </div>


<div class=‘albumTitle’><a href=”>Wall Photos</a></div>


<div class=‘photosNum’>4 photos</div>

    </div>

   
</div>


<!– include jQuery library and our FB album preview plugin –>
<script src=“js/jquery.min.js”></script>
<script src=“js/fb.album.preview.js”></script>

<!– this is how we’re gonna use the plugin –>
<script type=‘text/javascript’>
$(document).ready(function(){
    // since all albums images container are under the class ‘fbAlbum’,
    // that’s what we are gonna user as the selector
    $(‘.fbAlbum’).FbAlbumPreview();
});
</script>

</body>
</html>

Our CSS code:

body{
    font-family: ‘helvetica neue’, helvetica, arial, sans-serif;
}

.fbAlbum {
    position:relative;
    width:206px;
    height:206px;
    cursor:pointer;
}

.fbAlbum IMG {
    position:absolute;
    top:0;
    left:0;
    z-index:8;
    width:206px;
    height:206px;
}

.fbAlbum IMG.active {
    z-index:10;
}

.fbAlbum IMG.last-active {
    z-index:9;
}
           
.albumDetails{
    float:left;        
    width:206px;
    height:270px;
    margin:20px;
}

.albumTitle{
    font-family: ‘helvetica neue’, helvetica, arial, sans-serif;
    white-space: nowrap;
    font-weight:bold;
    font-size:14px;
    padding:10px 0 5px 0;
    text-align:center;
   
}

.albumTitle a{
    text-decoration:none;
    color:#3B5998;
}

.albumTitle a:hover{
    text-decoration:underline;
}

.photosNum{
    color:gray;
    line-height:19px;
    font-size:11px;
    text-align:center;
    font-family: ‘lucida grande’, tahoma, verdana, arial, sans-serif;
}

#mainContent{
    width:750px;
    margin:0 auto;
    margin-top:100px;
}

.clearb{
    clear:both;
}

Customization code: Yes, you can supply values to customize the view and fade speed effect of this plugin. The default is viewSpeed = 1000 and fadeSpeed = 500. viewSpeed should always be greater than fadeSpeed.

   $(‘.fbAlbum’).FbAlbumPreview({
        viewSpeed: 800,
        fadeSpeed: 400
    });

viewSpeed – refers to how long the user can take a look at the thumbnail image
fadeSpeed – how long the transition (fade effect) from one image to another will take place

FbAlbumPreview jQuery plugin Code (compressed)

/*FbAlbumPreview jQuery Plugin by Mike Dalisay - https://codeofaninja.com/ */
(function(a) {
    a.fn.FbAlbumPreview = function(b) {
        var c = a.extend({
            viewSpeed: 1e3,
            fadeSpeed: 500
        }, b);
        return this.each(function() {
            var b;
            var d = c.fadeSpeed;
            var e = false;
            a(this).hover(function() {
                var f = a(this);
                b = setInterval(function() {
                    f.find("IMG").show();
                    var a = f.find("IMG.active");
                    if (a.length == 0) {
                        a = f.find("IMG:last")
                    }
                    var b = a.next().length ? a.next() : f.find("IMG:first");
                    a.addClass("last-active");
                    b.css({
                        opacity: 0
                    }).addClass("active").animate({
                        opacity: 1
                    }, d, function() {
                        a.removeClass("active last-active");
                        e = true
                    })
                }, c.viewSpeed)
            }, function() {
                clearInterval(b);
                if (e == true) {
                    var c = a(this);
                    c.find("img").hide();
                    c.find("IMG.active").removeClass("active");
                    var f = c.find("IMG:first").fadeOut(d).fadeIn(d).addClass("active");
                    e = false
                }
            })
        })
    }
})(jQuery)

Download Source Codes
You can download all the code used in this tutorial for only $9.99 $5.55!

Related Tutorials

Thank you for learning from our post about FbAlbumPreview jQuery Plugin.

Home Facebook

Display Facebook Feed on Website Using PullFB Class

Update: Hi guys! I'm working on a new version of this code. Here's a sample LIVE DEMO. Let me know what you think! I'm going to post a new code and tutorial soon!

Hello guys! Today we are going to pull your Facebook page recent updates and display it to your website or to a webpage. This feature looks like a twitter widget (example is “My Twitter Updates” on the right sidebar of this site), but the posts were pulled from your Facebook page. This is good if you don’t want to use this Facebook Like Box social plugin and just want to show your page updates.

I updated the PullFB class a bit, to do this requirement. As I remember, this is one of the most requested feature, haha!
Our page_feeds.php code:

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″/>
        <title>The Code Of A Ninja – Pull Feeds From Facebook</title>
        <link href=”http://demo.codeofaninja.com/images/favicon.ico” rel=”SHORTCUT ICON”>
        <link rel=”stylesheet” type=”text/css” href=”css/style.css” />

    </head>
<body>

<div style=’font-size: 16px; font-weight: bold; margin: 0 0 10px 0;’>
    This demo is synchronized with this
    <a href=’https://www.facebook.com/CodeOfANinja’ target=’_blank’>
        Code of a Ninja Official Facebook Page Feed
    </a>
</div>

<?php
//change as you needed
date_default_timezone_set(‘Asia/Manila’);

echo “<p>Recent Updates from The Code of a Ninja</p>”;

//get page number
//if page num was not set, default to page 1
$page_num = isset( $_GET['page'] ) ? $_GET['page'] : 1;

//include our class
include ‘pull_fb.class.php’;

//pass appId, appSecret, and page number (anyway, we’re not using paging here)
$pull_fb = new PullFb( ‘change_to_your_app_id’, ‘change_to_your_app_secret’, $page_num );

//pass your fan page id
$feeds_result = $pull_fb->getFeeds( ’107786425949934′ );

//echo “<div>{$feeds_result->entries}</div>”;

foreach( $feeds_result->entries as $entries ){
    //just some time manipulation to suit my needs
    $ts = strtotime( “{$entries->published} +60 minutes” );

    echo “<div class=’object_item’ style=’text-align:left;’>”;
        //just for the sake of styling
        echo str_replace( “<br/><br/>”, “<br/>”, $entries->content );
        echo “<div class=’published_details’>”;
            echo “Published on “ . date( ‘m-d-Y H:i:s’, $ts );
            echo ” | <a href=’” . $entries->alternate . “‘ target=’_blank’>FB Link</a>”;
        echo “</div>”;
    echo “</div>”;

}
?>

  </body>
</html>

You can just copy and paste our updated PullFb class if you want. The code looks like this now:

<?php
require ‘fb-sdk/src/facebook.php’;

class PullFb{

    //set properties
    public $facebook;
    public $page_num;

    //number of items you want to see per page
    //you can add for other objects such as videos, etc.
    public $albums_per_page = 2;
    public $photos_per_page = 4;

    //if you want to exclude some albums like the Profile Pictures and Wall Photos, do something like:
    //$excluded_albums = “AND name <> ‘Profile Pictures’ AND name <> ‘Wall Photos’”;
    //in my example, I’m gonna exclude the wall photos only
    public $excluded_albums = “AND name <> ‘Wall Photos’”;

    //same with excluding photos, just state the pid
    public $excluded_photos = “AND pid <> ’221167777906963_1513599′ AND pid <> ’221167777906963_1513596′”;

    public function __construct( $appId, $secret, $page_num ){

        //create facebook instance
        $this->facebook = new Facebook(array(
          ‘appId’  => $appId,
          ‘secret’ => $secret,
          ‘cookie’ => true, // enable optional cookie support
        ));

        //for the page number
        $this->page_num = $page_num;
    }

    //get feeds in json format and then decode it using json_decode function
    public function getFeeds( $id ){
        $url = “https://www.facebook.com/feeds/page.php?id={$id}&format=json”;
        $feeds = json_decode( file_get_contents( $url ) );
        return $feeds;
    }

    //this will get facebook albums based on the $owner or fan page id
    public function getAlbums( $owner ){

        //we have to get the total number of albums first
        //i don’t know why the count function is not working
        $fql = “SELECT aid FROM album WHERE owner = {$owner} {$this->excluded_albums}“;

        //calculatePaging() will give us the paging settings
        //pass the fql and type of object
        $settings = $this->calculatePaging( $fql, ‘album’ );

        //get start and end limit for the next fql query
        $start_limit = $settings['start_limit'];
        $end_limit = $settings['end_limit'];

        //in this query we will include the paging based on the page number
        $fql = “SELECT
                    aid, object_id, owner, cover_pid, cover_object_id, name, created, modified,
                    description, location, size, link, visible, modified_major, edit_link,
                    type, can_upload, photo_count, video_count,
                    like_info, comment_info
                FROM
                    album
                WHERE
                    owner = {$owner} {$this->excluded_albums}
                LIMIT
                    {$start_limit}, {$end_limit}“;

        //set params
        $params = array(
            ‘method’ => ‘fql.query’,
            ‘query’ => $fql,
            ‘callback’ => ”
        );

        //get recordset
        $result = $this->facebook->api( $params );

        //we will include the settings to our result variable
        $result['pull_fb'] = $settings;

        return $result;
    }

    //this function was made for paging
    public function calculatePaging( $fql, $type ){

        //set the params based on passed fql
        //to count the total number of records
        $params = array(
            ‘method’ => ‘fql.query’,
            ‘query’ => $fql,
            ‘callback’ => ”
        );

        //get recordset
        $result = $this->facebook->api( $params );

        //get the total number of items
        $number_of_items = count( $result );

        //we will have the following calculations for the pagination
        //we just need some simple math

        //decide how many albums to show per page
        //values was actually declared as class property
        //you can easily add for other types of object
        if( $type == ‘album’ ){
            $items_per_page = $this->albums_per_page;
        }else if( $type == ‘photo’ ){
            $items_per_page = $this->photos_per_page;
        }

        //this is the current page
        $curr_page = $this->page_num;

        //previous page will be the current page MINUS one
        $prev_page = $curr_page - 1;

        //next page will be the current page PLUS one
        $next_page = $curr_page + 1;

        //no need to calculate for the first page, obviously, it’s 1
        //calculate last page
        $last_page = round( $number_of_items / $items_per_page );

        //detect if prev button will be visible
        if( $curr_page != 1 ){
            $prev_button = true;
        }

        //get $albums_shown value
        //it is the number of photos from the first page up to the current page
        $items_shown = $items_per_page * $curr_page;

        //detect if next button will be visible
        //if the $number_of_albums were still higher than the $albums_shown, show the next page button,
        //but if they are equal, don’t show the next page button
        if( $number_of_items > $items_shown ){
            $next_button = true;
        }

        //get start limit for the fql query
        $start_limit = $items_per_page * $prev_page;

        //get end limit
        //i’m not sure why i had to + 1, maybe it’s a facebook bug?
        $end_limit = $items_per_page + 1;

        //these are the values or settings returned
        //i made it to an array
        $settings = array(
            ‘number_of_items’ => $number_of_items,
            ‘prev_page’ => $prev_page,
            ‘next_page’ => $next_page,
            ‘prev_button’ => $prev_button,
            ‘next_button’ => $next_button,
            ‘start_limit’ => $start_limit,
            ‘end_limit’ => $end_limit,
            ‘last_page’ => $last_page
        );

        return $settings;
    }

    //to get photos of an album, we have to pass the album id
    public function getPhotos( $album_id ){

        //we have to get total number of photos first
        //i don’t know why the count function is not working
        $fql = “SELECT object_id FROM photo WHERE aid = ‘” . $album_id .“‘ ORDER BY position DESC”;

        //calculatePaging() will give us the paging settings
        //pass the fql and type of object, this is ‘photo’
        $settings = $this->calculatePaging( $fql, ‘photo’ );

        //get start and end limit for the next fql query
        $start_limit = $settings['start_limit'];
        $end_limit = $settings['end_limit'];

        //query the photos
        $fql = “SELECT
                        object_id, pid, src_small, src, src_big, link, caption, created, modified, position, like_info, comment_info
                    FROM
                        photo
                    WHERE
                        aid = ‘” . $album_id .“‘ {$this->excluded_photos}
                    ORDER BY
                        position DESC
                    LIMIT
                        {$start_limit}, {$end_limit}“;

        //set the parameters
        $params = array(
            ‘method’ => ‘fql.query’,
            ‘query’ => $fql,
            ‘callback’ => ”
        );

        //get photos recordset
        $result = $this->facebook->api( $params );

        //add the settings to the result
        $result['pull_fb'] = $settings;

        return $result;
    }

    //to get album cover, you need to pass the cover_id or id of the photo
    public function getAlbumCover( $cover_pid ){

        //get album cover query
        $fql = “select src_big from photo where pid = ‘” . $cover_pid . “‘”;

        $params = array(
            ‘method’ => ‘fql.query’,
            ‘query’ => $fql,
            ‘callback’ => ”
        );

        //run the query
        $result = $this->facebook->api( $params );

        //the the value and return it
        $value = $result[0]['src_big'];

        return $value;
    }

    //to get comments, you need to pass the object id, it can be a video, photo, album etc
    //check the fql tables to know object id https://developers.facebook.com/docs/reference/fql/
    public function getComments( $object_id ){

        //query the comment
        $fql = “SELECT
                text, time, fromid, likes
            FROM
                comment
            WHERE
                object_id = “ . $object_id;

        //set parameters
        $params = array(
            ‘method’ => ‘fql.query’,
            ‘query’ => $fql,
            ‘callback’ => ”
        );

        //get recordset
        $result = $this->facebook->api( $params );

        return $result;
    }

    //to get profile name, you need to pass fromid or the profile id
    public function getProfileName( $fromid ){
        //query commenter / profile name
        $fql = “SELECT
                name
            FROM
                profile
            WHERE
                id = “ . $fromid;

        //set the paramters
        $params = array(
            ‘method’ => ‘fql.query’,
            ‘query’ => $fql,
            ‘callback’ => ”
        );

        //get the resulting value
        $result = $this->facebook->api( $params );
        $value = $result[0]['name'];

        return $value;
    }

    //this time we will just get the profile name and profile thumbnail
    public function getProfileDetails( $fromid ){

        //select name and pic_square which can be used as profile thumbnail
        $fql = “SELECT
                name, pic_square
            FROM
                profile
            WHERE
                id = “ . $fromid;

        //set parameters
        $params = array(
            ‘method’ => ‘fql.query’,
            ‘query’ => $fql,
            ‘callback’ => ”
        );

        //get and return the result
        $result = $this->facebook->api( $params );

        return $result;
    }

    //to get album name, pass the album id
    public function getAlbumName( $aid ){

        //query album name
        $fql = “SELECT
                name
            FROM
                album
            WHERE
                aid = ‘{$aid}‘”;

        //set parameters
        $params = array(
            ‘method’ => ‘fql.query’,
            ‘query’ => $fql,
            ‘callback’ => ”
        );

        //return result value for album name
        $result = $this->facebook->api( $params );
        $value = $result[0]['name'];

        return $value;
    }

    //to get events, pass the uid or you fan page id
    public function getEvents( $uid ){
        //query the events
        //we will eid, name, pic_big, start_time, end_time, location, description  this time
        //but there are other data that you can get on the event table (https://developers.facebook.com/docs/reference/fql/event/)
        //as you’ve noticed, we have TWO select statement here
        //since we can’t just do “WHERE creator = your_fan_page_id”.
        //only eid is indexable in the event table, so we have to retrieve
        //list of events by eids
        //and this was achieved by selecting all eid from
        //event_member table where the uid is the id of your fanpage.
        //*yes, you fanpage automatically becomes an event_member
        //once it creates an event
        $fql = “SELECT
                    eid, name, pic_big, start_time, end_time, location, description
                FROM
                    event
                WHERE
                    eid IN ( SELECT eid FROM event_member WHERE uid = {$uid} )
                ORDER BY start_time asc”;

        //set parameters
        $param = array(
            ‘method’ => ‘fql.query’,
            ‘query’ => $fql,
            ‘callback’ => ”
        );

        //get recordset and retur results
        $result = $this->facebook->api($param);
        return $result;
    }

    //this function will get the profile invited to the event
    //pass eid or event id
    public function getEventMembers( $eid ){

        //query the members
        $fql = “SELECT
                    eid, uid, rsvp_status
                FROM
                    event_member
                where eid = {$eid}“;

        //set params
        $param = array(
            ‘method’ => ‘fql.query’,
            ‘query’ => $fql,
            ‘callback’ => ”
        );

        //get result and return it
        $result = $this->facebook->api( $param );
        return $result;
    }

    //get the videos
    //pass the owner or the fan page id
    public function getVideos( $owner ){

        //query to get videos
        //specify you fan page id, I got 221167777906963
        //you can also use the LIMIT clause here if you want to show limited number of videos only
        $fql = “SELECT
                    vid, owner, title, description, thumbnail_link,
                    embed_html, updated_time, created_time, link
                FROM
                    video
                WHERE owner={$owner}“;

        //set parameters
        $param = array(
            ‘method’ => ‘fql.query’,
            ‘query’ => $fql,
            ‘callback’ => ”
        );

        //get recordset and return it
        $result = $this->facebook->api($param);
        return $result;
    }

}
?>

Thanks for reading this [post title here]!

Home Facebook

Display Facebook Data To Website Using PullFb Class

Update: Hi guys! The script on this page is not actively developed anymore, but we have the alternatives! Learn how to display Facebook page data using our links below:

Hi guys! Today I’m going to post about this class I made for pulling data from your Facebook fan page.

In this post we are going to pull data such as photo albums, photos, events, event members, videos and their corresponding likes and comments.

I previously posted about pulling Facebook photos, events and videos with separate but simple methods.

Now this class (pull_fb.class.php), tries to work out all those functions in one with some newly added features.

Display Facebook Data To Website Using PullFb Class

Facebook Database – Facebook API – Your Website

Some people says the old Facebook PHP SDK (2.1.2) don’t work so I used the latest PHP SDK version 3.0.1 that can be downloaded on GitHub. And for this post, the you can download the code I used here:

DOWNLOAD CODE

Facebook Photos

For pulling Facebook albums and photos to website, this version has some new features which includes Facebook like count, comments, comments like count and pagination. Here’s a sample code on how I used the PullFb class to achieve it.

LIVE DEMO

Our index.php code:

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″/>
        <title>The Code Of A Ninja – Pull Photos From Facebook</title>
        <link href=”http://demo.codeofaninja.com/images/favicon.ico” rel=”SHORTCUT ICON”>
        <link rel=”stylesheet” type=”text/css” href=”css/style.css” />
       
    </head>
<body>

<div style=’font-size: 16px; font-weight: bold; margin: 0 0 10px 0;’>
    This demo is synchronized with this
    <a href=’https://www.facebook.com/pages/COAN-Dummy-Page/221167777906963?sk=photos’>
        Dummy Page Album
    </a>
</div>

<?php
echo “<p>COAN Dummy Page Albums</p>”;

//get page number
//if page num was not set, default to page 1
$page_num = isset( $_GET['page'] ) ? $_GET['page'] : 1;

//include our class
include ‘pull_fb.class.php’;

//pass appId, appSecret, and page number
$pull_fb = new PullFb( ‘change_to_your_app_id’, ‘change_to_your_app_secret’, $page_num );

//pass your fan page id
$album_result = $pull_fb->getAlbums( ’221167777906963′ );

//loop through the albums
foreach( $album_result as $key => $value ){
   
    if( trim( $key ) != ‘pull_fb’ ){ //because pull_fb is the settings for paging
   
        //pass album cover photo id to get album cover image
        $album_cover = $pull_fb->getAlbumCover( $value['cover_pid'] );
       
        //display the album details
        echo “<div class=’object_item’>”;
           
            //album cover
            echo “<div class=’field_item’ style=’height:auto;’>”;
                echo “<div class=’lbl’>Album Cover Photo:</div>”;
                echo “<a href=’show_photos.php?aid=” . $value['aid'] . “‘>”;
                    echo “<img src=’$album_cover‘ border=’1′ width=’400px’>”;
                echo “</a>”;
            echo “</div>”;
           
            //album name
            echo “<div class=’field_item’>”;
                echo “<div class=’lbl’>Album Name:</div>”;
                echo “<div class=’val’>” . $value['name'] . “</div>”;
            echo “</div>”;
           
            //album date created
            echo “<div class=’field_item’>”;
                echo “<div class=’lbl’>Album Created Date:</div>”;
                echo “<div class=’val’>” . date( ‘l, F d, Y h:i:s A’, $value['created'] ) . “</div>”;
            echo “</div>”;

            //description
            echo “<div class=’field_item’>”;
                echo “<div class=’lbl’>Album Description:</div>”;
                $description = empty( $value['description'] ) ? “N/A” : $value['description'];
                echo “<div class=’val’>” . $description . “</div>”;
            echo “</div>”;
           
            //where album photos were taken
            echo “<div class=’field_item’>”;
                echo “<div class=’lbl’>Album Location:</div>”;
                $location = empty( $value['location'] ) ? “N/A” : $value['location'];
                echo “<div class=’val’>” . $location . “</div>”;
            echo “</div>”;
           
            //link to facebook
            echo “<div class=’field_item’>”;
                echo “<div class=’lbl’>Album FB Link:</div>”;
                echo “<div class=’val’><a href=’” . $value['link'] . “‘ target=’_blank’>Click Here!</a></div>”;
            echo “</div>”;
           
            //how many photos in the album
            echo “<div class=’field_item’>”;
                echo “<div class=’lbl’>Album Photo Count:</div>”;
                echo “<div class=’val’>” . $value['photo_count'] . “</div>”;
            echo “</div>”;
           
            //videos included in the album
            echo “<div class=’field_item’>”;
                echo “<div class=’lbl’>Album Video Count:</div>”;
                echo “<div class=’val’>” . $value['video_count'] . “</div>”;
            echo “</div>”;
           
            //number of likes
            echo “<div class=’field_item’>”;
                echo “<div class=’lbl’>Album Like Count:</div>”;
                echo “<div class=’val’>” . $value['like_info']['like_count'] . ” people like this album</div>”;
            echo “</div>”;
           
            //number of comments
            echo “<div class=’field_item’ style=’height:auto;’>”;
                echo “<div class=’lbl’>Album Comment Count:</div>”;
                echo “<div class=’val’>” . $value['comment_info']['comment_count'] . ” comments</div>”;
           
            //pass the album object id to get comments
            $comments_result = $pull_fb->getComments( $value['object_id'] );
           
            //loop through comments
            foreach( $comments_result as $key => $value ){
           
                //you can set values to variables
                $text = $value['text'];
                $time = date( ‘l, F d, Y h:i:s A’, $value['time'] );
                $fromid = $value['fromid'];
                $likes = $value['likes'];
               
                //get commenter’s name by passing pass fromid
                $profile_name = $pull_fb->getProfileName( $fromid );
               
                //display the comment details
                echo “<div style=’display:block; text-align:left; float:left; border-bottom:thin solid blue; width:100%;’>”;
                    echo “<div>”;
                   
                        //provide link to commenter’s profile
                        echo “<a href=’https://www.facebook.com/profile.php?id={$fromid}‘ target=’_blank’>”;
                            echo “{$profile_name}“;
                        echo “</a>”;
                        echo ” says:”;
                       
                    echo “</div>”;
                   
                    //display comment
                    echo “<div style=’font-style:italic;’>{$text}</div>”;
                   
                    //the time and number of likes of the comment
                    echo “<div>{$time} | {$likes} people liked this comment</div>”;
                echo “</div>”;
               
            }
           
            echo “<div style=’clear:both;’></div>”;
            echo “</div>”;
        echo “</div>”; //end object_item
        echo “<div style=’clear:both;’></div>”;
    }
   
}

//paging here
//show the page buttons based on the settings returned from getAlbums()
echo “<div style=’font-size:24px;’>”;
    //paging here  
    if( $value['prev_button'] ){
        echo “<a href=’index.php?page=1′>&#9668;&#9668; First</a> “;
        echo “<a href=’index.php?page={$value['prev_page']}‘>&#9668; Previous</a> “;
    }
   
    if( $value['next_button'] ){
        echo “<a href=’index.php?page={$value['next_page']}‘>Next &#9658;</a> “;
        echo “<a href=’index.php?page={$value['last_page']}‘>Last &#9658;&#9658;</a>”;
    }
echo “</div>”;

?>

  </body>
</html>

Our show_photos.php code

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″/>
        <title>The Code Of A Ninja – Pull Data From Facebook</title>
        <link href=”http://demo.codeofaninja.com/images/favicon.ico” rel=”SHORTCUT ICON”>
        <link rel=”stylesheet” type=”text/css” href=”css/style.css” />
       
    </head>
<body>

<div style=’font-size: 16px; font-weight: bold; margin: 0 0 10px 0;’>
    This demo is synchronized with this
    <a href=’https://www.facebook.com/pages/COAN-Dummy-Page/221167777906963?sk=photos’>
        Dummy Page Album
    </a>
</div>

<?php
//get page number
//if page num was not set, default to page 1
$page_num = isset( $_GET['page'] ) ? $_GET['page'] : 1;

//get album id from the url
$album_id = empty( $_REQUEST['aid'] ) ? die( “Album ID cannot be empty” ) : $_REQUEST['aid'];

//include our class
include ‘pull_fb.class.php’;
   
//pass appId, appSecret, and page number
$pull_fb = new PullFb( ‘change_to_your_app_id’, ‘change_to_your_app_secret’, $page_num );

//get the album name based on album id
$album_name = $pull_fb->getAlbumName( $album_id );

//provide link to albums
echo “<div><a href=’http://demo.codeofaninja.com/tutorials/pull-facebook-data/’>Back To Albums</a> | Album Name: <b>” . $album_name . “</b></div>”;

//get photos of the album
$photos_result = $pull_fb->getPhotos( $album_id );

//loop through the photos
foreach( $photos_result as $key => $value ){
   
    if( trim( $key ) != ‘pull_fb’ ){ //because pull_fb is the settings
   
        //set caption to ‘None.’ if no caption was set
        $caption = !empty( $value['caption'] ) ? $value['caption'] : “None.”;
       
        //display the photo details
        echo “<div class=’object_item’>”;
       
            //the photo
            echo “<div class=’field_item’ style=’height:auto;’>”;
                echo “<div class=’lbl’>Photo:</div>”;
                echo “<a href=““ . $value['src_big'] . ““ title=““ . $caption . ““ rel=’lightbox’>”;
                    echo “<img src=’” . $value['src_big'] . “‘ border=’1′ width=’400px’ />”;
                echo “</a>”;
            echo “</div>”;
           
            //caption
            echo “<div class=’field_item’>”;
                echo “<div class=’lbl’>Photo ID:</div>”;
                echo “<div class=’val’>” . $value['pid'] . “</div>”;
            echo “</div>”;
           
            //caption
            echo “<div class=’field_item’>”;
                echo “<div class=’lbl’>Caption:</div>”;
                echo “<div class=’val’>” . $caption . “</div>”;
            echo “</div>”;
           
            //date created
            echo “<div class=’field_item’>”;
                echo “<div class=’lbl’>Album Created Date:</div>”;
                echo “<div class=’val’>” . date( ‘l, F d, Y’, $value['created'] ) . “</div>”;
            echo “</div>”;

            //date modified
            echo “<div class=’field_item’>”;
                echo “<div class=’lbl’>Album Modified Date:</div>”;
                echo “<div class=’val’>” . date( ‘l, F d, Y’, $value['modified'] ) . “</div>”;
            echo “</div>”;
           
            //photo position in the album
            echo “<div class=’field_item’>”;
                echo “<div class=’lbl’>Photo Position:</div>”;
                echo “<div class=’val’>” . $value['position'] . “</div>”;
            echo “</div>”;
           
            //link to facebook
            echo “<div class=’field_item’>”;
                echo “<div class=’lbl’>Album FB Link:</div>”;
                echo “<div class=’val’>”;
                    echo “<a href=’” . $value['link'] . “‘ target=’_blank’>Click Here!</a>”;
                echo “</div>”;
            echo “</div>”;
           
            //number of likes
            echo “<div class=’field_item’>”;
                echo “<div class=’lbl’>Album Like Count:</div>”;
                echo “<div class=’val’>” . $value['like_info']['like_count'] . ” people like this</div>”;
            echo “</div>”;
           
            //number of comments
            echo “<div class=’field_item’ style=’height:auto;’>”;
                echo “<div class=’lbl’>Album Comment Count:</div>”;
                echo “<div class=’val’>” . $value['comment_info']['comment_count'] . ” comments</div>”;
               
                //pass the object id to get comments of this photo
                $comments_result = $pull_fb->getComments( $value['object_id'] );
               
                //loop through retrieved comments
                foreach( $comments_result as $key => $value ){
               
                    //you can set the values to variables
                    $text = $value['text'];
                    $time = date( ‘l, F d, Y h:i:s A’, $value['time'] );
                    $fromid = $value['fromid'];
                    $likes = $value['likes'];
                   
                    //get commenter’s name by passing pass fromid
                    $profile_name = $pull_fb->getProfileName( $fromid );
                   
                    //display the comment details
                    echo “<div style=’display:block; text-align:left; float:left; border-bottom:thin solid blue; width:100%;’>”;
                        echo “<div>”;
                            //provide link to commenter’s profile
                            echo “<a href=’https://www.facebook.com/profile.php?id={$fromid}‘ target=’_blank’>”;
                                echo “{$profile_name}“;
                            echo “</a>”;
                            echo ” says:”;
                        echo “</div>”;
                       
                        //display comment
                        echo “<div style=’font-style:italic;’>{$text}</div>”;
                       
                        //the time and number of likes of the comment
                        echo “<div>{$time} | {$likes} people liked this comment</div>”;
                    echo “</div>”;
                   
                }
               
                echo “<div style=’clear:both;’></div>”;
               
            echo “</div>”;
           
        echo “</div>”;
   
    }
   
}

    //paging here
    //show the page buttons based on the settings returned from getPhotos()
    echo “<div style=’font-size:24px;’>”;
       
        if( $value['prev_button'] ){
            echo “<a href=’show_photos.php?aid={$_GET['aid']}&page=1′>&#9668;&#9668; First</a> “;
            echo “<a href=’show_photos.php?aid={$_GET['aid']}&page={$value['prev_page']}‘>&#9668; Previous</a> “;
        }
       
        if( $value['next_button'] ){
            echo “<a href=’show_photos.php?aid={$_GET['aid']}&page={$value['next_page']}‘>Next &#9658;</a> “;
            echo “<a href=’show_photos.php?aid={$_GET['aid']}&page={$value['last_page']}‘>Last &#9658;&#9658;</a>”;
        }
    echo “</div>”;
   
?>

    <!– START JLIGHTBOX –>
   
    <link rel=”stylesheet” type=”text/css” href=”jQuery-lightbox/css/jquery.lightbox-0.5.css” media=”screen” />
    <script type=”text/javascript” src=”jQuery-lightbox/js/jquery.js”></script>
    <script type=”text/javascript” src=”jQuery-lightbox/js/jquery.lightbox-0.5.js”></script>
   
    <script type=”text/javascript”>
   
        $(function() {
            $(‘a[@rel*=lightbox]‘).lightBox(); // Select all links that contains lightbox in the attribute rel
        });
   
    </script>
   
    <!– END JLIGHTBOX –>
   
  </body>
</html>

Facebook Events

For pulling Facebook events, it features pulling the event members and their corresponding RSVP status. As for the paging, maybe you can do the same approach I used in pulling Facebook albums and photos.

LIVE DEMO

Our show_events.php code:

<!DOCTYPE html>
<html xmlns=”http://www.w3.org/1999/xhtml”
    xmlns:fb=”http://www.facebook.com/2008/fbml”>
        <head>
            <meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″/>
            <title>The Code Of A Ninja – Pull Events From Facebook</title>
            <link href=”http://demo.codeofaninja.com/images/favicon.ico” rel=”SHORTCUT ICON”>
            <link rel=”stylesheet” type=”text/css” href=”css/style.css” />
        </head>
<body>
<?php

//get page number
//if page num was not set, default to page 1
$page_num = isset( $_GET['page'] ) ? $_GET['page'] : 1;

//we have to set timezone to California
date_default_timezone_set(‘America/Los_Angeles’);

//include our class
include ‘pull_fb.class.php’;

//pass appId, appSecret, and page number
$pull_fb = new PullFb( ‘change_to_your_app_id’, ‘change_to_your_app_secret’, $page_num );

//just a heading
echo “<div style=’font-weight: bold; margin: 0 0 20px 0;’>”;
echo “This event list is synchronized with this “;
echo “<a href=’https://www.facebook.com/pages/COAN-Dummy-Page/221167777906963?sk=events’>”;
echo “COAN Dummy Page Events</a></div>”;

//pass your fan page id
$event_result = $pull_fb->getEvents( ’221167777906963′ );

//looping through retrieved data
foreach( $event_result as $key => $value ){

    //see here http://php.net/manual/en/function.date.php for the date format I used
    //The pattern string I used ‘l, F d, Y g:i a’
    //will output something like this: July 30, 2015 6:30 pm

    //getting ‘start’ and ‘end’ date,
    //’l, F d, Y’ pattern string will give us
    //something like: Thursday, July 30, 2015
    $start_date = date( ‘l, F d, Y’, $value['start_time'] );
    $end_date = date( ‘l, F d, Y’, $value['end_time'] );

    //getting ‘start’ and ‘end’ time
    //’g:i a’ will give us something
    //like 6:30 pm
    $start_time = date( ‘g:i a’, $value['start_time'] );
    $end_time = date( ‘g:i a’, $value['end_time'] );

    //display the album details
    echo “<div class=’object_item’>”;
   
    //event image
    echo “<div style=’float: left; margin: 0 8px 0 0;’>”;
            echo “<img src={$value['pic_big']} />”;
    echo “</div>”;
       
        echo “<div style=’float: left;’>”;
           
            //event name
            echo “<div class=’field_item’>”;
                echo “<div class=’val’ style=’font-size: 26px’>”;
                    echo “<a href=’https://www.facebook.com/events/{$value['eid']}/’ target=’_blank’>”;
                        echo $value['name'];
                    echo “</a>”;
                echo “</div>”;
            echo “</div>”;
           
            //event date / time
            echo “<div class=’field_item’>”;
                echo “<div class=’val’>”;
                if( $start_date == $end_date ){
                        //if $start_date and $end_date is the same
                        //it means the event will happen on the same day
                        //so we will have a format something like:
                        //July 30, 2015 – 6:30 pm to 9:30 pm
                        echo “on {$start_date} – {$start_time} to {$end_time}“;
                }else{
                        //else if $start_date and $end_date is NOT the equal
                        //it means that the event will will be
                        //extended to another day
                        //so we will have a format something like:
                        //July 30, 2013 9:00 pm to Wednesday, July 31, 2013 at 1:00 am
                        echo “on {$start_date} {$start_time} to {$end_date} at {$end_time}“;
                }
                echo “</div>”;
            echo “</div>”;
           
            //event location
            echo “<div class=’field_item’>”;
                echo “<div class=’lbl’>Location:</div>”;
                echo “<div class=’val’>” . $value['location'] . “</div>”;
            echo “</div>”;
           
            //event description
            echo “<div class=’field_item’>”;
                echo “<div class=’lbl’>More Info:</div>”;
                echo “<div class=’val’>” . $value['description'] . “</div>”;
            echo “</div>”;
       
            echo “<div style=’clear: both’></div>”;
           
            //get people invited to the event
            $event_members = $pull_fb->getEventMembers( $value['eid'] );
           
            //loop through event members
            foreach( $event_members as $event_member ){
           
                //get profile pic and name of the event member
                $result = $pull_fb->getProfileDetails( $event_member['uid'] );
                $pic_square = $result[0]['pic_square'];
                $name = $result[0]['name'];
               
                //display event member details
                echo “<div style=’padding:8px 0; text-align:left;’>”;
               
                    //small square profile pic
                    echo “<div style=’float:left; width:40px;’>”;
                        echo “<img src=’{$pic_square}‘ width=’30px’ height=’30px’ />”;
                    echo “</div>”;
                   
                    //provide link to event member profile
                    echo “<div>Name: “;
                        echo “<a href=’https://www.facebook.com/profile.php?id={$event_member['uid']}‘ target=’_blank’>”;
                            echo $name;
                        echo “</a>”;
                    echo “</div>”;
                   
                    //rsvp status
                    echo “<div>RSVP Status: {$event_member['rsvp_status']}</div>”;
                   
                echo “</div>”;
            }
           
        echo “</div>”;
   
    echo “<div style=’clear: both’></div>”;
   
    echo “</div>”;
       
}

?>
</body>
</html>

Facebook Videos

For pulling Facebook videos, it features pulling the comments and likes. As for the paging, maybe you can do the same approach I used in pulling Facebook albums and photos.

LIVE DEMO

Our show_videos.php code:

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″/>
        <title>The Code Of A Ninja – Pull Videos From Facebook</title>
        <link href=”http://demo.codeofaninja.com/images/favicon.ico” rel=”SHORTCUT ICON”>
        <link rel=”stylesheet” type=”text/css” href=”css/style.css” />
    </head>
<body>

<div class=’page_title’>
    These videos are synchronized with this
    <a href=’https://www.facebook.com/video/?id=221167777906963′ target=’_blank’>
        Dummy Page Videos
    </a>
</div>
<?php

//get page number
//if page num was not set, default to page 1
$page_num = isset( $_GET['page'] ) ? $_GET['page'] : 1;

//include our class
include ‘pull_fb.class.php’;

//pass appId, appSecret, and page number
$pull_fb = new PullFb( ‘change_to_your_app_id’, ‘change_to_your_app_secret’, $page_num );

//pass your fan page id
$videos_result = $pull_fb->getVideos( ’221167777906963′ );

//loop through each videos
foreach( $videos_result as $keys => $value ){
   
    //display video details
    echo “<div class=’object_item’>”;
   
        //video embed html
        echo $value['embed_html'];
       
        //video title
        echo “<div class=’field_item’>”;
            echo “<div class=’lbl’>Title:</div>”;
            echo “<div class=’val’>” . $value['title'] . “</div>”;
        echo “</div>”;
       
        //date created
        echo “<div class=’field_item’>”;
            echo “<div class=’lbl’>Date Created:</div>”;
            echo “<div class=’val’>” . date( ‘l, F d, Y’, $value['created_time'] ) . “</div>”;
        echo “</div>”;
       
        //video description
        echo “<div class=’field_item’>”;
            echo “<div class=’lbl’>Description:</div>”;
            echo “<div class=’val’>” . $value['description'] . “</div>”;
        echo “</div>”;
       
        //fb link to video
        echo “<div class=’field_item’>”;
            echo “<div class=’lbl’>FB Link:</div>”;
            echo “<div class=’val’><a href=’” . $value['link'] . “‘ target=’_blank’>Click Here!</a></div>”;
        echo “</div>”;
                   
        echo “<div class=’field_item’ style=’height:auto;’>”;
       
        //vid is the object id of video, pass to get the comments
        $comments_result = $pull_fb->getComments( $value['vid'] );
       
        //loop through comments
        foreach( $comments_result as $key => $value ){
       
            //you can set values to variables
            $text = $value['text'];
            $time = date( ‘l, F d, Y h:i:s A’, $value['time'] );
            $fromid = $value['fromid'];
            $likes = $value['likes'];
           
            //get commenter’s name by passing pass fromid
            $profile_name = $pull_fb->getProfileName( $fromid );
           
            //display the comment details
            echo “<div style=’display:block; text-align:left; float:left; border-bottom:thin solid blue; width:100%;’>”;
                echo “<div>”;
                    //provide link to commenter’s profile
                    echo “<a href=’https://www.facebook.com/profile.php?id={$fromid}‘ target=’_blank’>”;
                        echo “{$profile_name}“;
                    echo “</a>”;
                    echo ” says:”;
                echo “</div>”;
               
                //display comment
                echo “<div style=’font-style:italic;’>{$text}</div>”;
               
                //the time and number of likes of the comment
                echo “<div>{$time} | {$likes} people liked this comment</div>”;
            echo “</div>”;
           
        }

        echo “<div style=’clear:both;’></div>”;
        echo “</div>”;
        echo “</div>”;
    echo “</div>”;
   
}

?>
   
  </body>
</html>

June 9, 2012 Update: Display Facebook Feed on Website

PullFB Class

Now here’s the code of our class pull_fb.class.php

<?php
require ‘fb-sdk/src/facebook.php’;

class PullFb{
   
    //set properties
    public $facebook;
    public $page_num;
   
    //number of items you want to see per page
    //you can add for other objects such as videos, etc.
    public $albums_per_page = 2;
    public $photos_per_page = 4;
   
    //if you want to exclude some albums like the Profile Pictures and Wall Photos, do something like:
    //$excluded_albums = “AND name <> ‘Profile Pictures’ AND name <> ‘Wall Photos’”;
    //in my example, I’m gonna exclude the wall photos only
    public $excluded_albums = “AND name <> ‘Wall Photos’”;
   
    //same with excluding photos, just state the pid
    public $excluded_photos = “AND pid <> ’221167777906963_1513599′ AND pid <> ’221167777906963_1513596′”;
   
    public function __construct( $appId, $secret, $page_num ){
       
        //create facebook instance
        $this->facebook = new Facebook(array(
          ‘appId’  => $appId,
          ‘secret’ => $secret,
          ‘cookie’ => true, // enable optional cookie support
        ));
       
        //for the page number
        $this->page_num = $page_num;
    }
   
    //this will get facebook albums based on the $owner or fan page id
    public function getAlbums( $owner ){
       
        //we have to get the total number of albums first
        //i don’t know why the count function is not working
        $fql = “SELECT aid FROM album WHERE owner = {$owner} {$this->excluded_albums}“;
       
        //calculatePaging() will give us the paging settings
        //pass the fql and type of object
        $settings = $this->calculatePaging( $fql, ‘album’ );
       
        //get start and end limit for the next fql query
        $start_limit = $settings['start_limit'];
        $end_limit = $settings['end_limit'];
       
        //in this query we will include the paging based on the page number
        $fql = “SELECT
                    aid, object_id, owner, cover_pid, cover_object_id, name, created, modified,
                    description, location, size, link, visible, modified_major, edit_link,
                    type, can_upload, photo_count, video_count,
                    like_info, comment_info
                FROM
                    album
                WHERE
                    owner = {$owner} {$this->excluded_albums}
                LIMIT
                    {$start_limit}, {$end_limit}“;
                   
        //set params
        $params = array(
            ‘method’ => ‘fql.query’,
            ‘query’ => $fql,
            ‘callback’ => ”
        );
       
        //get recordset
        $result = $this->facebook->api( $params );
       
        //we will include the settings to our result variable
        $result['pull_fb'] = $settings;
       
        return $result;
    }

    //this function was made for paging
    public function calculatePaging( $fql, $type ){
   
        //set the params based on passed fql
        //to count the total number of records
        $params = array(
            ‘method’ => ‘fql.query’,
            ‘query’ => $fql,
            ‘callback’ => ”
        );
       
        //get recordset
        $result = $this->facebook->api( $params );
       
        //get the total number of items
        $number_of_items = count( $result );
       
        //we will have the following calculations for the pagination
        //we just need some simple math
       
        //decide how many albums to show per page
        //values was actually declared as class property
        //you can easily add for other types of object
        if( $type == ‘album’ ){
            $items_per_page = $this->albums_per_page;
        }else if( $type == ‘photo’ ){
            $items_per_page = $this->photos_per_page;
        }
       
        //this is the current page
        $curr_page = $this->page_num;
       
        //previous page will be the current page MINUS one
        $prev_page = $curr_page - 1;
       
        //next page will be the current page PLUS one
        $next_page = $curr_page + 1;
       
        //no need to calculate for the first page, obviously, it’s 1
        //calculate last page
        $last_page = round( $number_of_items / $items_per_page );
       
        //detect if prev button will be visible
        if( $curr_page != 1 ){
            $prev_button = true;
        }
       
        //get $albums_shown value
        //it is the number of photos from the first page up to the current page
        $items_shown = $items_per_page * $curr_page;
       
        //detect if next button will be visible
        //if the $number_of_albums were still higher than the $albums_shown, show the next page button,
        //but if they are equal, don’t show the next page button
        if( $number_of_items > $items_shown ){
            $next_button = true;
        }
       
        //get start limit for the fql query
        $start_limit = $items_per_page * $prev_page;
       
        //get end limit
        //i’m not sure why i had to + 1, maybe it’s a facebook bug?
        $end_limit = $items_per_page + 1;
       
        //these are the values or settings returned
        //i made it to an array
        $settings = array(
            ‘number_of_items’ => $number_of_items,
            ‘prev_page’ => $prev_page,
            ‘next_page’ => $next_page,
            ‘prev_button’ => $prev_button,
            ‘next_button’ => $next_button,
            ‘start_limit’ => $start_limit,
            ‘end_limit’ => $end_limit,
            ‘last_page’ => $last_page
        );
       
        return $settings;
    }
   
    //to get photos of an album, we have to pass the album id
    public function getPhotos( $album_id ){

        //we have to get total number of photos first
        //i don’t know why the count function is not working
        $fql = “SELECT object_id FROM photo WHERE aid = ‘” . $album_id .“‘ ORDER BY position DESC”;
       
        //calculatePaging() will give us the paging settings
        //pass the fql and type of object, this is ‘photo’
        $settings = $this->calculatePaging( $fql, ‘photo’ );
       
        //get start and end limit for the next fql query
        $start_limit = $settings['start_limit'];
        $end_limit = $settings['end_limit'];
       
        //query the photos
        $fql = “SELECT
                        object_id, pid, src_small, src, src_big, link, caption, created, modified, position, like_info, comment_info
                    FROM
                        photo
                    WHERE
                        aid = ‘” . $album_id .“‘ {$this->excluded_photos}
                    ORDER BY
                        position DESC
                    LIMIT
                        {$start_limit}, {$end_limit}“;
       
        //set the parameters
        $params = array(
            ‘method’ => ‘fql.query’,
            ‘query’ => $fql,
            ‘callback’ => ”
        );

        //get photos recordset
        $result = $this->facebook->api( $params );
       
        //add the settings to the result
        $result['pull_fb'] = $settings;
       
        return $result;
    }
   
    //to get album cover, you need to pass the cover_id or id of the photo
    public function getAlbumCover( $cover_pid ){
   
        //get album cover query
        $fql = “select src_big from photo where pid = ‘” . $cover_pid . “‘”;
       
        $params = array(
            ‘method’ => ‘fql.query’,
            ‘query’ => $fql,
            ‘callback’ => ”
        );
       
        //run the query
        $result = $this->facebook->api( $params );
       
        //the the value and return it
        $value = $result[0]['src_big'];
       
        return $value;
    }
   
    //to get comments, you need to pass the object id, it can be a video, photo, album etc
    //check the fql tables to know object id https://developers.facebook.com/docs/reference/fql/
    public function getComments( $object_id ){
   
        //query the comment
        $fql = “SELECT
                text, time, fromid, likes
            FROM
                comment
            WHERE
                object_id = “ . $object_id;
       
        //set parameters
        $params = array(
            ‘method’ => ‘fql.query’,
            ‘query’ => $fql,
            ‘callback’ => ”
        );
       
        //get recordset
        $result = $this->facebook->api( $params );
       
        return $result;
    }
   
    //to get profile name, you need to pass fromid or the profile id
    public function getProfileName( $fromid ){
        //query commenter / profile name
        $fql = “SELECT
                name
            FROM
                profile
            WHERE
                id = “ . $fromid;
       
        //set the paramters
        $params = array(
            ‘method’ => ‘fql.query’,
            ‘query’ => $fql,
            ‘callback’ => ”
        );
       
        //get the resulting value
        $result = $this->facebook->api( $params );
        $value = $result[0]['name'];
       
        return $value;
    }
   
    //this time we will just get the profile name and profile thumbnail
    public function getProfileDetails( $fromid ){
   
        //select name and pic_square which can be used as profile thumbnail
        $fql = “SELECT
                name, pic_square
            FROM
                profile
            WHERE
                id = “ . $fromid;
       
        //set parameters
        $params = array(
            ‘method’ => ‘fql.query’,
            ‘query’ => $fql,
            ‘callback’ => ”
        );
       
        //get and return the result
        $result = $this->facebook->api( $params );
       
        return $result;
    }
   
    //to get album name, pass the album id
    public function getAlbumName( $aid ){
   
        //query album name
        $fql = “SELECT
                name
            FROM
                album
            WHERE
                aid = ‘{$aid}‘”;
       
        //set parameters
        $params = array(
            ‘method’ => ‘fql.query’,
            ‘query’ => $fql,
            ‘callback’ => ”
        );
       
        //return result value for album name
        $result = $this->facebook->api( $params );
        $value = $result[0]['name'];
       
        return $value;
    }
   
    //to get events, pass the uid or you fan page id
    public function getEvents( $uid ){
        //query the events
        //we will eid, name, pic_big, start_time, end_time, location, description  this time
        //but there are other data that you can get on the event table (https://developers.facebook.com/docs/reference/fql/event/)
        //as you’ve noticed, we have TWO select statement here
        //since we can’t just do “WHERE creator = your_fan_page_id”.
        //only eid is indexable in the event table, so we have to retrieve
        //list of events by eids
        //and this was achieved by selecting all eid from
        //event_member table where the uid is the id of your fanpage.
        //*yes, you fanpage automatically becomes an event_member
        //once it creates an event
        $fql = “SELECT
                    eid, name, pic_big, start_time, end_time, location, description
                FROM
                    event
                WHERE
                    eid IN ( SELECT eid FROM event_member WHERE uid = {$uid} )
                ORDER BY start_time asc”;
                               
        //set parameters
        $param = array(
            ‘method’ => ‘fql.query’,
            ‘query’ => $fql,
            ‘callback’ => ”
        );

        //get recordset and retur results
        $result = $this->facebook->api($param);
        return $result;
    }
   
    //this function will get the profile invited to the event
    //pass eid or event id
    public function getEventMembers( $eid ){
       
        //query the members
        $fql = “SELECT
                    eid, uid, rsvp_status
                FROM
                    event_member
                where eid = {$eid}“;
       
        //set params
        $param = array(
            ‘method’ => ‘fql.query’,
            ‘query’ => $fql,
            ‘callback’ => ”
        );
       
        //get result and return it
        $result = $this->facebook->api( $param );
        return $result;
    }
   
    //get the videos
    //pass the owner or the fan page id
    public function getVideos( $owner ){
   
        //query to get videos
        //specify you fan page id, I got 221167777906963
        //you can also use the LIMIT clause here if you want to show limited number of videos only
        $fql = “SELECT
                    vid, owner, title, description, thumbnail_link,
                    embed_html, updated_time, created_time, link
                FROM
                    video
                WHERE owner={$owner}“;
                   
        //set parameters
        $param = array(
            ‘method’ => ‘fql.query’,
            ‘query’ => $fql,
            ‘callback’ => ”
        );
       
        //get recordset and return it
        $result = $this->facebook->api($param);
        return $result;
    }
   
}
?>

This class can be easily modified or extend depending on your needs. You can play around different Facebook tables. Thanks for all your comments, suggestions, catches and contributions from the previous version. Feel free to do that again. :)

Regarding “Headers already sent…” issues, you can learn more fixing that here.

Note: A lot of you is trying this script in localhost, I think this won’t work. Please use this script on your real web host or buy from this bluehost link. Thanks!

Home PHP

Append Subtitle/Caption Image Using PHP and Hide It with CSS

Note: People say it isn’t actually a watermark, the image appended can be called a “Caption” or “Hidden Subtitle”. So in this post, when I say “watermark”, it refers to the ”Caption” or “Hidden Subtitle”.
Nowadays I see many websites with image contents. Funny images, interesting images, cosplay, art and many more kinds of images. Many people don’t want to hotlink or copy the image link and share it to any social networking site such as Facebook, instead they copy or download the image (using browser’s “Save image as” option) and upload it to their own account without linking it to the source or website where they found it.

One solution websites do is to append a watermark on their images. The don’t want this watermark to be shown on their website but they want it to appear when the user went to the actual image link or when this image was copied or downloaded.
An example website the does this is 9gag.com. When you see the image on their site, it does not have any watermark. But when you try to save the image, the watermark will appear, appended at the bottom part of the image, it is in white background.
Today we’re going to do a code the does something like that.

DOWNLOAD CODE LIVE DEMO

  • Append a watermark at the bottom part of the image using PHP
  • Hide it using CSS

First, we need to prepare:

  • Sample image – the image you want to put a watermark
  • Watermark image – the image that will be put as watermark on the sample image
    • As for the sample image, we’re going to use this image of my pets (yes, my pets):

      Append Subtitle/Caption Image Using PHP and Hide It with CSS

      For the watermark image:

      This will be appended on the main image

      This will be appended on the main image

      Some notes:

      • “sample.jpg” and “watermark.jpg” should be your variable
      • PHP GD library should be enabled on your server

      Our index.php, we are going to have the following code:

      <?php
      
          //set the header
          header( "Content-type: image/jpg" );
      
          //get image sizes first
          $image_size = getimagesize( "sample.jpg" );
          $watermark_size = getimagesize( "watermark.jpg" );
      
          $image_size_width = $image_size[0];
          $image_size_height = $image_size[1];
      
          $watermark_size_width = $watermark_size[0];
          $watermark_size_height = $watermark_size[1];
      
          //create images
          $main_img = imagecreatefromjpeg( "sample.jpg" );
          $watermark = imagecreatefromjpeg( "watermark.jpg" );
      
          //create canvas
          $canvas = imagecreatetruecolor(
      
              $image_size_width, //width of main image
              $image_size_height + $watermark_size_height //this is the new height, height of main image plus watermark image
          ) or die('Cannot Initialize new GD image stream.');
      
          
          //set white background of canvas
          $bg = imagecolorallocate( $canvas, 255, 255, 255 );
          imagefill ( $canvas, 0, 0, $bg );
      
      
          //paste main image to the canvas
          imagecopymerge(
              $canvas, 
              $main_img, 
              0, //main_img x coordinate ( distance from left side of main_img )
              0, //main_img y coordinate ( distance form top of main_img )
              0, //main_img x coordinate image ( distance from left side of main_img )
              0, //main_img y coordinate image ( distance from top side of main_img )
              $image_size_width, //main_img width
              $image_size_height, //main_img height
              100 //the opacity of main_img
      
          );
      
          //paste the watermark image to the canvas
          imagecopymerge(
              $canvas, 
              $watermark, 
              0, //watermark x coordinate ( distance from left side of main_img )
              $image_size_height, //watermark y coordinate ( distance form top of main_img )
              0, //watermark x coordinate image ( distance from left side of watermark )
              0, //watermark y coordinate image ( distance from top side of watermark ) 
              $watermark_size_width, //watermark width
              $watermark_size_height, //watermark height
              100 //the opacity of watermark
      
          );
      
          //show the new image
          imagejpeg( $canvas );
      
          //if you want to save it to your server directory, just add the second param
          //something like:
          //imagejpeg($canvas, 'your_directory/new_img.jpg');
      
          imagedestroy( $canvas );
          imagedestroy( $main_img );
          imagedestroy( $watermark );
      
      ?>
      

      new_img

      Now, we are going to the second part of this post. We are going to show the output image on a webpage, but the watermark is hidden using CSS.

      Our page.php should have the following code:

      <html>
      
          <head>
      
              <title></title>
      
          </head>
      
      <body>
      
          <div style='font-weight:bold; font-size:18px;'>The image below has a watermark, but it was hidden.</div>
          <div style='margin:5px 0;'>Try to go to the actual image by doing 'open image in new tab' or downloading it.</div>
      
      
          <div style='overflow:hidden;'>
      
              <!-- -30px here is the height of our watermark -->
              <img src='new_img.jpg' style='margin:0 0 -30px 0;' />
      
          </div>
      
      </body>
      </html>
      

      See the live demo for the output! :)

Past Month Traffic Details By Google Analytics

Hi guys! Earlier, I (accidentally) checked out our website’s Google Analytics account. I was surprised and happy about what I saw. 
The Stats
For the past month, we got almost 12 thousand unique visitors, more than 14 thousand visits and more than 22 thousand page views. For me these statistics are very encouraging. I realized that I can help other people by writing something about programming. I feel like today, I’m realizing my dream of being a teacher in the future.

Click to enlarge. This link could help us undertand these data.

The Sources

Most of the traffic we got are from search engines, so I thank Google, Bing, Yahoo Search and the like for bringing more people to our website. Second source of traffic are from referral links, so I thank those people who liked, tweeted, shared and linked our posts to Facebook, Twitter, Stackoverflow, DZone, Hacker News and other websites that are linked to our place. Third source of traffic is the direct traffic, thanks for bookmarking, subscribing and returning here guys! 
Click to enlarge.
The New Perspective
Since I’m encouraged and inspired by your positive feedbacks, I will blog more high quality contents (Hmm, maybe as often as every week?) that can be useful for different level of programmers and not just short code snippets or quick tips. I will still reply to your comments depending on my available time. Yes, I’m also aware of negative feedbacks on this site but I prefer to look at it in a positive way. For me, negative feedbacks are great opportunities to learn something. 
Regarding code snippets or quick tips or fast posts, I’d still love to blog about it. I believe they are helpful too. Little code blocks with a little story or experience. I’ll blog these things on a different website or sub domain, something like php.codeofaninja.com, jquery.codeofaninja.com or android.codeofaninja.com. I just want to put more high quality posts as much as possible on our main website codeofaninja.com 
Again, thanks guys! See you!