A whole new way of writing jQuery plugins

On August 22 2005, John Resig offered the first hint of a JavaScript library to use CSS selectors. It’s almost a decade since then. Today jQuery is used on more than half of all websites. There are about a billion websites out there!

There is no other JavaScript library that is used as a dependency as much as jQuery. In fact the importance of jQuery becomes immediately evident when you start putting together a web application without it. It has a massive eco system of plugins which acts as the ‘batteries’ (if you will) for your jQuery based applications. And that’s what this article is about: Super simplifying jQuery plugin creation (especially useful if you have a application with a dozen or more jQuery plugins)

Before we move on, here’s what a plugin will look like once I m done explaining this whole new way of writing jQuery plugins:

This is a very simple plugin that sets the color of an element to red. As you can see, it’s quite short yet very readable. Of course, a lot of boilerplate code that you will add to a plugin is abstracted out and added to the jQuery object.

this.$el

One thing that may stand out is the use of this.$el. This is just a reference to the element on which the plugin will be initialized. It is already added in the abstracted out plugin generator code. The init method is called by default. It acts as a handy method to bootstrap your plugin initialization the way you want.

The objective is to define the functionality of your plugin in an object literal and abstract out all the common code required to write a testable jQuery plugin.

Let’s say we abstracted out all the boilerplate code into a function called registerPlugin and put it in the root jQuery object, we can then use it like this:

This will add ‘colorMeRed’ as a plugin to jQuery’s prototype (stored as $.fn) using the factory design pattern. In this pattern a plugin is defined as a Function and extended via it’s prototype object to implement further functionality. In our case, this will happen behind the scenes (instead of the plugin definition itself)

Let’s initialize the plugin on a div element.

Let’s say we wanted to add another functionality to this plugin which allows us to restore the original color of the element. Basically we would need to store the original color before applying the new color and simply revert to it when need be. Hence we will modify the code a little and add a new method to the object literal

Now if we would like to restore the color at some point we would simply call the plugin again and pass the ‘restore’ function to it.

This will not re-initialize the plugin all over again. It will simply go to the plugin function on that element and execute the ‘restore’ function in it.

How to use this new way of writing jQuery plugins?

Download the jQuery.registerPlugin utility and load it using the script tag before you load your scripts that define your objects. You can even use require.js to load the jQuery plugin utility and then use the registerPlugin

Added functionality

Since the core plugin creation is abstracted out, you can then implement common functionality to ‘all’ the plugins at once.

Find elements within the element

If you want to select an element with the class comments on the page, you’d typically do $(‘.comments’). But  If you’d like to look for this inside the element on which the plugin is initialized, then you would have to do an elaborate ‘find’ relative to the element. The jQuery.registerPlugin utility provides a short hand for this.

Calling a plugin’s method from another plugin.

Let’s say we have 2 divs with the classes a and b with the plugins plugA and plugB initialized on them respectively. Then plugA can initialize a method from plugB like this,

Event map

Inspired by backbone.js the registerPlugin utility provides a helper to define events and handlers. For example, let’s say you have registered an object literal as a jQuery plugin and initialized it on a DOM element that has the following markup:

Let’s say you want to add a onClick event handler on the button element and you’d like it to call a method that’s already defined in your object literal, then you can use the event map:

The openCommentSection method is a property on the object literal. We are simply routing the click event on the button element to call it. As you can quickly notice, now the openCommentSection is available for any other scenario as well. Now it’s not just limited to the button’s click event. Not to mention, it can be isolated and tested as well.

Mixins

One of the aspects of writing code is ‘code reuse’. Since we are using an object literal to define the plugin, we can use existing objects and combine their methods to compose a new object to create our jQuery plugin object literal. Consider the following 2 objects (let’s assume they lie in their own .js files)

We can then mix and match their methods to create an entirely new object, like this:

Now we have a whole new object made with a method from object ‘a’ and a method from object ‘b’. We can use this to create our plugin:

