Copy JavaScript Array with All Items Except One

var newArr = (newArr = oldArr.slice(), newArr.splice(newArr.indexOf(item), 1), newArr);

By combining JavaScript’s comma operator, Array slice and Array splice, we can conditionally duplicate JavaScript arrays.

Example code:

// Removing '2' from the new Array.
var a = [1, 2, 3, 4, 5];
var b = (b = a.slice(), b.splice(2,1), b);
// b = [1, 2, 4, 5];

Here we have to use a.slice() to copy Array a to b. Otherwise changes made to b would reflect on a as well.

Best Programming Language for Web Development

Disclaimer: I’m not really going to mention any language as ‘best’. The title of this post is actually very misleading.

I started doing hard core web development barely a year ago, but a question I face on a daily basis is whether I’m using an optimal programming language and technology. When I started making websites (not web apps) around four years ago, I used to create them using simple HTML + CSS. Then as my clients needed things which were ‘dynamic’ and wanted to jump on the then popular boat of ‘CMS’, I switched to WordPress for delivering websites. WordPress became my one stop solution for all sorts of websites (although it is actually a blog software with lots of code/functionality which you will probably never need). Soon I started developing on WordPress (plugins) for further delivering to custom requirements. I almost always ended up using a dozen WordPress API methods throughout my code and usually had no any idea how they did what they did.

When I moved to the corporate scene of web development (in my current job), I started using PHP for building web applications. I started using (and still use) frameworks like CodeIgniter (for old projects) and Laravel (newer and cooler). PHP is the most dominantly used server side language right now, powering at least two third of the Internet (source). It is also the web language which gets the maximum hate. The Internet is filled with articles criticizing PHP and then articles trying to justify its usage.

Last semester I started going to hackathons, and pretty much everyone in every hackathon I went, told me how much PHP sucked when I used to tell them that I code in PHP. The common thing about those people was most of them had never actually even used PHP, but were fancied by other ‘cool’ languages. When everyone everywhere I met went totally berserk for PHP, while enchanting how cool Python is (which it actually is btw), I finally made my move to Python (Flask) for web development. It was very cool in syntax and all that (no ugly braces anymore, no more couple of $ signs in every single line), but I did feel that I wasn’t doing anything significantly different than what I could have done using Laravel + Composer/Packagist.

In my opinion, the biggest problem of PHP is the very low bar of entry. Most of the other languages require at least some sort of initial setting up/program compilation for producing even the Hello World but in PHP it’s as easy as writing <?= 'Hello World' ?> in any text file saved with a .php extension. Even almost all of the shared web servers online come with PHP only preinstalled. Because of this PHP becomes the choice of programming for every Joe pretending to be a web developer. What this usually results in is ugly PHP code mixed with HTML, plus five redundant functions doing the same thing and unsanitized SQL queries– all in the same page. This is the stuff which makes PHP bad; but the developers are responsible, not the language.

I’m not saying PHP is the best and greatest programming language. There are certainly more promising languages, like Python, Erlang and Haskell. I just believe PHP is not as bad as everyone claims it to be. There must be a reason why Facebook, Yahoo, Etsy and Mailchimp still use it (although Facebook doesn’t use the php which we use). If people try to follow good coding practices in PHP, it will certainly come out to be as good as other languages (if not greater).

All this being said and as I mentioned above, there are some languages which certainly seem to be very promising for web development. I actually love Python too a lot for writing server side code. Also Erlang too is pretty cool and defines efficiency. Whatsapp, the mobile phone app which was sold couple of days/weeks ago to Facebook had around half a billion users while having just thirty two employees and twenty support people. It is believed that the team was able to pull something like that off because of their strong software in place, which was made using Erlang. Then there is Haskell, which is known for delivering crazy fast websites. I guess if someone wants to know ‘Best Web Programming Language’ for him or herself, the only way to know it is by using each of them. As the quote goes “Never judge a book by its cover”, so is applicable to programming languages.

Further Reading

Ways to Build a Website

There are bunch of ways by which we can get a website up on the Internet. Each way has it’s merits and demerits. In this post I’ll share some ways which I think are fairly quick if you need a simple website up in minimal time. These ways are listed in the order of their coolness.

