Equal Height and Width for WordPress Widgets Using JQuery

equal width height post image

There are situations when a developer needs to set equal height and width to child div’s that contain dynamic content. I came across such a situation, in which I had to place more than one widget in a single horizontal row. If I applied static heights and widths to the divs, there was a possibility of breaking the div after a certain number of widgets. To overcome this situation, I came up with a solution using jQuery wherein the divs which contain these widgets will get equal heights and widths depending on the size of the content.

This function automatically calculates the size of the content that is going to be inserted into the div, and applies the height of the div whose height is largest from all the other divs. The width of parent div is divided by the number of widgets and then applied to each widget.

Example:

Assume we have a parent div “#sidebar_1” of width 960px. I insert three divs into parent div of variable height and width. Using the below function, each widget will be applied with the width that is obtained after dividing the parent div from the number of widgets (960/3). Each widget’s height is calculated and the greatest height is applied to all the widgets.

Here is my html code,

<div>
    <div class="child1">my custom content 1</div>
    <div class="child2">my custom content 2</div>
    <div class="child3">my custom content 3</div>
</div>

Here is my CSS which I applied,

#sidebar_1 { width: 960px; overflow: hidden; }
.child1, .child2, .child3 {
border-right: 1px solid #EDEDED;
float: left;
overflow: hidden;
padding: 5px 10px; }

jQuery Function to dynamically apply equal height and width

// to div's present in a parent div
function rt_equalHeightWidth( group ) {

// Get parent div width
    var rt_group_width = group.width();

// Get child div's
    var rt_group_child = group.children();

// Get size of child div present in the parent div
    var rt_group_child_size = group.children().size();

// Remove left padding from the first child div
    rt_group_child.first().css( { 'padding-left': '0' } );

// Remove right padding and right border from the last child div
    rt_group_child.last().css( { 'border-right': '0', 'padding-right': '0' } );

// Function to apply equal width for all child div's
        rt_group_child.each( function() {
// Calculate width for each child div
            var rt_group_child_width = rt_group_width / rt_group_child_size;

// Count extra padding and border width
            var rt_extra_width = parseInt( jQuery( this ).css( 'padding-left' ) ) + parseInt( jQuery( this ).css( 'padding-right'  ) ) + parseInt( jQuery( this ).css( 'border-right-width' )+ rt_group_child_size );

// Remove extra padding and border width from width
            var rt_group_child_actual_width = rt_group_child_width - rt_extra_width;

// Apply actual width to each child div
            jQuery( this ).css( { 'width' : rt_group_child_actual_width + 'px' } );
        } );

// Equal height for all child div's
        var rt_height = 0;

// Function to apply equal height for all child div's using jQuery each
        rt_group_child.each( function() {

// Get height for each widget
            var thisHeight = jQuery( this ).height();

// Get height for widget and apply equal height's to all widget
            if ( thisHeight > rt_height ) { rt_height = thisHeight; }
        } );
        rt_group_child.height( rt_height );
}

// Apply parent selector by replacing '#sidebar_1' selector
rt_equalHeightWidth( jQuery( '#sidebar_1' ) );

Here are the resultant screenshots of div’s where the above code is used to apply equal height and width.

1_widget2_widgets3_widgets

Besides sidebar widgets the above code can be used for any div’s that has dynamic content, and you want them to have equal height and width. You just need to apply parent selector by replacing ‘#sidebar_1’ selector.

Hope this helps and saves your time, do drop in your opinions and comments below.

jQuery Codes to Fix Facebook Share’s Zero-Count

It’s been a long time since Facebook started providing the official share-count. Before that, the void was  filled by a third-party service called fbShare.me, which is still active and works fine.

During one of my performance-optimization experiment, I found that the official Facebook share-count loads much faster. Also, being “official”, it seems a safer choice keeping the future in mind.

But when I switched to new codes, a new problem surfaced as you can see in the screenshot below…

The issue is, if Facebook share count is zero, the big share button shrinks to 1/4 of its size and hides the counter because of the surrounding buttons near it. I prefer the share-count to show even if it was zero.