Closing notes

Like the title of this post says, this is a whole new way of writing jQuery plugins. If you notice something that needs attention or could use some improvement, then do express your concern via comments or better still, fork this repository and create a pull request! This is an open source initiative to standardize and super simplify jQuery plugin creation.


Categories: Javascript, jQuery, Useful | Tags: , , , | Comments Off

Understanding JavaScript closures through the context of Indian classical music and modern art

One good thing about music, when it hits you, you feel no pain.
- Bob Marley

As of EcmaScript 5, closures, along with functions, are at the heart of creating modules in JavaScript. While understanding closures can take some time initially, the effort invested yields great results on the dawn of understanding of what closures are. A “closure” is an expression (typically a function) that returns an object or function along with the environment it was created in, such that it has access to the variables and identifiers from the environment, even after that environment or the function that surrounds (or closes) it, has returned.

In Indian classical music, there is a concept called Raaga. Raaga is like an advanced scale or mode with melody. Using a scale as the means to define a Raaga is like using tap water to explain the concept of rain. But there is really no simpler way to explain this to an audience which comprises of both Indian as well non Indian ‘closure’.

There are many different Raagas. In many cases, a Raaga is explored in a concert by a vocal artist or instrumentalist with an attempt to invoke in the listeners, the original emotion that was responsible for the birth of the Raaga. To give the listeners the same feeling without giving them the circumstances that caused that feeling.

JavaScript closures and Indian classical music

Awareness of the feeling thru the rendition of a Raaga is the transfer of state(emotion) and data(notes) to the listener. Once the listener is one with the feeling that the artist is trying to express, a perfect closure scenario takes place. The feeling the listener gets is the object returned and the rendition itself is the closure. The same analogy can be easily applied to the other art forms. An artist’s painting is the closure and the disturbance or joy derived by soaking oneself in the artwork is the object returned. No wonder then, we feel nothing sometimes when we look at some of the modern art. That happens when the closure fails to return an object along with it’s environment.

To sum it up, closures give out a function or object that remembers the environment it was created in. The general approach to understanding closures is to get as many different perspectives about it till one of ‘em clicks for you. I hope this abstract comparison to art  and music for explaining closures acts as yet another perspective about closures. Happy coding!


Categories: Javascript | Tags: , | Leave a comment

Simple pattern matching with Javascript String.replace

The first rule of any technology used in a business is that automation applied to an efficient operation will magnify the efficiency. The second is that automation applied to an inefficient operation will magnify the inefficiency.
-Bill Gates

For my personal music related project (Scribbletune) I wanted to generate an array of objects from a string. Here are some examples of the input expected and the output desired in each case:

Input (String):

Output(Array of Objects):

What’s happening here is, x denotes a Note On state and one or more underscores following an x denotes the length of the note in units of 32. Each hyphen denotes an interval or a Note Off state. The first thing that came to mind was to use a for loop on the string input and then whenever x is detected, I could split the string from that x to the end of the string and run one more loop to find the occurence of the underscores and use them to compute the noteLength value.

So then it would like

This is fine and it will get the job done. But I wanted to break away from the dependency on the for loop.

Enter String.replace

The replace() method returns a new string with some or all matches of a pattern replaced by a replacement.  The pattern can be a string or a RegExp, and the replacement can be a string or a function to be called for each match.

Basically I d need to ‘match’ occurrences of  x followed by zero or more underscores and occurrences of hyphens. Then based on those, I d just need to push the desired object to an array.

And that’s about it. The jsperf for this shows tremendous performance improvement as well as reduced number of lines of code (from 25 lines it went down to 4 lines) without sacrificing readability!


Categories: Javascript | Tags: , | Leave a comment

How to load jquery plugins dynamically while understanding Javascript closures and the difference between apply and call.

I guess the issue for me is to keep things dynamic.
-Robert Downey, Jr.