Static Website Template

If you don’t need anything fancy, then this is certainly the way to go. Just get a nice and pretty looking template from one of those template websites like Themeforest.

Pros

  1. Usually these templates are quite pretty.
  2. Several categories to chose from for templates (like restaurants, medical, etc).
  3. Come with stock/dummy content + images, which are easy to replace.
  4. Support is decent if you buy from a legitimate place.
  5. At times there are free templates too!

Cons

  1. You need to somewhat know your way around HTML/CSS. Otherwise the result won’t be very nice.
  2. Very generic templat-ey looking websites.
  3. Usually overloaded with a dozen varieties of galleries, sliders, etc, thus not efficient.
  4. Can be difficult to maintain if the number of pages in your website is not in single digits.

WordPress Website

I personally used to use WordPress for creating normal and just about every kind of website, and did so for couple of years until I realized how horrible that idea was. However, I believe this is still the most popular way to get static and dynamic websites up. I’m not saying the idea of using WordPress for normal websites is bad, just that I personally don’t like use things which are an overkill. WordPress is loaded and powerful, but do evaluate if you need all those features or not, and if using it is worth it. I use WordPress for this website because this place is essentially a blog only (and WordPress provides me with all the functionality I need).

Pros

  1. Everything from above, plus:
  2. You get a backend enabled website (CMS) fairly easily.
  3. Thus you can easily add or remove pages and maintain them too.
  4. Lots of plugins for quick functionality.
  5. Comes with blog! (duh)
  6. Most ideal for typical users.

Cons

  1. Everything from above (except 4), plus:
  2. The templates are not exactly flexible, it’s alright if you need to change the styling, but if you need to do structural stuff, you are better of creating your own template using something like underscores.me.
  3. I don’t like the file structure and code modularity of WordPress websites.
  4. Not very scalable (at least not neatly), although you can create bunch of plugins for doing bunch of stuff, but there is no central approach like present in other web frameworks.
  5. Most people usually tend to use several plugins and most many of these plugins will slow your website down.

Python/PHP Frameworks

If you kind of know your way around web development, then this is what you should probably do. There are bunch of awesome frameworks but top two (according to me) for a fairly functional website would Flask and Laravel (Python and PHP Web Frameworks). They both offer some great features like front end templates (Jinja2 and Blade) and are driven by things like template inheritance, etc. I know this may not be the most efficient solution for just a website, but it all depends upon your velocity. Personally I can more quickly and more neatly set up a website using Laravel than WordPress.

Pros

  1. Nice, clean and structured code base (because you authored most of it yourself).
  2. These frameworks typically have many modules/extensions which you use for a plethora of tasks (like ORMs for querying databases, form classes for HTML forms, etc).
  3. You write less code because of these already available modules/classes, and typically the building blocks behind these are pretty good.
  4. Because of these, your web site/application would typically be very easy to scale and maintain.

Cons

  1. You actually jumped to web development from web designing here.
  2. You need to be somewhat familiar with web development using Python or PHP.
  3. Maybe be an overkill for many people.

Website Builders

This is typically what people who have no idea about how to make websites do. They are usually offered from shared web hosting providers (like 1&1 Website Builder, etc) and are targeted towards users with no web design experience. There are also services which only do this, two most popular ones of this kind are Squarespace and Virb (owned by Media Temple (which is owned by GoDaddy)).

Pros

  1. Best option for people with no design experience.
  2. You can still end up with a decent looking website since they have a wide range of existing templates to chose from.
  3. Quite fast. It’s like using a rich text editor- for websites.

Cons

  1. Scalability and Flexibility? Lol.
  2. Not so much for customizations either.
  3. No matter what they advertise, but most of the websites which come out of tools like these don’t look very good.

Honorary Mentions

There are also tools like Concrete5 and Sitefinity CMS, in which case I think you would probably be better of with WordPress and also things like Expressions Engine and KendoUI, which I don’t really know what is and how they are better than their free counterparts.

A Guide to Future Proof Mobile/Tablet Friendly Websites

