Tag: jQuery

Picking up random elements from DOM using jQuery

tumblr_n1zv0cTukw1tubinno1_1280

Selecting a group of DOM elements is super duper easy these days using CSS selectors, or a particular element via their ID. But what about picking up a random element from these group of elements? In this article I am going to show you how to do it by extending jQuery

Let’s consider that we have the following markup. Now we will pick a random button and change it’s value

[sourcecode language=”html”]
<div class="container">
<button>1</button>
<button>2</button>
<button>3</button>
<button>4</button>
<button>5</button>
</div>
[/sourcecode]

Let’s extend jQuery and add a random() function to it

[sourcecode language=”javascript”]
$.fn.random = function() {
return this.eq(Math.floor(Math.random() * this.length));
}
[/sourcecode]

Now we can pick up a random button and change it’s value quite easily.

[sourcecode language=”javascript”]
$(".container button").random().html("Click Me");
[/sourcecode]

That was easy, eh? Hope you’ll like it.

Delegating Events Instead of Direct Binding in DOM

tumblr_n1rr53o21A1tubinno1_1280

When it comes to attaching event listeners, be it a particular element in the DOM, or a group of elements via CSS selectors, most of us bind the event listener directly to the elements. Direct binding is fine when you’re doing for a PARTICULAR element, but it may create problems for a group of elements if you’re not taking extra care while event binding. To understand the issue, let’s have a look at the following code block (Here’s a live example)

[sourcecode language=”html”]
<!– index.html –>
<div class="container" style="margin-bottom:50px;"></div>
<input type="button" value="Add More Buttons" id="addmore" />
[/sourcecode]

And we added the following javascript (depends on jQuery)

[sourcecode language=”javascript”]
;(function($){
$(document).ready(function(){
$("#addmore").on("click",function(){

var l = $(".container button").length+1;
$("<button/>").html("Click Me "+l).appendTo($(".container"));
$(".container button").on("click",function(){
alert("Clicked");
});

});
});
})(jQuery);
[/sourcecode]

Now if you add more and more buttons, you can see that it repeatedly attaching events. See the effect in the following animation

dom-1

To avoid these repeated bindings, you can modify your code like this and detach all the event listeners which were attached previously to these buttons.

[sourcecode language=”javascript”]
$(".container button").off("click");
$(".container button").on("click",function(){
alert("Clicked");
});
[/sourcecode]

This is boring, lengthy and sometime risky because you have to manually detach events everytime a new DOM element which satisfies your CSS selector rule adds in the container. And if you forgot to do that, chances are higher to break something somewhere.

Now, to save from this pain, jQuery had introduced event delegation which doesn’t bind the event listener to the dom elements but it delegates the event from their parent. This way, you will never have to worry about detaching previous attached event listeners anymore. Let’s have a look at our final code block, and here is a live example too

[sourcecode language=”javascript”]
;(function($){
$(document).ready(function(){

//event delegation
$(".container").on("click","button",function(){
alert("Clicked");
});

$("#addmore").on("click",function(){

var l = $(".container button").length+1;
$("<button/>").html("Click Me "+l).appendTo($(".container"));

});
});
})(jQuery);
[/sourcecode]

In the above example see how we have delegated the click event to every “button” in the container div. Once the delegation is done, it doesn’t matter whenever a new dom element (in this case, a “button”) inserts in the container. It will always capture the “click” event because the parent div “.container” will delegate that event to it properly. All you have to do is select a parent element, and then delegate the event to childrens (via CSS selector) belonging to it. It’s the same .on() method, just takes an extra parameter in the middle which represents the CSS selector to which the event will be delegated.

[sourcecode language=”javascript”]
//event delegation
$(".container").on("click","button",function(){
alert("Clicked");
});
[/sourcecode]

By using event delegation in jQuery for a group of DOM elements, you can avoid risks, keep your code cleaner and save yourself from some overkill every time. Hope you’ve liked this article 🙂

BucketAdmin – Our new dashboard for your next web application

01_bucketmin_preview.__large_preview

If you are a fan of beautiful dashboards and admin panels, then BucketAdmin might be a good choice for you with plenty of carefully selected javascript controls and plugins. Beside that, BucketAdmin’s documentation and clean structure will help you to implement it without a lot of pain. Purchase BucketAdmin today for $21 only from http://bit.ly/1e9TtGP.

Here is a collection of a few cool features of BucketAdmin

BucketAdmin Features