I really thought that Facebook might have some parameters or setting to fix it, but after a lot of brainstorming, I finally managed to fix it using jQuery codes below:

//fix facebook share's zero-count
jQuery(document).ready(function(){
	jQuery(".fb_share_no_count .fb_share_count_inner").text("0");
	jQuery(".fb_share_no_count").removeClass("fb_share_no_count");
});

Of course, for the above code to work smoothly, you must have jQuery included somewhere before the above code-snippet.

Here is how it will look like after the fix…

I hope you will find this code useful! ;-)

JavaScript/jQuery Snippet to check if a function exists

I am working on a very complex wordpress theme from last few weeks and on the way learning many new things.

To keep load time of this new theme in check, I am using many ‘if’ statements in header.php to control which javascript library/jquery plugin loads on which page. So before making JavaScript/jQuery function calls, it became essential for me to check if function exists in current environment.

Following are code snippets I am using frequently in this case…

JavaScript codes to check if function exists

if(typeof window.rtFunction == 'function') {
	// function exists, so we can now call it
	rtFunction();
}

Example: Calling md5 function

if(typeof window.md5 == 'function') {
	// function exists, so we can now call it
	md5(286);
}

jQuery codes to check if function exists

if( jQuery.isFunction(jQuery.fn.rtFunction) ){
	// function exists, so we can now call it
	jQuery(document).rtFunction();
}

Example: Say if you are using jQuery tabs plugin…

if( jQuery.isFunction(jQuery.fn.tabs) ){
	// function exists, so we can now call it
	jQuery('#tabs').tabs();
}

These two functions turned out to be life saver for me.

Thanks Paul for javascript codes and besh.jquery for jQuery codes.

I have found many more ways to optimize wordpress themes while working on this theme. I will surely post them starting next week, once we launch this new theme! ;-)

WordPress Themes – Standards and Checklists (beta)

This article was originally created (in parts) for rtCampers to guide our trainees and follow the best CSS and design practices. It is by no means complete but hopefully it will evolve over time as we get more mature with WordPress, CSS and web-design in-general.

The goal of this article is to create a master list of standards that we want to follow while designing wordpress themes. Comments & criticism – awaited!

#1. Always Start with CSS-Reset

CSS-Reset is a snippet of code that should be always pasted in your “style.css”.

CSS-Reset clears (nullify) formatting on all HTML tags. Each browser has its own default formatting for most HTML tags and they vary from browser-to-browser. CSS-Reset brings all browsers to common ground! ;-)

There are many variation of CSS-Reset, but one I have always used is pasted below. It is from Stakers theme by Elliot Jay, which has been starting point for most of my themes. I will talk about stakers theme in detail some other day!

[css]
/* RESET */
/* —————————————– */

/* Global reset */
/* Based upon ‘reset.css’ in the Yahoo! User Interface Library: http://developer.yahoo.com/yui */
*, html, body, div, dl, dt, dd, ul, ol, li, h1, h2, h3, h4, h5, h6, pre, form, label, fieldset, input, p, blockquote, th, td { margin:0; padding:0 }
table { border-collapse:collapse; border-spacing:0 }
fieldset, img { border:0 }
address, caption, cite, code, dfn, em, strong, th, var { font-style:normal; font-weight:normal }
ol, ul, li { list-style:none }
caption, th { text-align:left }
h1, h2, h3, h4, h5, h6 { font-size:100%; font-weight:normal }
q:before, q:after { content:”}

/* Global reset-RESET */
/* The below restores some sensible defaults */
strong { font-weight:bold }
em { font-style:italic }
a img { border:none } /* Gets rid of IE’s blue borders */
[/css]

#2. Don’t forget to add CSS for WordPress Generated classes

WordPress post-editor adds some classes like .alignleft, .alignright to the content. Also some template tags and standard widgets generates additional CSS classes that may be useful. More details about this can be found here.

At bare minimum you should have following CSS added in your theme.