When I was a kid, I had this big hard cover red book of Russian folk tales. This book was filled with stories of dragons with more than 8 heads dealing with sons and daughters of farmers while covering a lot of ground on foot or animal back. Each story had a really long title, just like the title for this blog post :)

At the cost of not digressing any more, I ll start off with what I intended to document through this post. I had to solve a challenge where there were over 50 custom jquery plugins written to do specific things on certain HTML elements but the presence of the HTML elements that they were to be initialized on were not fixed. It was certain though that there would not be more than 7 or 8 elements at any given time that would need their corresponding plugins. So here’s what I came up with for this. It also helps me showcase a really good example for JavaScript closure and the difference between apply and call. I ve noticed that these terms are searched widely and though the explanations for them exist widely too, there just arent enough good examples that demonstrate them.

Ok here goes.

You can download this sample from github to see how the files are structured and what are their contents.

Just as a sample, I created just 4 js files and called them a.js, b.js, c.js and d.js. These were to denote 4 custom jquery plugins. For this sample the plugin would just put the alphabet letter in the html() of the element they were initialized on. So the plugin a.js would insert ‘a’ in the html element that it was initialized on. b.js would insert ‘b’ in the html element that is was initialized and so on:

Then I created a HTML page that had DIVs in the following fashion in its BODY tag:

As you can see, each div has a class called ‘hasPlugin’ to denote that this html element will need a plugin initialized on it. These divs also have a data-plugin attribute that denotes the name of the plugin that it needs. As you can also see, I have 3 divs with the requirement for the plugin ‘a’. This is just to demonstrate a one to many relation while initializing the plugins.

The only next thing I did in the HTML was to add a script tag that pulled jquery from a CDN

This concludes my HTML setup. For the SCRIPT part, I started with an anonymous function declaration. But this is not my example for JavaScript closures. That example will come up shortly and it ‘will’ explain how and why you would use it :)

My goal was clear and my logic was simple. I knew that there could be multiple DIVs that required the same plugin. And I certainly did not want to go and fetch that plugin multiple times. Neither did I want to use some custom function to loop over an array to remove duplicate entries. So I defined a hash map kinda object called plugs = {}. I looped over the DIVs which had the class ‘hasPlugin’ and took their data-plugin attribute to determine the name of the required plugin. I started assigning the names of the plugins as properties of the plugs object. Every time I did that if that property already existed

This way I did not have to worry about having to explicitly remove duplicates. Here’s how that code looked:

At the end of that I got a pseudo hashmap with plugin names as the property name and an object with the DIVs that had the plugin applied to them as a value. I also included the name of the plugin in this object so that I could make use of it later.

All I need to do now was to go over the plugs object and take each ‘item’ in it and load the JavaScript file for it. On loading of that file I needed to initialize that plugin on to the DIVs of that ‘item’. Here’s where we’ll use the closure (as well as the function.call method)

A little bit of explanation is called for. In the loop, I m first setting up a file reference object that create’s a SCRIPT tag it’s src attribute set to the name of the plugin. That was pretty straightforward. The next thing I do is to check for the onload method of the file reference object in which I use a JavaScript closure. I love digressing and I m gonna do that for a bit now. Let’s say you had a bunch of buttons that you created from a ‘for’ loop. Like this:

What do you think will be alerted every time you click any of the buttons? If you are one of those really cool kids who actually try out things before answering these kinda questions, you ll take a moment to quickly run that last snippet in the console of your browser to learn that no matter what button you click, it always alerts 5! What a mischievous bunch of buttons we’ve created! :D Well maybe it was obvious and maybe you re so cool that you knew it without running the snippet in the console of your browser :)

If we change the snippet such that we use a JavaScript closure in the form of an anonymous function inside the loop and explicitly tell it the value of i then we can discipline the buttons to behave appropriately:

Basically we are passing that (function(){})(); thing inside the onclick to define an anonymous function which we are defining and calling at the same time. ()(); is the function call itself. The first set of braces is to define the function with whatever arguments we want. The second set of braces is to pass in the arguments we defined. This should suffice as a good example of a closure. If you run that last snippet in your browser’s console, you ll see that the buttons are not so mischievous anymore.