Improving UX in the WordPress Admin Panel with Interactive Meta Boxes

Our goal is simple today, we want to add interactivity to our boring metaboxes. Instead of showing lots and lots of irrelevant input boxes at once, we will properly group them into different metaboxe containers and then display the required one based on the action of another one.

We will create a custom post called “profession”, then we will let our user choose from two pre defined professions, for example “photographer” and “programmer”. Based on his choice we will display another set of metaboxes to get the details of that profession.

Step 1: Register the custom post
Here is a simple custom post register script, add the following snippet in your functions.php

[sourcecode language=”php”]
add_action( ‘init’, ‘mytheme_custom_post_profession’ );
function mytheme_custom_post_profession() {

$labels = array(
‘name’ => _x( ‘Professions’, ‘profession’ ),
‘singular_name’ => _x( ‘Profession’, ‘profession’ ),
‘add_new’ => _x( ‘Add New’, ‘profession’ ),
‘all_items’ => _x( ‘Professions’, ‘profession’ ),
‘add_new_item’ => _x( ‘Add New Profession’, ‘profession’ ),
‘edit_item’ => _x( ‘Edit Profession’, ‘profession’ ),
‘new_item’ => _x( ‘New Profession’, ‘profession’ ),
‘view_item’ => _x( ‘View Profession’, ‘profession’ ),
‘search_items’ => _x( ‘Search Professions’, ‘profession’ ),
‘not_found’ => _x( ‘No professions found’, ‘profession’ ),
‘not_found_in_trash’ => _x( ‘No professions found in Trash’, ‘profession’ ),
‘parent_item_colon’ => _x( ‘Parent Profession:’, ‘profession’ ),
‘menu_name’ => _x( ‘Professions’, ‘profession’ ),
);

$args = array(
‘labels’ => $labels,
‘hierarchical’ => false,
‘public’ => true,
‘show_ui’ => true,
‘show_in_menu’ => true,
‘supports’ => array( ‘title’, ‘thumbnail’),
);

register_post_type( ‘profession’, $args );
}
[/sourcecode]

Step 2: Add the necessary libraries in your theme/plugin
Creating metaboxes is a tedious and boring task. So we will take help of one of the fantastic metabox libraries out there. We will be using Custom-Metabox-Framework which is also widely known as “CMB”. It will make our code a lot less cluttered. So download (or checkout) the library, unzip and rename the folder as “cmb” and place it inside your theme folder. Now add the following code in your functions.php

[sourcecode language=”php”]
add_action( ‘init’, ‘mytheme_initialize_cmb_meta_boxes’ );
function mytheme_initialize_cmb_meta_boxes() {
if ( !class_exists( ‘cmb_Meta_Box’ ) ) {
require_once( ‘cmb/init.php’ );
}
}
[/sourcecode]

Step 3: Create some metaboxes for this profession custom post
Now we have all the necessary tools available, lets create three metaboxes and attach them with only this “profession” type custom post.

[sourcecode language=”php”]
function mytheme_profession_metaboxes( $meta_boxes ) {
$prefix = ‘_mytheme_’; // Prefix for all fields
$meta_boxes[] = array(
‘id’ => ‘profession_details’,
‘title’ => ‘Profession Details’,
‘pages’ => array(‘profession’), // post type
‘context’ => ‘normal’,
‘priority’ => ‘high’,
‘show_names’ => true, // Show field names on the left
‘fields’ => array(

array(
‘name’ => ‘Your Name’,
‘id’ => $prefix . ‘name’,
‘type’ => ‘text’
),
array(
‘name’ => ‘Profession Type’,
‘id’ => $prefix . ‘profession_type’,
‘type’ => ‘select’,
‘options’=>array(
array("name"=>"Select a Profession","value"=>0),
array("name"=>"Photographer","value"=>1),
array("name"=>"Programmer","value"=>2),
)
),
),
);

$meta_boxes[] = array(
‘id’ => ‘profession_photographer’,
‘title’ => ‘Some details of your <b>photography</b> job’,
‘pages’ => array(‘profession’), // post type
‘context’ => ‘normal’,
‘priority’ => ‘high’,
‘show_names’ => true, // Show field names on the left
‘fields’ => array(
array(
‘name’ => "Your Camera",
‘id’ => $prefix . ‘photography_camera’,
‘type’ => ‘text_medium’
),
array(
‘name’ =>"Your primary interest is",
‘desc’ => ‘Landscape/Portrait/Street/Lifestyle’,
‘id’ => $prefix . ‘photography_interest’,
‘type’ => ‘text_medium’
),
),
);

$meta_boxes[] = array(
‘id’ => ‘profession_programmer’,
‘title’ => ‘Some details of your <b>programming</b> job’,
‘pages’ => array(‘profession’), // post type
‘context’ => ‘normal’,
‘priority’ => ‘high’,
‘show_names’ => true, // Show field names on the left
‘fields’ => array(
array(
‘name’ => "Your Favorite IDE",
‘id’ => $prefix . ‘programming_ide’,
‘type’ => ‘text_medium’
),
array(
‘name’ =>"Your primary language",
‘desc’ => ‘C/PHP/Java/Python/Javascript’,
‘id’ => $prefix . ‘programming_lang’,
‘type’ => ‘text_medium’
),
),
);

return $meta_boxes;
}