[css]
.aligncenter,
div.aligncenter { display: block; margin-left: auto; margin-right: auto;}

.alignleft { float: left;}

.alignright { float: right;}
[/css]

Also note coding style of above CSS block is different than style given on WordPress codex page.

Its matter of personal choice. You can see my CSS coding style here.

#3. Javascripts in WordPress Theme

These days tabs and sliders are quite common among wordpress themes! Most of this fancy stuff is done using jQuery, its plugins and/or some extra javascript files.

Best way to include javascripts in wordpress theme is:  wp_enqueue_script( ) function.

Always create your own javascripts files under “js” folder in your themes directory.

For javascripts library, before adding/uploading a copy to your theme directory, check list of javascript libraries that comes with wordpress. All these default libraries can be included in your theme merely by calling wp_enqueue_script( ) function. There is no need to upload them separately in your theme. ;-)

#4. Use Proper Test Data

To properly test a theme you are developing, you need test-data that covers most commonly used type of contents.

By default, when you install a new wordpress it creates a “Hello World” post, a comment on that post, an “About” page and few more data which is completely useless if you are developing a theme. Also exporting data from real big blog for testing purpose may not be good idea. We need test-data which must have lots of variations rather than larger number of posts.

For this:

  1. Always test your theme with standard test data given here.
  2. Above link open (or downloads) a XML file. Save it on your disk.
  3. Then log into wordpress admin side. Go to “Tools >> Import >> Wordpess” and select XML file.
  4. Its good idea to check “Download and import file attachments” checkbox on next screen

Thats all! Now check each link/page on test site in each browser!

Standard test data and CSS-Reset will save your considerable time that goes wasted in support phase.

#5. Final Testing & Checklist!

The biggest and most extensive checklist with plenty of test-cases can be found on wordpress codex.

Any theme we develop must be tested against that checklist.

#6. Additional Work for Public Themes

In case you want to release your theme for public on official wordpress.org theme repo, then make sure you follow these guidelines.

For GPL compatibility, you can simply put the following 2 lines in a comment block in top-portion of your style.css file.

[css]
/* The CSS, XHTML and design is released under GPL:
http://www.opensource.org/licenses/gpl-license.php */
[/css]

(to be continued…)

Feed Sweep: Create widgets for showing feeds on website

Feed Sweep

When designing a website or a blog, you might need to show some feeds from another website. This is quite relevant if you have two blogs and want to show feeds from one to the other.

Feed Sweep is a website which allows the user to register and create customized widgets for showing feeds from other websites. It creates a code of the customized widget which you can insert into your homepage for the feeds to show up.

About Feed Sweep

  • Feed Sweep has various  plans and most of them are paid. The free plan comes with some advertisements. I was curious to know if these advertisements would be intrusive but was surprised pleasantly that they were text based and pretty similar to Google Ads.
  • In the Free plan I could add upto 5 feeds to show up. I could customize the format and color of the widget. Once done with it, I got to see an example of how the widget would look along with the HTML code which I had to enter in my website (see image below).
  • The customizing part is pretty good. It includes defining the width in pixels of the Feed. It also allows you to choose the number of feeds that will be posted on the widget. A customizable title is also allowed. When you get the code it is in JavaScript.

feed_sweep2

So try out Feed Sweep if you want a widget to show feeds from another website. Let me know through your comments what you think about Feeds Sweep along with any other similar products which are also free.

Adobe Security Updates on May 12

untitled Last month, Adobe’s Product Security Incident Response Team (PSIRT) announced potential vulnerability in Adobe Reader 9.1 and 8.1.4 and had urged users on all platforms to disable JavaScript.

Since then, many have been eagerly awaiting Adobe security patches so that the issue can be fixed. Adobe has set a May 12 date for the delivery of patches to fix the vulnerability in its Adobe Reader and Acrobat software products.

PSIRT says:

“We are in the process of fixing the issue, and expect to make available product updates for the relevant supported Adobe Reader and Acrobat versions and platforms by May 12th, 2009.