Going back to the intended subject of this post, we are using a similar closure to define an anonymous function which is called at the same time and we are passing it the plug object to work with.

Now we come to the difference between JavaScript function.call and function.apply. In the following partial snippet I m using function.call:

Both function.call and function.apply have a similar role to play. Both call a function and allow us to pass the value for ‘this’ as the first argument followed by the arguments required by the function itself. If you do not know how many arguments you are gonna end up passing OR if the function expected an Array to be passed, then use function.apply. But if you know the number of arguments you are going to pass, then use call. A comment on StackOverflow had an interesting way to remember this. The comment was something to the effect of, use Apply for an Array as an argument (AA) and use Call when you can Count the arguments you re going to pass (CC). Unfortunately (at least for me) this does not yet fully explain the difference nor the use case scenario for either function.apply OR function.call. I need a real world use case scenario sometimes to understand some concepts. The topic I m covering in this post helps me get just that. A use case scenario!

So as we ve discussed so far, we are dealing with a bunch of jquery custom plugins that we load dynamically and initialize them on DIV elements that need them. Since they are jquery plugins, they are basically namespaced under $.fn coz at the very basic level, a jquery plugin is:

So if I had to initialize that on the first DIV element on a page, I d first need to load the script file a.js along with jquery and then simply initialize the plugin in this way:

For our example, we do not have ‘div:first’ nor do we know that it needs plugin ‘a’. But we do have those in variables. So we use function.call in this fashion:

This will initialize the pluginName on to $(div). This could ve been done with function.apply in this fashion:

But since the plugin did not have any arguments for this sample, we do not need to pass any second argument to either call or apply. In such a case I d rather use function.call coz it may be a little faster than function.apply which has to parse the second argument as Array. Function.call is not obliged to do so and we do not have a second argument here.

So that summarizes my take on dynamic jquery plugin loading, closures and apply vs call. You can download this sample from github to see how the files are structured and what are their contents.


Categories: How To, Javascript, jQuery | Tags: , , , | Leave a comment

How to run Grunt tasks only on changed files

You can observe a lot by just watching.
-Yogi Berra

For a recent workflow improvement I was trying at work, I needed to setup a Grunt watch and uglify on a bunch of javascript files to minify them into individual minified files and then concatenate them. The number of files to be concatenated was over 50 hence uglifying the whole bunch each time a file was updated would slow down the workflow.

So the goal was to minify each file individually into its own minified version and then run a watch on the minified files directory contents and concatenate the minified files into one js file. The uglify target looked like this:

The second part of the goal was to concatenate minified files into one main.js. This needed to happen every time a file was minified. Which means I needed to run the uglify task only on the file that was changed or updated and then concatenate the minified files. Before moving on, here’s the Grunt concat task inside the watch:

A watch task on the ‘js’ directory would run the uglify task and a watch task on the ‘js-min’ directory would run the concat task. The challenge was, every time the uglify task ran, it went through all of the js files specified in it’s target and uglified them. And then the watch task on the ‘js-min’ directory would kick in and concatenate all the files in the ‘js-min’ directory. SO the required behaviour was to set the watch task for uglify to run only on the updated/changed file.

Say hello to the on watch event

Grunt watch has a ‘on’ event so that one can compile files as needed. My first hack was to use this ‘on’ event and run uglify on the changed file from this event’s handler which provides a filepath paramenter. Grunt’s core developers will not advise us to use this event method in this fashion as it deviates from the standard procedure of assigning tasks using Grunt. Hence we ll maintain the existing uglify task just the way it was defined earlier. In the watch event handler, we ll simply change our uglify task’s source parameter to the file that was updated. So instead of taking all the files defined in the src parameter, Grunt watch will only process the updated file

This will make sure that only the changed file is uglified. Once it compiles it as a minified file, we run concat on the minified files by adding another watch target in the Gruntfile.