Tablet and Phones
In a matter of couple of years, more than half of total web browsing will be done from mobile devices, however, mobile devices don’t necessarily provide the same design implementation as desktop computers do and many of times we see our websites breaking on those small screens, while many designers create tablet/mobile specific website, but I think maintaining one website is better than maintaining two separate ones. Below I will discuss some importanr things which we can keep in mind while creating a website to make it future proof for mobile devices as well as desktop computers.

Use Responsive Frameworks

Responsive Web Design
Getting back to the idea of two separate websites, I don’t think it pleases me or anyone much, we are better off doing one Responsive Website. Well, what is this Responsive Website exactly? Wikipedia defines Responsive Web Design as

Responsive Web Design (RWD) essentially indicates that a web site is crafted to use Cascading Style Sheets 3 media queries, an extension of the @media rule, with fluid proportion-based grids, to adapt the layout to the viewing environment, and probably also flexible images.

Which means, having a responsive website enables us serve all devices via a single website, it enables us to address the ever-changing screen sizes, orientations and resolutions by using a flexible/fluid grid which will adapt to any screen size (and resolution). With responsive design, we have one website which serves all kinds of devices. This is in contrast from the other trend where we need to maintain at least two websites (desktop and mobile version). It has an obvious major advantage of far easier maintenance (now we maintain one instead of two websites).

The essential concept of responsive design is minimum (or no) of resizing, scrolling (horizontal) and panning. There are many frameworks for fluid grids out there, I like the the 1140px CSS Grid and those who are loyal to 960px width can check out Gumby 960 CSS Framework.

Use Media Queries, everywhere

Media queries are certainly the most important part of responsive websites. Media queries were restricted in CSS2 to only screen, print and all, but, in CSS3 they are far more robust. We can now apply different stylesheets/styles based on the size of the viewport and pixel densities. Generally, for the most part, website implementation looks similar in tablets and desktops, however, many elements tend to get implemented (or displayed) differently in tablets, we can fix those elements using specific CSS thanks to media queries, also, we can differentiate how a particular element or the whole website will look in small screen phones, smart phones, tablets and desktops using media queries only. Here I am sharing some essential media queries.

Media Query for Normal Phones

We can include all of our phone specific styles within this block:

Select Code
@media only screen and (min-device-width : 320px) and (max-device-width : 480px) {
/* ==================================== */
/* ! All phone specific CSS goes here   */
/* ==================================== */
}

Media Query for Smart Phones

The difference between a smart phone and a normal phone is resolution, smart phones will always higher resolution than normal phones, we can include all of our smart phone specific styles within this block:

Select Code
@media handheld, only screen and (max-width: 767px) {
/* ========================================= */
/* ! All smartphone specific CSS goes here   */
/* ========================================= */
}

Media Query for Tablets

We can use the below media query for all of our tablet specific styles, do keep in mind this will not get applied to those 10 inches tablets like Motorola Xoom, Toshiba Thrive, etc and will get applied to small/old monitors.

Select Code
@media only screen and (min-device-width: 600px) and (max-device-width: 1024px) {
/* ===================================== */
/* ! All tablet specific CSS goes here   */
/* ===================================== */
}

Media Query for New Retina Displays

If we have some high resolutions assets which we will like to be applied to iPhone 4, iPhone 4S and iPad 3, then we can use the below block:

Select Code
@media only screen and (-webkit-min-device-pixel-ratio: 2) {
/* =================================== */
/* ! Higher resolution CSS goes here   */
/* =================================== */
}

Taking Care of Orientation Problems

As I discussed in my post: Making Devices on Portrait Orientation Behave like Mobile, some websites get screwed in portrait orientation, read there only how it happens and why I strongly recommend to use the below media query.

Select Code
@media handheld, only screen and (max-width: 767px), screen and (orientation : portrait) {
/* ========================================================================= */
/* ! All phone and tablets(in portrait orientation) specific CSS goes here   */
/* ========================================================================= */
}

Design Light and Fast Websites

Fast Websites
The CPU of a mobile device is not same as of a desktop computer, thus if we are using a lot of high resolution assets like images and videos, we should give it a second thought from the perspective of mobile devices, also, loading a lot of jQuery/JavaScript for animations and other effects will most likely deteriorate the performance of our website and the website will tend to hang frequently, to overcome this, make sure the website made is light weight and simple, a simple website is definitely a winner for mobile devices as it can also be used easily.