Additionally, we have confirmed the second vulnerability (CVE-2009-1493) for Adobe Reader for Unix. This issue will be resolved in the upcoming Adobe Reader for Unix updates. Currently, we have not been able to reproduce an exploitable scenario for Windows and Macintosh, but we will continue to investigate.”

Adobe Upcoming Updates:

  1. Window updates for Adobe Reader versions 9.X, 8.X, and 7.X
  2. Window updates for Acrobat versions 9.X, 8.X, and 7.X
  3. Macintosh updates for Adobe Reader versions 9.X and 8.X
  4. Macintosh updates for Acrobat versions 9.X and 8.X
  5. Adobe Reader for Unix versions 9.X and 8.X.

In the meantime, continue to keep your JavaScript in Adobe PDF Reader disabled. To know how you could do that, read my earlier post: Disable JavaScript in Adobe PDF Reader!

If you still think Adobe Reader could be a “risk” to your machine, then do consider using an alternate program.

(Source: Adobe Blog)

Disable JavaScript in Adobe PDF Reader!

Adobe Product Security Incident Response Team (PSIRT) has reported a potential Adobe Reader issue.

“Adobe is aware of reports of a potential vulnerability in Adobe Reader 9.1 and 8.1.4, as described in SecurityFocus BID 34736. We are currently investigating, and will have an update once we get more information.”

Adobe has urged users on all platforms to disable JavaScript. This is a temporary arrangement made to avoid any code execution attack. Adobe said that they plan to provide updates for all affected versions for all platforms (Windows, Macintosh and Unix) so that the issue can be resolved as soon as possible.

adobe un-check

Instructions:

Here are a few steps that Adobe suggests:

  1. Launch Acrobat or Adobe Reader
  2. Select Edit> Preferences
  3. Select the JavaScript Category
  4. Un-check the ‘Enable Acrobat JavaScript’ option
  5. Click OK

Immediately recommending the users to disable JavaScript till the time a patch is released looks like a welcome step by Adobe. Better be proactive than be a victim later. No harm in playing safe, right?

However, in the meantime, is anyone aware of any alternate secured software that can be used temporarily?

(Source: Adobe blog)

Page Navigation Hack for Blogger (Blogspot)

Most of the people think that page navigation hack is only for who blogs at WordPress. But here is the hack for those who use blogger and want to add page navigation to their blog. This hack will show page number instead of text link older posts, as shown in following screenshot.

You can see live demo here.

Now this involves two things – adding some CSS code and javascript code to your template. All steps are explained below.

Steps:

  • Log in to your blogger account and navigate to Layout section. Now go to the Edit HTML tab.
  • Search for line ]]></b:skin>
  • Add CSS in this file above that line.
  • Now search for this code or related in your template (no need to expand widgets)
<b:section class='main' id='main' showaddelement='yes'>
<b:widget id='Blog1' locked='true' title='Blog Posts' type='Blog'/></b:section>

Mods:

In javascript codes in this file, find line…

var pageCount =5;

The digit in red represents number of posts to be shown in single page. Change the digit to show as many pages you want.

var displayPageNum = 3;

Here the digit in red represents number of pages to be listed. Change the digit to list as many pages you want.

That’s it now we have added Page Navigation menu hack to our blog successfully

Your Comments are appreciated..  :-)

(Credits: Muhammed from RTW)

Related: 6 WordPress Plugins for Better Navigation and User Experience


[Editor Note: This is first post by Arjun Kumar on this blog. Arjun is just 16 year old and that make him youngest Devil in team DW. He is working hard on our new project OrkutBuddy, dedicated for orkut users.

If you like to write for Devils Workshop, please check this. Details about our revenue sharing programs are here.]

Using Firebug Console to log from GreaseMonkey Scripts

This is for all Greasemonkey developers who also use Firebug. Firebug is one of the best Firefox extension for developers.

To start with, almost every Greasemonkey developer uses built-in API method “GM_log()” to log debugging messages to Firefox’s javascript console.