This solution helps meet the goal I set out to achieve. Though there is an issue in this. What if we wanted to append .min.js to the end of all the files we minify? We could just add that in the uglify target object as ext: min.js. But then it will create some problems on files that have a dot (or 2) in their ‘name’ itself. For example its a common practice to name jquery plugins like this: jquery.pluginname.js

At the time of this writing, Grunt uglify will not differentiate between files with more than one dot in their name. It will use the first dot that it finds in the file name and consider the rest of the file path as an extension of the file. So let’s say we decide to append a .min.js to our uglified files, our Grunt task will convert both jquery.pluginname.js and jquery.js to jquery.min.js. This is not what we want! There is a bug filed for this and maybe the core team will do something to tackle it, but since one can pass a rename function, they may not consider tackling this right away.

A quick and dirty solution is to explicitly rename the changed files the way you want in the on watch event itself. So you’d first uncomment the ext portion in the uglify task and update the on watch task:

If you know a better way than this, then please do leave it in the comments.


Categories: How To, Javascript | Tags: , , | 1 comment

Twitter Bootstrap Website Starter: Create a mobile friendly, HTML5 responsive website instantly!

One cannot be deeply responsive to the world without being saddened very often.
-Erich Fromm

While creating a small HTML website, I wonder if developers still need to manually put together a bunch of HTML files and wire them up in a navigation menu. I feel the process to put together a barebones HTML5 website should be like a handy Lorem Ipsum text generator. It should let you quickly setup a site based on maybe a settings file that you can edit to suit your website’s structure. Well, I ve just put together something like that and here is how to use it :)

Download or clone the Bootstrap Website Starter from github. If you do not intend to customize it using the built-in python tool, then simply:

  1. copy the contents of the ‘site’ folder to your web server’s public folder
  2. each page is a static HTML page, so you can just go in and populate the page with your content

Here s a demo of what that would look like.

A quick design suggestion I d like to recommend is: head over to Google web fonts and select 2 contrasting fonts (please do not use similar looking fonts – it really does not add any value to your typography). Use one for the header texts and the other for the body text. Since we are using Twitter Bootstrap, you can even change the navigation bar to something else.

Of course, so far we ve only used the ‘site’ folder contents as is. The biggest issue is, what if you wanted more pages than the default number of pages provided? What if you needed to change the name of the Project or the name of the pages themselves? Well, you d need to manually change all that and then you ll have to go to each page to make changes to the navigation menu (and links) as well! Honestly, it wont be so bad to do it manually, but then if you don’t mind using the terminal a little bit, then you could simply use the built-in python tool to structure your site the way you want before you start making any design changes.

Please note: Windows users need to have Python on their machine. For Linux and Mac users, Python in installed by default and you can simply open settings.json from the downloaded starter kit and edit the file to suit your site-structure needs. Here is the default settings.json file (we ll edit this shortly):

In this file, you can have 2 primary settings. One for the project itself (which is self explanatory) and the other is an array for the pages to generate. To add more pages, just copy over one of the ‘page’ objects in the array (do not add a comma at the very end coz Python will not accept it as a valid JSON page) Each ‘page’ object in this array has a ‘title’ and a ‘template’ property. Change the title to whatever you want. For example, if you’d like to call the ‘Contact’ page ‘Get in touch’ then simply change the title for that page object to ‘Get in touch’. The tool will create a file called ‘get-in-touch.html’ and set its title and header text to ‘Get in touch’.

For the template of each page object, you can chose one of the following template types:

  • home.html <- Generates a home page with a slideshow on it
  • page.html <- Generic page
  • gallery.html <- Generates a page with thumbnals
  • contact.html <- Generate a a page with a basic contact form

These are self explanatory for the kind of content they d create. In most cases, you d need to chose ‘page.html’ for a new page. This will create a generic ‘page’ with 2 columns (one with an image and the other with some text). You can even add more template types if you want. Take a look at the HTML inside the templates folder and create another HTML file to create a new template.

