Share Tweet Reccomend

JavaScript: Apply and Call Methods

In what follows we are going to look at 2 different JavaScript methods used when dealing with functions: apply and call. Apply and call are essentially used to call a function elsewhere in your code * using the arguments of another function as the arguments for calling that other function *. So if you were inside a function and needed to do some sort of process that figured out something about the arguments of your current function, you could use apply or call. The only real practical difference is that “apply” passes the arguments as a single array and “call” passes each of the arguments individually as separate arguments.

Let’s take a look at the following…

function calculateMyTotal(number1, number2){
    return number1 + number2;
}
function sumArguments1(num1, num2){
    return calculateMyTotal.apply(this, [num1, num2]);  //passing in array
}

Here you can see we have called the calculateMyTotal function and have used the arguments of the current function as the arguments to pass into another function. The “this” just means this current function — in this case, sumArguments1. Another powerful and useful feature of using the apply and call methods is the ability to change what the “this” pointer points to. When you use apply and call, “this” becomes the function/object you are passing into the apply and call methods. It may not be immediately apparent from our simple demonstrations, but it can be very useful if used properly in other instances.

So, getting back to our example, if we were to do…

sumArguments1(1,2);
sumArguments1(4,8)

The results would be 3 and 12.

Because JavaScript functions all have an arguments property (which is a sequential array-like object of the arguments passed into the function), you could just as easily say…

function sumArguments1 (num1, num2) {
    return calculateMyTotal.apply(this, arguments);    //passing in arguments object
}

You don’t even necessarily have to use apply on “this” current function. What if we had another function…

function favoriteNumbers(num1, num2) {
    return 'My favorite numbers are ' + num1 + ' and ' + num2;
} 

Now, elsewhere in your code, we could pass favoriteNumbers in as the function. You could say…

calculateMyTotal.apply(favoriteNumbers, [3,4]); // needs pass in array as 2nd argument 

This will give you 7 even though favoriteNumbers is a function that has nothing to do with adding 2 numbers together.

The call method is similar, but instead of using an array as the second argument, you have to use each argument individually. So if we were to do the same as our previous example we could do…

calculateMyTotal.call(favoriteNumbers, 3,4); // passing each number as a separate argument

Which will also give us 7. It’s the same result, but which one you want to use depends on what kind of function you are trying to pass into apply or call (or it might even come down to personal preference). Either way, you can see that you can use a function’s arguments and apply them to another function, or call another function using them.

Share Tweet Reccomend

Creating a Facebook “Like” Box in WordPress

In what follows, we’re going to take a look at how to create a Facebook Like Box in WordPress. If you create a Facebook Like box on the Facebook developer’s page, Facebook will give you some code to paste into your website. Something like the following…

<iframe src="//www.facebook.com/plugins/likebox.php?href=http%3A%2F%2Fwww.facebook.com%2Fplatform&width=292&height=590&show_faces=true&colorscheme=light&stream=true&border_color&header=true" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:292px; height:590px;" allowTransparency="true"></iframe>

This is an example of the iframe generated code, though there are a number of different types of code they’ll give you to choose from (HTML5, XFBML, etc).

You could certainly take the approach to paste this code directly into the PHP files in your WordPress theme where you want to show your Facebook Like box, but we’re going to do this in the form of a WordPress shortcode. That way we can pass in variable content to our Facebook Like box and we don’t have to update the raw code anytime we want to make a change.

Create a function in the location in your theme where you normally register your shortcodes. A lot of times this is the functions.php file but in the author’s humble opinion I believe that there are ways to keep your code more organized. Whether you are using functions.php or a class, add the following function to your code wherever it seems good to you…

function facebookBoxShortcode($atts, $content = null) 
{
	extract(shortcode_atts(array("id" => '', "path" => '', "showfaces" => 'true', "colorscheme" => 'light', "bordercolor" => 'white'), $atts));
	$scheme = '';
	$faces = '';
	if ($colorscheme == "dark")
		$scheme = "dark";
	else 
		$scheme = "light";
	if ($showfaces == "false")
		$faces = "false";
	else 
		$faces = "true";	
	return '<iframe id="'.$id.'" class="facebookBox" src="//www.facebook.com/plugins/likebox.php?href='.$path.'&colorscheme='.$scheme.'&show_faces='.$faces.'&border_color='.$bordercolor.'&stream=false&header=false" scrolling="no" frameborder="0" style="border:none; overflow:hidden;" allowTransparency="true"></iframe>';
} 

Then immediately after this you’ll want to register your shortcode…

add_shortcode('facebookbox', 'facebookBoxShortcode');	

If you are registering your shortcode in a class — which I think is a good idea — then you’d use the following slightly different code instead…

add_shortcode('facebookbox', array($this, 'facebookBoxShortcode'));	