Also, we should try reducing requests around network to minimum, some techniques for reducing HTTP requests include using CSS Sprites, combining (and compressing) multiple stylesheets/JavaScript files into one and using Data URI whenever possible. Data URIs are means to inline data in web pages, that is no external HTTP Request, here is one website to encode Data URIs. Back to JS, we should try and load all JavaScript in the end as it will increase the overall performance or at least we can use defer and async attributes (HTML5 only), furthermore, a lot of JS becomes useless for mobile device anyways, we should simply not load them by checking for user agent, here is JS snippet which pretty much checks for every mobile and tablet around:

Select Code
var mobile = (/iphone|ipod|android|blackberry|opera mini|opera mobi|skyfire|maemo|windows phone|palm|iemobile|symbian|symbianos|fennec/i.test(navigator.userAgent.toLowerCase()));

var tablet = (/ipad|android 3|sch-i800|playbook|tablet|kindle|gt-p1000|sgh-t849|shw-m180s|a510|a511|a100|dell streak|silk/i.test(navigator.userAgent.toLowerCase()));

if (mobile) {
/* JS for mobile devices  */
}
else if (tablet) {
/* JS for tablets  */
}
else {
/* JS for everything else  */
}

This is not a 100% bulletproof method, but there is nothing to lose.

Dealing with Hardware

A4
One thing to remember while building mobile websites is that they don’t have any mouse or keyboard, so all keyboard jQuery for navigation will not work, also, since there is no mouse, there are no hover effects.

Building navigation menu for tablets is little tricky, although most tablets like iPad make most of the navigation menus easily usable, however, in some tablets like PlayBook, making our navigation menu work is real pain, especially the ones with sub menus (since they use hover), we need to carefully CSS between :hover and :active pseudo classes (as they are practically same for mobile devices).

Whitespacing is another crucial element in mobile devices, we don’t want our website to look in clutter and we must build elements, especially clickable elements with decent amount of padding and adequate spacing so that our fingers can tap easily on them (since our fingers are much more thicker than mouse pointers and some times it gets irking when we can not click items and need to zoom-in to do so). Besides, check out jQuery Mobile for adding touch gestures to websites.

Ditch Flash

Flash
Most of us are already aware of that many mobile devices like iPhones, iPads, Windows Phones, Chrome on Android, etc don’t have flash, even if some do, flash experience on them is not the same as in desktop computers, thus we should certainly not use it. We can use jQuery animation instead of flash to achieve most of the effects and where flash is absolutely necessary, we can do conditionals to check for flash and then execute the suitable code. SWFObject is an easy to use and standards friendly method to embed Flash content, which utilizes one small JavaScript file, we should use this where we absolutely need to use flash.

And finally, not all tablets are Webkit, use standardized properties!

Windows 8 Tablet
I know this will sound weird to most of you, especially since currently every tablet (probably) is on Webkit and thus what we tend to do is use those non standardized -webkit only CSS3 without their other counterparts, though it is very helpful and it works (and we should use them), but there are problems because of this, let me illustrate one.

A decade ago, IE6 was the most dominant web browser in the world, the whole Internet was full of websites made only for IE6, the users of other browsers were discontented. Though that particular problem is over now, but it is back in another form now, Webkit. Webkit is the rendering engine used by almost every modern mobile device (except a very few) and hence the mobile Internet is now full of Webkit only websites, now what if in future tablets ditch Webkit? And that future might not be very distant, later this year, Microsoft will introduce its flagship for tablet operating system, Windows 8, and as far as I can tell from its release preview and beta, its quite good, and its success wont be any surprise, however, it will be a surprise for designers when most of their websites wont work on it’s default web browser. Similarly, Firefox and Opera also have a decent share of mobile browsing, those -webkit properties wont work on even them (although Opera supports some -webkit properties). So to avoid all this, we are better off using standardized CSS properties for most of our designing and use -webkit properties with their -moz, -ms, -o and prefixless counterparts. Prefixr.com can help you to make your cross-browser CSS.

Further Reading

[unordered_list style="arrow"]

[/unordered_list]