While normal javascript developers use Firebug’s API method “console.log()” to log debugging messages to Firebug console.

Now problem is, if you try calling “console.log()” directly from Greasemonkey scripts, it will not work. As Firebug’s console object reside outside Greasemonkey scripts scope.

There are few workarounds to use Firebug console to log Greasemonkey debugging messages. But one which always work for me is detailed below.

Simplest way is to use…

unsafeWindow.console.log()

You can use other firebug logging functions similarly by prefixing unsafeWindow to them. Complete information about Firebug console can be found here.

Next what if you are editing your older Greasemonkey script! A simple way to use text-editors search-and-replace feature and replace all occurrences of “GM_log” with “unsafeWindow.console.log”.

Well it may be nice for some but geeks way is different! I will recommend adding following lines of code at the beginning of your Greasemonkey scripts.

if(unsafeWindow.console){
   var GM_log = unsafeWindow.console.log;
}

The beauty of above codes is, it will first check if Firebug console is available. If yes, then all output from GM_log will be sent to Firebug console. And when Firebug is not available, it will simply use Firefox’s built-in javascript console without any error!

Next if you want to switch back to Firefox’s built-in javascript console, you can do that by just removing or commenting above code.

Disable logging for all GM_log calls…

While developing Greasemonkey scripts, we use GM_log a lot to speed-up coding. But once we are done, ideally we should remove all unnecessary GM_log calls from script as keep Firefox or Firebug console busy.

But this may not sound good idea for some guys who code scritps for sites which changes so often. So better approach is to disable logging via GM_log by adding one line of code, as below, in the beginning of script.

var GM_log = function (){};

This will basically assign an empty function to GM_log. Even smarter approach is to use code like below…

var GM_Debug = 0;

if(!GM_Debug) {
   var GM_log = function(){};
}

Now all you have to change one character to enable/disable logging.

If you have noticed you are basically assigning a different function to GM_log to override it. Those who are new to javascript may find it little strange, but its perfectly valid!

Enable Right-Click On Any Website (Including Orkut)

There are many websites which prefer to disable right-clicking on web-pages specially images. To do this they normally use one of JavaScript ways.

The most popular way is to add following code to element tag on which you want to disable right-clicking.

oncontextmenu="return false;"

For example, say you have code for an image like below…

<img src=”something” />

Change it to…

<img src=”something” oncontextmenu="return false;"/>

Now reason I am posting about this is, popular social networking site Orkut, which I use quite often, started using code like above and disabled right-clicking on album images.

So as usual, we got to do something to get back our right to “right-click”!

GreaseMonkey Script: If you use Firefox and GreaseMonkey, then easiest way to enable right click on any website is to install right to “right-click” script.

JavaScript: If you are not fond of GreaseMonkey, then you can try following JavaScript.

javascript: var items = document.evaluate('//*[@oncontextmenu=\"return false;\"]', document, null, 7 , null); for ( i = 0; i < items.snapshotLength; i++){items.snapshotItem(i).removeAttribute('oncontextmenu');};void(0);

Bookmarklet: You can also use this bookmarklet in Firefox and other standard-compliant browser.

Internet Explorer: If you are an IE user, specially IE 6 then paste following code in address bar and hit enter whenever you stuck. Please note code below is for Orkut only and most likely to break anytime.
javascript: document.getElementById('m').oncontextmenu="";void(0);

Important Note:

From above all solutions, I am planning to take GreaseMonkey solution further. I will add more anti right-clicks hacks soon. As of now this script takes care of most famous way so it should work on many sites.

We can not blindly set “oncontextmenu” attribute to null or “return true” as some sites provides useful functions by overriding browser context-menu. WordPress, Google docs are some popular examples.

If you find a site where right-click is disabled and this script is failing to work,  please leave a comment below with page URL and element description where it failed to work. I will try to update this script ASAP.

Link: Install Right to “Right-Click” Script (How?)

Related: JavaScript to Unmask Password on Web Pages