Once you re done editing the settings.json file, fire up the terminal and ‘cd’ into the folder you downloaded (or cloned). Run the following command:

A brand new site with your customized settings will get created inside the ‘site’ folder. Copy over its contents to your web server’s public folder and that’s about it!

Here s a demo of what a site thus generated would look like.


Categories: How To, Useful | Tags: , , , | 1 comment

How to layout a BackboneJS project in CakePHP using GruntJS

BackboneJS does not seem to come with a recommended layout for its file structure, though Yeoman suggests it’s own concept of laying out a BackboneJS project. I took inspiration from Yeoman to put together this approach for laying out a BackboneJS project inside the CakePHP framework. CakePHP is convention over configuration and expects you to put all your assets inside cakeroot/app/webroot/.

For the sake of this tutorial, I m going to create my files based on a simple ToDo project since almost every developer creates a ToDo app at least once! The ToDo list app for this project has a database with 3 tables:

Inside webroot/js, create the following directories

Yeoman generates directories for routes, helpers and templates. I m not going to add these coz I dont need them. For routes, I m going to use only one file and it can stay inside the js folder alongside my main.js file. I have a feeling that the convention to use main.js comes from ActionScript 3.0 projects (though I do not have any proof of this)

Once you ve created your directories in the js folder, its time to put in some files. Here is the same directory structure for the js/ directory, but includes files that are based on my database schema.

Yeoman creates the main.js with one global variable based on the name of your project and creates placeholders within that for our models, collections, views and routes. Here s a sample of it:

Now, while defining your models or collections or views, make sure to namespace it inside ProjectName.Models or ProjectName.Collections or ProjectName.Views. For example, our task-model would look like this:

Notice the name of the model. The file was named task-model.js and the model itself is called TaskModel. This is just a convention. You can change this to whatever you think is better for you.

Finally templates, Yeoman does create a structure for that but I figured that out the easy way that it has not yet implemented the feature where you can define .ejs files inside your templates directory and use em from there. At least not as of this post. So instead of trying to do that, we can just define the templates inside a directory inside app/View/Elements/Templates. We can then render that element in Cake’s view file which also has the scripts pulled in for our app. For this tutorial, I have a controller called UsersController.php and I have routed /app to UsersControllers:app

Since that s how the route is defined, we need to have a file at app/View/User/app.ctp. At the beginning of this render the templates file and at the end of the same file, pull in the required JS files.

For now I ll just pull all the required JS files from CakePHP’s perspective (later we’ll use Grunt):

Lets say your application-router.js file looks like this:

Then at the end of all the javascript calls, create script tag and create a router object and kick start the show!

We could even use GruntJS and have all the JavaScript and CSS files uglified or minified into one single app.js and app.css file and just pull that instead. To do so you ll need NodeJS and Node Package Manager installed. If you do have these installed, then create a file called package.json inside cakeroot/app/. I m not using the webroot directory coz I dont want my Gruntfile and package.json file to be publicly accessible. Inside your package.json file you could do something like this:

Then, add n navigate to your app folder in a terminal and run:
npm install

Once the required modules are installed, you can add app/node_modules to your .gitignore file. Then create a file (inside app/) called Gruntfile.js (unless it is not already created) and enter something like this:

I m just using uglify and cssmin along with watch. You can add whatever else you may need. After that you wont need to pull all those JS files in your view file. As you may already know, the browser pulls 2 files at a time from the server. So if you have 16 files (including Javascript as well as CSS), then it ll make 8 trips to the server and back!

Now that we have some grunt tasks running, we can reduce the round trips to the server (and cut file size considerably). Run ‘grunt’ from the ‘app/’ directory in a terminal and marvel at the ‘magic’ from the contributors of Grunt as you make even the tiniest of the changes to the files that are being ‘watched’. These views are just my idea based on how Yeoman lays out a Backbone JS project. If you have some suggestions to improve this, then please do share.