add_filter( ‘cmb_meta_boxes’, ‘mytheme_profession_metaboxes’ );
[/sourcecode]

At this point, if we click on “New Profession” from our WordPress admin panel, we will see the editor screen like this. Please notice that we have already disable the “editor” field while registering this custom post (using the “supports” attribute)

The Profession Screen

Uh, oh! that looks very confusing for people of both professions. I mean asking the photographer about their favorite language and ide is utter nonsense, and vice versa. So How can we make sure that only photographers will see the second metabox container, and programmers will see the third metabox container? Lets do this!

Step 4: The Magical Ingredient: Adding the interactivity using Javascript
We need to add some javascript at this point to improve the user experience at this point. Create a new javascript file inside the “js” folder inside your theme folder. Name the file as “profession-admin.js”. Now we need to make sure that this file is loaded properly in the admin panel.

[sourcecode language=”php”]
function mytheme_admin_load_scripts($hook) {
if( $hook != ‘post.php’ && $hook != ‘post-new.php’ )
return;

wp_enqueue_script( ‘custom-js’, get_template_directory_uri()."/js/profession-admin.js" );
}
add_action(‘admin_enqueue_scripts’, ‘mytheme_admin_load_scripts’);
[/sourcecode]

Now open the js/profession-admin.js and add the following code. Please keep in mind that jQuery is loaded in wordpress admin panel by default, and it works in no-conflict mode. So we want code like this if we want to use our favorite $ as a reference to the jQuery object.

[sourcecode language=”javascript”]
(function($){
$(document).ready(function(){
$("#profession_photographer").hide();
$("#profession_programmer").hide();

//lets add the interactivity by adding an event listener
$("#_mytheme_profession_type").bind("change",function(){
if ($(this).val()==1){
// photographer
$("#profession_photographer").show();
$("#profession_programmer").hide();
}else if ($(this).val()==2){
//programmer
$("#profession_photographer").hide();
$("#profession_programmer").show();
} else {
//still confused, hasn’t selected any
$("#profession_photographer").hide();
$("#profession_programmer").hide();
}
});

//make sure that these metaboxes appear properly in profession edit screen
if($("#_mytheme_profession_type").val()==1) //photographer
$("#profession_photographer").show();
else if ($("#_mytheme_profession_type").val()==2) //programmer
$("#profession_programmer").show();

})
})(jQuery);
[/sourcecode]

At this moment, when you click on the “New Profession” you will see like this.
Improved Profession Screen

And if you select a profession, the appropriate metabox will be displayed instantly.
Photography

That looks good eh? So what did our javascript do? Lets have a look at the things it does

  • It passes the jQuery object to our function as $
  • It hides all the secondary metaboxes related to the professions
  • It registers a new event listener that monitors the change event in our profession select box
  • It displays the appropiate metabox when someone picks a profession
  • It also displays the correct metabox when someone edits a profession

So that’s mainly it. We have made our profession screen look much better. And we are now collecting details about the particular profession without confusing people from other professions. And most of all, it is much friendlier than before 🙂

I hope you have enjoyed this article and already started planning to implement it in your next wordpress project. Have fun!

Shameless Plug
If you are looking for a fantastic NGinx+PHP-fpm based WordPress hosting with Solid Performance, give WPonFIRE a try. You will never be disappoint at all. And if you want a 25% discount coupon for life, let me know in the comment and I will arrange you one.

WPonFIRE Premium WordPress Hosting for Everyone

Breakpoint JS – load external javascript for different browser breakpoints

idea

Live Demo: http://hasinhayder.github.io/BreakPoint/