What we are doing in our function is allowing for a number of different variables to be passed into our shortcode.

  • id: This is where we can set the “name” of your Facebook box. It is used as an identifier if you want to have multiple different Facebook boxes on the same page. It can have any single word string value but each should be unique because (as you can see in the code), it maps to a CSS ID selector.
  • path: This where you’d want to se the URL of the Facebook page you want people to “Like”. The default we have set is http://www.facebook.com/platform, but you’d want to change this to your own page.
  • colorscheme: This setting could have the string value of either “dark” or “light”
  • showfaces:
  • bordercolor: Set the color of the border here. The default value is “white.”

We are now all set. Once you have your variables all configured the way that you want them, to use our newly implemented shortcode you could just add the following to your page or post…

[facebookbox id="myFacebookBox" path="http://www.facebook.com/yourpage here" showfaces="true" colorscheme="light" bordercolor="white"]

If you wanted to use this code outside of the WordPress Loop, such as your sidebar.php or footer.php files, you could use the following….

echo do_shortcode(‘[facebookbox id="myFacebookBox" path="http://www.facebook.com/yourpage here" showfaces="true" colorscheme="light" bordercolor="white"]‘);

May many Facebook “Likes” follow you wherever you go for all the days of your life.

Share Tweet Reccomend

WordPress Shortcode: Popular Posts in Last X Number of Days

Shortcode Sunday! The time when we provide a semi-useful WordPress shortcode to kick your week off on a good note! This shortcode will allow you to display your most popular posts in the last 20 days or 30 days or 60 days or any number of days that you want to specify. The way that it determines what is “popular” is by the number of comments that the post has received. You will also be able to specify a limit to the number of popular posts you want to show.

So go ahead and add this function to wherever it is you are registering your shortcodes in WordPress…

function popularPostsShortcode($atts, $content = null) {
    extract(shortcode_atts(array("limit" => '4', "days" => '60'), $atts));
    global $wpdb;
    $sql = $wpdb->prepare("SELECT comment_count, ID, post_title, post_date FROM $wpdb->posts WHERE post_date BETWEEN DATE_SUB(NOW(), INTERVAL $days DAY) AND NOW() ORDER BY comment_count DESC LIMIT 0, $limit");
    $posts = $wpdb->get_results($sql);
    $list = '<div>';
        foreach ($posts as $post) {
            setup_postdata($post);
            $id = $post->ID;
            $title = $post->post_title;
            $count = $post->comment_count;
            if ($count != 0) {
                $list .= '<a href="'.get_permalink($id).'" title="'.$title.'">'.$title.'</a> ('.$count.' comments)';
            }
        }
        $list .= '</div>';
    return $list;		
}

Then all you have to do is register this shortcode after declaring the function…

add_shortcode('popularposts', 'popularPostsShortcode');

or if you are using it inside a class (as I highly recommend) you would register it in the following manner…

add_shortcode('popularposts', array($this, 'popularPostsShortcode'));