Categories: How To, Javascript | Tags: , , , | 3 comments

Install Apache, MySQL PHP and phpMyAdmin on Ubuntu 13.04 Raring Ringtail

When Thomas Edison worked late into the night on the electric light, he had to do it by a gas LAMP or candle. I’m sure it made the work seem that much more urgent.
-George Carlin

Ubuntu 13.04 ‘Raring Ringtail’ released yesterday and though I use Crunchbang, like any ex Ubuntu fanboy I got myself the iso, put it on a thumbdrive and installed it on a small netbook I have that was just lying around doing nothing fancy. I thought I d install the new Ubuntu on it and use it to ‘code’ while in the John or while standing in the line at Starbucks :D

So anyway, I had to setup a LAMP server:

MySQL

Apache

PHP

Restart Apache

phpMyAdmin

I don’t like to use Apache’s default http folder /var/www so I need to update the apache2.conf file:

Changing the default location will require me to make sure phpMyAdmin continues to load on http://localhost/phpMyAdmin so at the end of the same file I ll add the virtual host configuration for phpMyAdmin

Restart Apache


Categories: How To, Linux, Useful | 27 comments

Rearrange characters of a string to create all possible combinations

Governments tend not to solve problems, only rearrange them
-Ronald Reagan

How to take a word(string) and rearrange its letters to create all possible combinations? Lets say we want to use the word ‘goal’ and list out all possible words that can be made by rearranging the letters of the word ‘goal’. Take the first letter ‘g‘ and then create permutations and combinations of the balance letters ‘oal‘ and append them to ‘g‘.

g oal
ola
alo
aol
loa
lao 

Then take go and create create permutations for the balance letters ’al‘ and append them to ‘go‘.

go al
la

Then we take goa and l

goa l

This is done for each of the letters. As you can see, with each letter, the permutations will reduce for the subsequent letters. The parameters that are passed to our recursive function are a string that will be used to prepend (starting with an empty string) AND the array of the letters of the word that will be looped over to rearrange its words.

At the moment the JavaScript function I ve written tends to have too many iterations to produce the desired result but it works alright. Here’s a demo for this. I ve added 2 helper functions to this function. One to find if an item exists in a given array and another to remove an item from an array by index. I m not using the Array.splice function to remove item by index coz it to alters the array that was passed to it.

Here’s the function in JavaScript:
Here’s the same thing in python:


Categories: How To, Javascript | 1 comment

Create a right click menu for your web application

Taken out of context I must seem so strange.
-Ani DiFranco

Update: I ve converted this into a jquery plugin. You can download/fork it from my gitbhub page.

There is a common issue when crafting out non-trivial web applications, where you may have many different actions for the user to perform and yet you certainly do not want to overwhelm her with a complex UI with icons, menus, floating divs with action buttons in them etc. A simpler way to reduce the UI clutter could be to introduce a contextual menu on right-clicking an element. This is really simple using jQuery. Here s a DEMO for the following snippet. And here’s the demo for the same thing as a jquery plugin.

You could design a UL element the way you want and set

Assuming that we want this context menu to appear on right clicking an image, the sample HTML could be:

Now we simply bind the ‘contextmenu’ event of images to show this context menu.

Basically, we got the X and Y position of the current mouse position and applied it to the context-menu UL element (which has position set to absolute) and prevented the default action from happening. Finally, we need to get rid of this context menu if the user clicks anywhere but the context menu.

We don’t want the menu to hide if the user clicked the menu itself, so we disable the default behavior of the element from propagating the click event way up to the HTML element:

Since we set position: absolute on the context menu, resizing the browser when its open will mess it s position. The probability of the user right clicking the image and then resizing the browser window is low, but just in case she does so, then we can simply hide the menu on resize as well:

So that s about it. Here’s a DEMO for this code. and here s my github repo for it.


Categories: How To, jQuery, Tips | 4 comments

← Older posts