Best .htaccess Hacks for WordPress

I previously wrote Best .htaccess Hacks For Websites, now this article has .htaccess hacks pertaining to WordPress only. .htaccess is a configuration file on your server which controls Apache Server and is a very powerful tool for your website if used properly. Here are some .htaccess snippets which will surely help you improve your WordPress installation.

Please backup your .htaccess file before doing any changes. In case anything goes unexpected just replace the .htaccess with your backup.

Redirect WordPress Feed to FeedBurner

This simple snippet will redirect your default WordPress feed to your Feedburner, easy yea?

RewriteEngine on
RewriteCond %{HTTP_USER_AGENT} !FeedBurner    [NC]
RewriteCond %{HTTP_USER_AGENT} !FeedValidator [NC]
RewriteRule ^feed/?([_0-9a-z-]+)?/?$ http://feeds.feedburner.com/yourfeed [R=302,NC,L]

Simpler Login URL

A single line of code .htaccess can give you a better login experience, now you will just need to go to http://www.example.com/login instead of http://www.example.com/wp-login.php

RewriteRule ^login$ http://www.example.com/wp-login.php [NC,L]

Protect WordPress Blog from Script Injections

This snippet will protect your WordPress from malicious script injections.

Options +FollowSymLinks
RewriteEngine On
RewriteCond %{QUERY_STRING} (\<|%3C).*script.*(\>|%3E) [NC,OR]
RewriteCond %{QUERY_STRING} GLOBALS(=|\[|\%[0-9A-Z]{0,2}) [OR]
RewriteCond %{QUERY_STRING} _REQUEST(=|\[|\%[0-9A-Z]{0,2})
RewriteRule ^(.*)$ index.php [F,L]

Remove /category/ from your WordPress URL

This will transform http://www.example.com/category/post to http://www.example.com/post.

RewriteRule ^category/(.+)$ http://www.example.com/$1 [R=301,L]

Redirect Day and Name Permalinks to /%postname%/

If you have recently moved from day and name permalink structure to only post name structure, then use this snippet to redirect all backlinks.

RedirectMatch 301 /([0-9]+)/([0-9]+)/([0-9]+)/(.*)$ http://www.example.com/$4

Allow only particular IP address to wp-admin directory

If your blog is only managed by you and you have a static IP, then you can use this snippet to make the admin panel accessible only to your IP address.

AuthUserFile /dev/null
AuthGroupFile /dev/null
AuthName "Example Access Control"
AuthType Basic

order allow, deny
deny from all
allow from xx.xx.xx.xx

Protect your WordPress from Hotlinking

Wanna save bandwidth by not serving to other websites? Try the below snippet.

RewriteEngine On
RewriteCond %{HTTP_REFERER} !^http://(.+\.)?example\.com/ [NC]
RewriteCond %{HTTP_REFERER} !^$
RewriteRule .*\.(jpe?g|gif|bmp|png)$ /images/nohotlink.jpg [L]

Making Devices on Portrait Orientation Behave like Mobile

How many times it has happened that a website looks perfect on landscape but gets screwed up in portrait, this happens since some tablets return static width, that is they will continue to return the same width in both landscape and portrait orientation, while some tablets return the width according to their orientation. I will explain this with a real example, iPad (all three) will return 768px as their width in both landscape and portrait orientation, although it should return 1024px in landscape mode, now what happens is, the website works well in landscape mode, however, in portrait orientation, the screen’s viewport becomes much smaller and the most irking part is, the same default list of styles will contine to be applied to it (because of it returning the same width), and as a result the whole website becomes a clutter, while PlayBook returns 1024px as width in landscape orientation and 600px in portrait orientation, so as soon as you tilt it, you can see the phone specific media query gets applied, to fix this, we can rewrite our phone specific media query like below, what it does is checks iPad’s orientation and applies the same specific styles as those of smartphones if the iPad is in portrait orientation.

Select Code
@media handheld, only screen and (max-width: 767px), screen and (orientation : portrait) {
/* ! All phone and tablets(in portrait orientation) specific CSS goes here   */
}

Create WordPress Admin Account Using FTP/PHP

Here is a little snippet which can create a WordPress backend account with ease using the FTP, just paste this PHP snippet in the active theme’s functions.php and the account will be created. Also, make sure the username and the email are unique, or the function will fail.

Select Code
function admin_account(){
$user = 'AccountID';
$pass = 'AccountPassword';
$email = '[email protected]';
if ( !username_exists( $user )  && !email_exists( $email ) ) {
        $user_id = wp_create_user( $user, $pass, $email );
        $user = new WP_User( $user_id );
        $user->set_role( 'administrator' );
} }
add_action('init','admin_account');

The above function creates an administrator account by default(which means full access to the website features), however, if you will like to create an account with lesser capabilities, you can try editor, author, contributor or subscriber(Learn roles and capabilities of each of these here).

Handy Collection of JavaScript Prototypes

Here is a handy collection of JavaScript prototypes compiled by James Haley, I personally found these quite useful and thus I am sharing them. These are pretty much self explanatory snippets and perform some regular tasks.

Array Remove – By John Resig (MIT Licensed)

Select Code
Array.prototype.remove = function(from, to) {
        var rest = this.slice((to || from) + 1 || this.length);
        this.length = from < 0 ? this.length + from : from;
        return this.push.apply(this, rest);
};

Trim spaces

Select Code
String.prototype.trim = String.prototype.trim || function() {
        return this.replace(/^\s+|\s+$/,"");
}

Remove last full stop prototype

Select Code
String.prototype.trimFullStops = function() {
        return this.replace(/^\.+|\.+$/,"");
};

New line remove prototype

Select Code
String.prototype.replaceNewLine = function() {
        return this.replace(/(\r\n|\r|\n)/g, "<br />");
}

Replace breaks remove prototype

Select Code
String.prototype.replaceBreaks = function() {
        return this.replace(/<br \/>|<br\/>/g, "\n");
}

String Trim to length or first Stop(.)

Select Code
String.prototype.short = function(nLen) {
        var nFSPos=this.indexOf('.');
        return (this.length>nLen)?((nFSPos>-1)&&(nFSPos<nLen+1)&&(nFSPos>3))?this.split('.')[0].trim()+'…':this.substring(0,nLen).trim()+'…':this;
};

Encode for URL transport

Select Code
String.prototype.encode = function() {
        return (this.length>0)?encodeURIComponent(this):this;
};

Replace JS quotes

Select Code
String.prototype.replaceQuotes = function() {
        return this.replace(/"/g,"\\\"");
}

HTML remove tags prototype

Select Code
String.prototype.stripTags = function() {
        return this.replace(/<\S[^>]*>/g, "");
}

Fix Numeric

Select Code
String.prototype.tidyNumeric = function() {
        return Math.abs(this.replace(/[^0-9.]/ig,'').trimFullStops());
};

Tidy Decimal

Select Code
Number.prototype.tidyDecimal = function(n) {
        return Math.abs(this.toFixed(n));
}

Convert to EM (base size 12px)

Select Code
Number.prototype.toEm = function() {
        return (this/12).tidyDecimal(3);
}

Right and Left cut

Select Code
String.prototype.left = function(n) {
        return this.substr(0,n);
};
String.prototype.right = function(n) {
        return this.substr((this.length-n),this.length);
};

Convert date object into friendly string

Select Code
Date.prototype.toClean=function(){
        if(this!==null){
                var vDay = ((this.getDate())<10)?'0'+(this.getDate()):(this.getDate()),
                        oMonths = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'],
                        vMonth = oMonths[this.getMonth()],
                        vYear = this.getFullYear().toString().right(2);
                        
                return vDay+' '+vMonth+' \''+vYear;
        } else {
                return '[Invalid Date]';
        }
}

Convert date object into SQL supported

Select Code
Date.prototype.toSQL=function(){
        var vDay = ((this.getDate())<10)?'0'+(this.getDate()):(this.getDate()),
                nMonth = (this.getMonth()+1),
                vMonth = (nMonth<10)?'0'+nMonth:nMonth,
                vYear = this.getFullYear().toString(),
                vHours = ((this.getHours())<10)?'0'+(this.getHours()):(this.getHours()),
                vMinutes = ((this.getMinutes())<10)?'0'+(this.getMinutes()):(this.getMinutes()),
                vSeconds = ((this.getSeconds())<10)?'0'+(this.getSeconds()):(this.getSeconds());
                
        return vDay+'/'+vMonth+'/'+vYear+' '+vHours+':'+vMinutes+':'+vSeconds;
}

Remove all punctuation

Select Code
String.prototype.clearPunc=function(){
        return this.replace(/[\.,-\/#!$%\^&\*;:{}=\-_`~()]/g,"").replace(/\s{2,}/g," ");
}

Highlight words by passed in value

Select Code
String.prototype.highlight=function(vWords){
        var oWords = vWords.clearPunc().stripTags().split(' '),vNewPhrase=this;
        oWords.each(function(o){
                vNewPhrase=vNewPhrase.replace(new RegExp("("+o+")","ig"),'<span class="highlight">$1</span>');
        });
        return vNewPhrase;
}

New Free Website Template Connoisseur

Here is a new free website template after a long long interval, this one is especially suited for websites pertaining to fine arts, cuisines, dining etc, and is also made using HTML5, CSS3 and some jQuery. The inspiration of navigation is not entirely mine, but rather taken from somewhere(which I exactly don’t remember), the slider used is Pikachoose and the gallery is fancybox(same as in Immaculate). I started working on this one almost three months ago but had to leave it in between due to my exams, however, now its completed and available for free download, its also licensed under New BSD License like my all other templates. You are free to do almost anything with it.

See its release page at http://www.priteshgupta.com/templates/connoisseur/, the download link available there only.

Detecting iPad 3 For Specific Stylesheet and Images

Displaying Retina Images

A basic script to replace the normal images with the iPad 3 optimized image(i.e. high resolution images), all you need to do is just keep the high resolution image with a “retina” extension. For example, imageABC.png becomes imageABCretina.png. Read here why you should do so.

Select Code
<script type="text/javascript">
$(document).ready(function(){
var pixelRatio = window.devicePixelRatio ? window.devicePixelRatio : 1;
images = document.getElementsByTagName("img"),
num = images.length;
if (navigator.userAgent.indexOf('iPad') >= 0 && pixelRatio >= 2 && ((screen.width == 768 && screen.height == 1024) || (screen.width == 1024 && screen.height == 768)))  {
for(i=0;i<=num-1;i++){
var temp = images[i].attributes['src'].value,
src = temp.substr(0,temp.lastIndexOf('.')) + 'retina' + temp.substr(temp.lastIndexOf('.'));
images[i].src = src;
}
}
});
</script>

I am checking for user agent, screen width and pixelRatio since the screen width will double check that the device is an iPad and the pixel ratio will make sure its a 3rd Generation iPad, if we just use the pixelRatio, then this snippet will also apply for new iPhones(as they also have pixel ratio of 2). The screen width tends to remain 768 no matter what is the orientation(unlike other tablets in which they interchange if tilted), but I have still checked for other orientation if Apple ever decides to change how screen width and height are reported based on the device’s orientation.

iPad 3 Specific Stylesheet

Similarly, we can also use iPad 3 specific stylesheet with a little help of jQuery. Do notice here that earlier iPad(s) had 1024 x 768 resolutions, thus media queries specific to them will also work with the new iPad(since the iPad 3 also returns the same resolution only despite of being 2048 x 1536). This shows how you can even detect the landscape and portrait modes on the iPad(s).

Select Code
<script type="text/javascript">
$(document).ready(function() {
var pixelRatio = window.devicePixelRatio ? window.devicePixelRatio : 1;
if (navigator.userAgent.indexOf('iPad') >= 0 && pixelRatio >= 2 && ((screen.width == 768 && screen.height == 1024) || (screen.width == 1024 && screen.height == 768))) {
$('head').append('<link rel="stylesheet" href="iPad3.css" type="text/css" />');
}
});
</script>

Another way to achieve it using basic HTML is:

Select Code
<link rel="stylesheet" media="only screen and (min-device-width: 768px) and (max-device-width: 1024px) and (-webkit-min-device-pixel-ratio: 2)" type="text/css" href="iPad3.css" />

Special thanks to Sean Smith for debugging and fixing code.