Breakpoint helps you to define multiple breakpoint ranges and load external javascript files when someone resize their browser window to those breakpoints. Beside loading external scripts, Breakpoint also triggers an event whenever browser width falls in any of those predefined breakpoint ranges.

Using Breakpoint
Using BreakPoint is pretty simple. Include jQuery in your web application and then include jquery.breakpoint.js. Now you can define multiple breakpoint ranges and initialize like this

[sourcecode language=”javascript”]
$(document).ready(function(){
$.BreakPoint({
breakpoints:{
mobile:{max:480,load:true},
default:{min:480,max:1024, load:true},
wide:{min:1024,max:1200,load:true},
superwide:{min:1200,load:true},
}
});
});
[/sourcecode]

In the example above, we have defined four different breakpoints. The first one mobile will be used whenever browser is resized from 0px to 480 pixel (all inclusive). The next breakpoint, default will be used whenever browser is resized between 480px to 1024px (all inclusive), and so on.

Now, whenever a breakpoint is reached, BreakPoint jQuery Plugin will load an external javascript file with the same name of the breakpoint. For example, when browser is resized to 400px it will fall under mobile and now an external file named mobile.js will be loaded and executed.

By default BreakPoint will look for external javascript files in the js/ folder in the current path. But you can change this by passing a parameter named prefix, like this

[sourcecode language=”javascript”]
$(document).ready(function(){
$.BreakPoint({
prefix:"scripts/",
breakpoints:{
mobile:{max:480,load:true},
default:{min:480,max:1024, load:true},
wide:{min:1024,max:1200,load:true},
superwide:{min:1200,load:true},
}
});
});
[/sourcecode]

Now BreakPoint will load external js files from the scripts/ folder.

Breakpoint Parameters
prefix: By default, prefix is set to js/ but you can change it to anything you want.
breakpoints: for each breakpoints, there are three paramaters you can pass which are “min”, “max” and “load”. By default min is set to 0, max is set to 9999 and load is set to false. The load parameter is an important one if you want to load external javascript files whenever a breakpoint is reached. If load is set to true, external files will be loaded, otherwise not.

BreakPoint Events
Whenever a breakpoint is reached, BreakPoint plugin will trigger a window event named breakpoint. The event object will have an attribute named breakpoint which will contain the name of the breakpoint that has been reached. Here is an example how you can add an event listener to this breakpoint event

[sourcecode language=”javascript”]
$(document).ready(function(){
$(window).bind("breakpoint",function(e){
if(console)
console.log(e.breakpoint);
});
});
[/sourcecode]

That’s mainly it. Enjoy! Check out the live demo at http://hasinhayder.github.io/BreakPoint/

The Badass List of Essential jQuery Plugins

banner

Check it out here: http://hasinhayder.github.io/essential-jquery-plugins/

I have started curating this list for last couple of weeks and the purpose is to create an one stop place where you can look for the essential jQuery plugin for your project and look no where else. Honestly, sometime it’s really hard to find the perfect plugin in this overwhelming world of jQuery plugins.

I hope you will find it useful. If you want to contribute, you can open an issue and tell me a missing plugin and I will be happy enough to look at it. If it’s worth to be in the list, it will be added back there, no worry. You can also fork this github repo and add the missing plugin in the readme.md file in markdown format and send me a pull request.

So enjoy this badass list of essential jQuery Plugins which is continuously growing.

An Animated Responsive grid with Filtering feature

This is a followup of my previous post, where we had created a beautiful responsive grid with barely 6 lines of javascript code. But this time, we have added filtering feature in it, and added category/tag selector which triggers the filtering. For filtering we have used MixItUp library in this example.

Have a look at the live demo at http://hasinhayder.github.io/ResponsiveGalleryWithFiltering. Resize the browser window and see how the grid items adapt to the new width. Select categories from the dropdown list in the top right corner to see how the filtering works.

Positioning the dropdown list was managed using media queries which you can see at the bottom of the <style> block.

One more thing to note here, a very important note perhaps. If you have used MixItUp before then you probably already know that every time mixitup refreshes the list, it actually removes the old list items and redraws them in the container. This phenomenon removes any events attached to the list items. To fix it up, you need to attach event listeners using $.delegate() method, as done in the example. However, lets have a look at that

[sourcecode language=”javascript”]
$(".grid ul").delegate("li","click",function(){
var src = $(this).find("img").attr("src");
alert(src);
});
[/sourcecode]