And if you want to use it in a page or post somewhere you’d just have to call it like so.

    Limit refers to the maximum number of posts you want to show and days refers to the number of days prior to the current day that you want to get popular posts for. So this shortcode would get the top 5 most commented on posts in the last 60 days.

    Enjoy :)

    Share Tweet Reccomend

    jQuery: What’s the Difference Between $(this), $this, and this?

    When doing jQuery development and looking at the code in other people’s jQuery functions and plugins you’ll eventually see that different developers will use different syntaxes in different places. This is probably most apparent in the use of the term “this”. Sometimes you will see this. Other times you will see $(this) and still other times you will see $this. What is the difference between all of these and when should you use each one?

    The this pointer in JavaScript refers to the current object that we are running our code inside. In JavaScript everything is an object, so the scope of this is always changing.

    Let’s say we had a page like one that is shown below…

    <!DOCTYPE html>
    <html>
    <head>
    <script src="http://code.jquery.com/jquery-latest.js" type="text/javascript"></script>
    </head>
    <body>
    <div id="one" class="myClass">One</div>
    <div id="two" class="myClass">Two</div>
    <div id="three" class="myClass">Three</div>
    <div id="four" class="otherClass">Four</div>
    <script type="text/javascript">
    </script>
    </body>
    </html> 
    

    Now in the <script> section let’s add some jQuery to loop through all of the elements with the “myClass” class (all the <div>’s on the page. As many know, to do this we use the jQuery each method. Inside of each we can use the pointer “this” to refer to the current DOM element in set of elements we are on.

    $(document).ready(function() {
        $('.myClass').each(function(){
           // do something with this here
        });
    });
    

    Let’s use the native JavaScript function getAttribute() to get the id attribute of each element.

    $(document).ready(function() {
        $('.myClass').each(function(){
           console.log(this.getAttribute('id'));
        });
    });
    

    If we look in our console, we can see that the text one, two, three appears (the id attributes of each DOM element that has “myClass”). So everything works as expected.

    But as you know jQuery also has a method for getting an attribute: the attr() method. So let’s try it with that.

    $(document).ready(function() {
        $('.myClass').each(function(){
           console.log(this.attr('id'));
        });
    });
    

    However if we look in our console we get an error.

    Uncaught TypeError: Object # has no method ‘attr’.

    Why is that? We know we are referencing the correct DOM element. Well, it’s because we haven’t wrapped this (the current DOM element) in jQuery so that we can call jQuery methods on it. That’s really the big distinction between $(this) and this. They both refer to the same object. However, if you want to use any jQuery on the object, it must be wrapped in a jQuery object as $(this) like so.

    $(document).ready(function() {
        $('.myClass').each(function(){
           console.log($(this).attr('id'));
        });
    });
    

    The reverse is also true. Because the $() is a jQuery wrapper, you cannot call native JavaScript on it. So $(this).getArribute(‘id’) also wouldn’t work.

    So that’s the big thing to remember. If you want to call a jQuery method on your object, wrap it it $(). If you want to use a native JavaScript method, don’t wrap it in $(). Just use plain ol’ this

    What about $this?

    $this is a little different because it’s actually just a variable that uses the $. It has no inherent relation to jQuery. It would be no different than JavaScript variables named $corn or $carrots. You just was easily say var $this = “My pet cat is named Mittens.”; It’s just a variable with the dollar sign in it. JavaScript allows characters like this in variable names. The reason that you see use of $this inside of jQuery plugins is that often times developers in the global scope inside of their plugin will say something like:

    var $this = $(this);
    

    That way they can always have a reference to the object on which the plugin was called. The scope of “this” will change in any methods used inside the plugin so it’s always good to have a global variable (that is, global inside the plugin scope) which you can refer to the object on which the plugin was called. But the important thing to remember is that $this has no inherent relation to jQuery. It’s just a variable like any other.

    Personally however, I never really liked naming the DOM element object using that convention. I always used var object = $(this); as can be seen in some jQuery plugins I have written. I figured with all the this’s running around inside of all of these objects, no need to throw another one in there if not absolutely necessary. But it’s really just a matter of personal preference there :)

    Hopefully this has cleared up some of the weirdness in uses of different this syntaxes.

    Share Tweet Reccomend

    Create a Responsive jQuery Accordion

    In this post I am going to show you how to create an accordion that will slide down on click using CSS and jQuery. There are a lot of tutorials out there that will show you how to do something similar to this but what I like about this accordion is that it uses <div>’s of content rather than list items for each of the accordion sections. A lot of tutorials show how to make menu-style accordions but not necessarily ones for any content that you want. That’s what this aims to accomplish.

    Before we start, I think I should mention that this accordion is not technically “responsive” in the sense that it has any media queries attached to it, only that the percentage-width based fluidity of it should allow you to fit it into any content area as the viewport resizes.

    View Demo

    It’s also going to be “vanilla” enough such that it’s not overstyled to the point where you’re going to have to undo a lot of the styling to fit the theme of your website (should you want to integrate it). It’s going to be fairly bland, boilerplate, and basic, but that’s always a good place to build from.

    The width of the accordion is going to be percentage based so that it should adapt well for responsive designs as well.

    So start and we’re going to lay out our basic structure in the HTML….

    <div class="accordion">
      <div class="accordionHeader"><span>One</span></div>
      <div class="accordionContent">Mauris quis tellus sed mi bibendum vulputate. Nam nec fermentum leo. Donec ante nisl, varius nec scelerisque nec, pulvinar id ipsum. Phasellus sodales tellus quis odio tincidunt quis feugiat sapien mollis. Ut hendrerit nisl eu turpis mattis sit amet accumsan ante pretium. 
      </div> 
      <div class="accordionHeader"><span>Two</span></div>
      <div class="accordionContent">Vestibulum neque justo, rutrum eu interdum sed, aliquam sit amet nulla. Pellentesque ultricies enim sit amet urna fringilla venenatis. Etiam eleifend dolor ut felis sagittis quis dignissim neque venenatis. In posuere tempus sodales. Aliquam tellus ante, posuere vitae congue at, tempus sed dolor. Etiam ac urna leo, at pellentesque augue osuere vitae congue at. Imperdiet ac euismod leo viverra. Maecenas convallis, lectus sit amet eleifend vehicula, sapien sem pretium dolor, in tincidunt est sapien eget orci. Sed vel libero urna. Aliquam ornare sodales egestas. Duis feugiat vulputate libero id tempor. Pellentesque elementum molestie nisi ac elementum
      </div> 
      <div class="accordionHeader"><span>Three</span></div>
    <div class="accordionContent">Nunc elit nisl, vestibulum ac laoreet nec, cursus sed leo. Aenean sit amet nibh justo. Quisque dui arcu, pharetra non sollicitudin nec, rhoncus at ligula. Etiam placerat porttitor adipiscing. Aenean fermentum nulla a justo malesuada id pulvinar urna sagittis. Morbi urna orci, faucibus sed sollicitudin sit amet, faucibus dictum massa. In sit amet enim at nisi rutrum vulputate. Vestibulum quis mattis nulla. Duis viverra orci ut enim tincidunt auctor. Ut molestie eros eget mauris consectetur eget tristique arcu elementum. </div> 
      <div class="accordionHeader"><span>Four</span></div>
      <div class="accordionContent">Nulla sollicitudin laoreet nulla quis suscipit. Curabitur tristique, dolor vel condimentum molestie, purus leo sodales enim, ac vehicula sem est eget eros. Sed vehicula, metus vel convallis tempus, mauris lorem tristique ipsum, ac condimentum arcu tellus vel nisi. Aliquam mauris est, adipiscing a pharetra ut, molestie egestas mi. Fusce vulputate blandit sagittis. Praesent eget dignissim felis. Integer ac libero eu felis congue cursus. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Fusce vel dui a sapien posuere consequat in quis mi. Proin eros nisi, lacinia id tempus id, congue eget justo. Proin ac justo non mi pretium vehicula sed id odio. Vivamus felis nibh, facilisis ut adipiscing at, blandit vitae magna. Praesent tellus est, molestie ut elementum at, pretium nec eros. Etiam diam nisl, varius non gravida eu, facilisis eu nunc.  
      </div>
    

    Seems straightforward enough. We’ve basically just defined a header item for the accordion titles and a content section for each wrapped into a wrapper <div> with the class “accordion”…

    With that out of the way, we can give it a little bit of styling using CSS…

    .accordion .accordionHeader {
      display: block;
      background: #eee;
      background: #eeeeee -moz-linear-gradient(top, #fcfcfc 0%, #eeeeee 100%);
      background: #eeeeee -webkit-linear-gradient(top, #fcfcfc 0%, #eeeeee 100%);
      background: #eeeeee -o-linear-gradient(top, #fcfcfc 0%, #eeeeee 100%);
      background: #eeeeee -ms-linear-gradient(top, #fcfcfc 0%, #eeeeee 100%);
      background: #eeeeee linear-gradient(top, #fcfcfc 0%, #eeeeee 100%);
      border: 1px solid #ccc;
      border-radius: 3px;
      -moz-border-radius: 3px;
      -webkit-border-radius: 3px;
      padding: 10px;
      font-size: 16px;
      font-weight: normal;
      cursor: pointer;
      margin-bottom: 10px;
    }
    .accordion .accordionHeader span {
      background: url(images/plus.png) center left no-repeat;
      padding-left: 30px;
    }
    .accordion .accordionHeader:hover {
      background: #fcfcfc;
    }
    .accordion .activeItem span {
      background: url(images/minus.png) center left no-repeat;
    }
    .accordion .accordionContent {
      margin-bottom: 10px;
    }
    

    And lastly we can bring it to life with jQuery…

    $(document).ready(function () {
        var nbsAccordionSliding = false;
        $('.accordion').find('.accordionHeader').click(function() {
            if(!nbsAccordionSliding) {
                nbsAccordionSliding = true;
                $(this).toggleClass('activeItem') 
                $(this).next().slideToggle({duration: 300, queue: false, easing: 'linear', complete: function() {
                    nbsAccordionSliding = false;
                }});
            }
        }).next().hide();
    });
    

    UPDATE: What if you wanted to have everything collapse and only show one at a time. To do that, you’ll want to replace the $(document).ready code block with the following…

    $(document).ready(function () {
        var nbsAccordionSliding = false;
        $('.accordion').find('.accordionHeader').click(function() {
            $('.accordionHeader').removeClass('activeItem');
            $(this).addClass('activeItem');
            if(!nbsAccordionSliding) {
                nbsAccordionSliding = true;            
                if($(this).next().is(':visible')){            
                    $(this).next().slideUp(function(){
                        nbsAccordionSliding = false;                
                    });
                }            
                else {
                    $('.accordion').find('.accordionHeader').next().slideUp();  
                    $(this).next().slideToggle({duration: 300, queue: false, easing: 'linear', complete: function() {
                        nbsAccordionSliding = false;
                    }});
                }
            }
        }).next().hide();
    });
    

    Click below to view the demo of the final finished product. If you like what you see, you can download the files and use them wherever you like :)

    View Demo Download Files