Enjoy!

Detecting if a DOM element has visible scrollbar.

Webkit browsers, specially in Mac osx hides the scrollbar intelligently when not in use. This feature improves the look-n-feel. But for the designers, sometime this can be a pain because they may need to alter the designs based on the visibility of scrollbar.

Here goes two simple jQuery plugin which can detect the visibility of scrollbar for a given DOM element

For Horizontal Scrollbar
[sourcecode language=”javascript”]
(function($) {
$.fn.hasHorizontalScrollBar = function() {
return this.get(0) ? this.get(0).scrollWidth > this.innerWidth() : false;
}
})(jQuery);
[/sourcecode]

For Vertical Scrollbar
[sourcecode language=”javascript”]
(function($) {
$.fn.hasVerticalScrollBar = function() {
return this.get(0) ? this.get(0).scrollHeight > this.innerheight() : false;
}
})(jQuery);
[/sourcecode]

You can later use it like this
[sourcecode language=”javascript”]
if($("#element").hasVerticalScrollbar()){
//do whatever you’d like to
}
[/sourcecode]

Source & Idea: This SO Discussion 🙂

LazyMouse jQuery Plugin – detect mouse inactivity easily :)

LazyMouse

Before jumping into the details, let me hear you asking “WHY?”. To be honest, not all of you will need to detect the mouse inactivity in your web applications. But sometime, it’s useful to do something different after a certain period of inactivity either to grab attention of the viewer, or to help him by improving the UX. For example, hide the sidebar and top navigation when user is reading the content, to emphasis his reading experience. Or show an animation – just do whatever during your user’s mouse is inactive for some time.

And to detect mouse inactivity easily, here comes the LazyMouse jQuery plugin which attaches two new events to the bodyelement, one is mouse.active and another one is mouse.inactive . You can just add two listeners for those events and do whatever you want to do 🙂

Using jQuery LazyMouse is pretty simple. Initialize it like this
[sourcecode language=”javascript”]
$(document).ready(function(){
$.LazyMouse();
})
[/sourcecode]

You can also specify the inactivity threshold in milliseconds, like this

[sourcecode language=”javascript”]
$(document).ready(function(){
$.LazyMouse({
delay:2000 //2 seconds threshold
});
})
[/sourcecode]

Once initialized, as we have mentioned earlier, the body element will be triggered with two new events. Lets add a listener to those, like this

[sourcecode language=”javascript”]
$(document).ready(function(){
$("body").bind("mouse.active",function(){
console.log("Mouse Active");
});
$("body").bind("mouse.inactive",function(){
console.log("Mouse Inctive");
});
})
[/sourcecode]

The events are propagated using jQuery Debounce, and therefore it is rate limited for good. See the live demo at http://hasinhayder.github.io/LazyMouse, and fork the github repo at http://github.com/hasinhayder/LazyMouse

Enjoy 🙂

An awesome animated responsive grid in a few lines of javascript and css3 goodness

Screen Shot 2013-08-15 at 4.36.33 AM

Responsive grid is a pain to many people, because sometime they have to achieve the desired effects either using complex plugins, css layout styling with the help of media queries. And here comes a nifty solution which works perfectly well in all devices. The responsiveness is done using a few lines of Javascript which listens to window resize event. But to save the browser from refreshing the layout, it uses debounce technique which only fires after the resizing is done.

The trick is pretty neat. All you got to do is tell it a minimum width of the grid items. Then, once resized, it divides the window width by that minimum, extract the integer part and displays that many items in a row by setting a width (in percentage) for each of them.

[sourcecode language=”javascript”]
var minWidth = 250;
$(document).ready(function(){
$(window).resize($.debounce(250,function(){
var w = $(window).width();
var numberOfItems = parseInt(w/minWidth);
var itemWidthinPercentage = 100/numberOfItems;
$(".grid ul li").css({width:itemWidthinPercentage+"%"});
}));
});
[/sourcecode]

See the working grid at http://hasinhayder.github.io/responsivegrid and resize the window to check out how it fits perfectly.

The animation is done using the following css3 transition for each list item
[sourcecode language=”css”]
-webkit-transition:all 0.2s ease;
-moz-transition:all 0.2s ease;
-o-transition:all 0.2s ease;
-ms-transition:all 0.2s ease;
transition:all 0.2s ease;
[/sourcecode]

Checkout the demo and fork the github repo to customize it anyway you’d like to 🙂