Javascript
January 21st 2010 // JavaScript // Permalink
jQuery UI: Add Close button to dynamically added tabs
When working with jQuery UI tabs it is really easy to dynamically add tabs. You just use UI's "add" method as specified in the documentation: .tabs( 'add' , url , label , [index] ). But there is no method for dynamically adding a close button so the tabs can be removed. Here is a quick little script I wrote to do just that.
$(function() {
//DECLARE FUNCTION: removetab
var removetab = function(tabselector, index) {
$(".removetab").click(function(){
$(tabselector).tabs('remove',index);
});
};
//create tabs
$("#tabs").tabs({
add: function(event, ui) {
//select newely opened tab
$(this).tabs('select',ui.index);
//load function to close tab
removetab($(this), ui.index);
},
show: function(event, ui) {
//load function to close selected tabs
removetab($(this), ui.index);
}
});
//load new tab
$(".addtab").click(function(){
var href=$(this).attr("href");
var title=$(this).attr("title");
$("#tabs").tabs( 'add' , href , title+' ');
return false;
});
});
Usage is simple. Just add class ".addtab" to the links you want opened in a tab, and make sure the link has "title" attribute set as it is used for the tab label.
Add Tab
Here is an example:
Etiam aliquet massa et lorem. Mauris dapibus lacus auctor risus. Aenean tempor ullamcorper leo. Vivamus sed magna quis ligula eleifend adipiscing. Duis orci. Aliquam Proin elit arcu, rutrum commodo, vehicula tempus, commodo a, risus. Curabitur nec arcu. Donec sollicitudin mi sit amet mauris. Nam elementum quam ullamcorper ante.sodales tortor vitae ipsum. Aliquam nulla. Duis aliquam molestie erat. Ut et mauris vel pede varius sollicitudin. Sed ut dolor nec orci tincidunt interdum. Phasellus ipsum. Nunc tristique tempus lectus.
Improvements
To avoid adding of duplicate tabs. a function should be added that checks if a specific tab was already added. It should be easy to do. I'll just need to find time to do it.
Update: 02/26/2010
If you don't want to use jQuery UI, but would like to achieve similar effect, visit JankoAtWarpSpeed.com.
Do you like this or find it useful? Drop me a note or treat me to a double-espresso from my favorite coffee shop.
December 3rd 2009 // JavaScript // Permalink
Progressive Enhancement: Anchor Links to Side Tabs
Here is an example of progressive enhancement technique using jQuery to turn anchor links into side tabs.

Anchor Links Example
Assumption here is that the links are inside an unordered list with ID "services" services assigned to it.
- Donec arcu est
- Sed at sem lacus
- Proin non turpis urna
- Vestibulum non ipsum orci
- Nullam cursus ullamcorper
- Lorem ipsum dolor sit amet
Named anchord are inside a div element with class "item" assigned to it.
....text........text........text........text........text........text....
jQuery code
Here is a summary of what jQuery will do to the DOM:
- Append styles
- Add wrapper div and place all items inside it
- Highlight and show the first item
- Add click event to handle navigation from item to item
See comments below for more details.
$(document).ready(function(){
//page settings
var navcontainer = "#services"; //Add to the UL conaining the links
var itemcontainer = ".item"; //Add to the DIV around each section
var itemwrap = "item_wrap"; //A DIV element with this ID will be wrapped around all items
var selecteditem = "selecteditem"; //class assigned to the currently selected link
/*****STYLES BLOCK*****/
// Styles can also be defined in a separate CSS file. if you do so comment out or delete styles block
var styles = '<style>'+
'#'+itemwrap+' {background: #e8e8e8; padding: 10px 15px 15px 15px; float: left; width: 400px; }'+
navcontainer+' {float:left;font-size:12px;margin:10px 0 0;padding:0;width:250px;list-style: none;}'+
navcontainer+' li{border-bottom:1px solid #E8E8E8;}'+
navcontainer+' li a{display:block; color:#3333CC; text-decoration:none;line-height:12px;padding:8px 0px 8px 10px;outline:0;}'+
navcontainer+' .'+selecteditem+'{background: #e8e8e8;}'+
'</style>';
//add styles to the head
$("head").append(styles);
/*****END STYLES BLOCK*****/
//create item_wrap div
$(itemcontainer+":first").before('<div id="'+itemwrap+'"> </div>');
//add items to wrap
$(itemcontainer).appendTo("#"+itemwrap);
//show only first item
$(itemcontainer).not(":first").hide();
//mark first link as selected
$(navcontainer+" li:first").addClass(selecteditem);
//services click
$(navcontainer+" a").click(function(){
$(navcontainer+" li").removeClass(selecteditem);
$(this).parent("li").addClass(selecteditem);
var li_index = $(navcontainer+" a").index(this);
$(itemcontainer).hide().eq(li_index).slideToggle("fast");
return false;
});
});
Here is an example.
Do you like this or find it useful? Drop me a note or treat me to a double-espresso from my favorite coffee shop.
Comments
No Comments
November 25th 2009 // JavaScript // Permalink
Progressive enhancement: Accordion Style FAQ's with jQuery
Condense a lengthy FAQ page with accordion style navigation, making your answers only appear when the questions of interest are clicked.
To use it:
- Add this script to the FAQ page
- Assign class "question" to every question
- Assign class "answer" to every answer
$(document).ready(function(){
//just some regular style sheets. change them as you see fit
var styling =".question{font-size:14px; font-weight:bold; cursor:pointer;}" +
".answer{display:block;}" +
".opened{color:#006699;}" +
".closed{color:#009966;}";
//attach style to the page
var style = document.createElement("style");
style.type = "text/css";
try {
style.appendChild( document.createTextNode(styling) );
} catch (e) {
if ( style.styleSheet ) {
style.styleSheet.cssText = styling;
}
}
document.body.appendChild( style );
//style all questions as closed
$(".question").addClass("closed");
//make sure first question is styled as open
$(".question:first").removeClass("closed").addClass("opened");
$(".answer").hide(); //hide answers
$(".answer:first").show(); //show first answer
//question click
$(".question").click(function() {
$(".answer").slideUp("fast");
$(".question").removeClass("opened").addClass("closed");
if ($(this).next(".answer").is(":hidden")) {
$(this).next(".answer").slideDown("fast");
$(this).removeClass("closed").addClass("opened");
}
});
});
Example HTML
Lorem ipsum dolor sit amet, consectetur adipiscing elit?
Ed ligula libero, dictum at dapibus non, egestas a massa. Cras sit amet dolor felis. Morbi gravida vulputate condimentum. Nam ut nisl nibh.
Nulla a placerat leo. Proin ut hendrerit tellus?
Sed consequat turpis ac justo tristique elementum. Maecenas vitae mi dui. Maecenas nulla ligula, condimentum vitae posuere nec, fringilla eu sapien.
Donec faucibus tristique quam ac eleifend?
Nullam malesuada malesuada tempus. Phasellus posuere imperdiet dignissim. Nam id arcu erat, vel volutpat est. Maecenas ullamcorper interdum lacus vel tincidunt. Quisque egestas turpis et orci rhoncus posuere. Integer vehicula gravida interdum.
Working Example
Lorem ipsum dolor sit amet, consectetur adipiscing elit?
Ed ligula libero, dictum at dapibus non, egestas a massa. Cras sit amet dolor felis. Morbi gravida vulputate condimentum. Nam ut nisl nibh.
Nulla a placerat leo. Proin ut hendrerit tellus?
Sed consequat turpis ac justo tristique elementum. Maecenas vitae mi dui. Maecenas nulla ligula, condimentum vitae posuere nec, fringilla eu sapien.
Donec faucibus tristique quam ac eleifend?
Nullam malesuada malesuada tempus. Phasellus posuere imperdiet dignissim. Nam id arcu erat, vel volutpat est. Maecenas ullamcorper interdum lacus vel tincidunt. Quisque egestas turpis et orci rhoncus posuere. Integer vehicula gravida interdum.
Do you like this or find this useful? Drop me a note or treat me to a double-espresso from my favorite coffee shop.
Comments
December 8th 2009
wow! - This works like magic! Thank you so much!! Just treated you to an expresso. ;)
Emir - I love when I get treated to a coffee on a Tuesday (double-punch day). Thanks!!!
November 23rd 2009 // JavaScript // Permalink
jQuery UI: Highlight multiple dates in jQuery datepicker
The events are stored as UNIX timestamps in a MySQL table. We'll be getting those events from the database via AJAX and highlight them in the jQuery UI datepicker widget.
HTML
Javascript
$.ajax({
url: "dates.php",
data: "action=showdates&id=1",
dataType: "json",
success: function(calendarEvents){
$(".calendarwidget'").datepicker({
// [rows, columns] if you want to display multiple calendars.
numberOfMonths: [1, 1],
showCurrentAtPos: 0,
beforeShowDay: function (date){
for (i = 0; i < calendarEvents.length; i++) {
if (date.getMonth() == calendarEvents[i][0] - 1
&& date.getDate() == calendarEvents[i][1]
&& date.getFullYear() == calendarEvents[i][2]) {
//[disable/enable, class for styling appearance, tool tip]
return [false,"ui-state-active","Event Name"];
}
}
return [true, ""];//enable all other days
}
});
}
});
PHP
Here is our AJAX service. Assumption here is that we are getting the date from a UNIX timestamp stored in a MySQL table.
$action = $_REQUEST['action'];
$id = $_REQUEST['id'];
switch ($action){
case 'showdates':
$qry = "SELECT * FROM event_table WHERE eventid = '".$id."'";
$result = mysql_query($qry) or die ("Error in query: $qry. " . mysql_error());
echo '[';
do{
if($row->eventid != ''){//makes sure no blanks are returned
//this assumes that "eventdate" is UNIX timestamp
$converteddate = date("m,d,Y",$row->eventdate);
$dates .= '['.$converteddate.'],';
}
}while($row = mysql_fetch_object($result));
$dates =rtrim($dates, ",");
echo $dates;
echo ']';
break;
}
Resources
jQuery UI datepickerhttp://jqueryui.com/demos/datepicker/
jQuery AJAX
http://docs.jquery.com/Ajax
PHP Date Manual
http://php.net/manual/en/function.date.php
Do you like this or find it useful? Drop me a note or treat me to a double-espresso from my favorite coffee shop.
Comments
January 27th 2010
nurion - Thanks! You pointed the right direction for me and saved my head from being achy ;)
November 17th 2009 // JavaScript // Permalink
Progressive enhancement: AJAX navigation menu with jQuery
Progressive enhancement allows everyone to access the basic content and functionality of a given web site using any browser or Internet connection, while also providing those with a more advanced browsers an enhanced version of the site.
Here is an example on how to enhance a starndard navigation bar with AJAX.
Scenario

Let's assume that #header, #navigation and #footer are same on every page and #mainconent, and #sidebar inside the #content are changing on every page.
Problem
The site will have a music player that clients can choose to use while browsing the site. And if they do, we don't want the music to be interupted as they move from page to page.
Solution
Use unobtrusive javascript and AJAX to load content and update the URL using hash in case someone wants to bookmark loaded content.
sdf
Javascript/jQuery
We'll use jQuery to bind a click event to the navigation links and use load function to load contents of the clicked page.
Html navigation
Javascript
//FIRST: We'll check if the URL has a hash (was bookmarked) and redirect the user to appropriate page
if(window.location.hash!=""){
var hashpage = window.location.hash.split("#");
window.location.pathname = hashpage[1];
}
jQuery
//bind click event to the navigation links
$("#navigation a").unbind("click").click(function(){
//get href attribute
var page = $(this).attr("href");
//load all children of the #content div of the clicked page
$("#content").load(page+" #content > *");
//append hash to the url for bookmarking
window.location.hash="#"+page;
//cancel browser default so the page doesn't reload
return false;
});
Putting it all together
$(document).ready(function(){
if(window.location.hash!=""){
var hashpage = window.location.hash.split("#");
window.location.pathname = hashpage[1];
}
//navigation
$("#navigation a").unbind("click").click(function(){
//get href attribute
var page = $(this).attr("href");
//load contents of all children of the #content div
$("#content").load(page+" #content > *");
//append hash to the url for bookmarking
window.location.hash="#"+page;
//cancel browser default so the page doesn't reload
return false;
});
});
Do you like this or find it useful? Drop me a note or treat me to a double-espresso from my favorite coffee shop.
Comments
December 12th 2009
Jay - Great tutorial. I had this idea a while back while using Facebook, but I never got around to coding it. (I'm a bit of a procrastinator :P)
November 17th 2009 // JavaScript // Permalink
Create simple cross-browser textarea editor
This tutorial will help you create simple cross-browser textarea editor you can use on any of your HTML forms. View the sample.
The main DHTML methods used in this cross-browser textarea editor are:
- execCommand.
This method executes a command on the current document, current selection, or the given range. - getElementById
Returns a reference to the first object with the specified value of the ID attribute.
Commands used to specify an action to take on the given object:
- Bold
Toggles the current selection between bold and nonbold. - Underline
Toggles the current selection between underlined and not underlined. - Italic
Toggles the current selection between italic and nonitalic. - JustifyCenter
Centers the format block in which the current selection is located. - JustifyLeft
Left-justifies the format block in which the current selection is located. - JustifyRight
Right-justifies the format block in which the current selection is located. - Indent
Increases the indent of the selected text by one indentation increment. - Outdent
Decreases by one increment the indentation of the format block in which the current selection is located. - Undo
Undo the step - Redo
Redo the step
Main DHTML properties used:
- innerHTML
Sets or retrieves the HTML between the start and end tags of the object. - designMode
Sets or retrieves a value that indicates whether the document can be edited.
Download the button images here.
CSS File
.editorbuttons {
list-style: none;
margin: 0px;
padding: 0px;
}
.editorbuttons li {
float: left;
}
.editorbuttons li img {
border:none;
}
.editorbody{clear:both; float:none;}
HTML File
JavaScript File
See comments for details
//First initiate some variables
var isEditable= false;
var isIE;
var isGecko;
var isSafari;
var isKonqueror;
var browser = navigator.userAgent.toLowerCase();
function initiateEditor() {
//check what browser is in use
isIE = ((browser.indexOf("msie") != -1) && (browser.indexOf("opera") == -1) && (browser.indexOf("webtv") == -1));
isGecko = (browser.indexOf("gecko") != -1);
isSafari = (browser.indexOf("safari") != -1);
isKonqueror = (browser.indexOf("konqueror") != -1);
//enable designMode if the browser is not safari or konqueror.
if (document.getElementById && document.designMode && !isSafari && !isKonqueror) {
isEditable= true;
}
}
//Javascript function dislpayEditor will create the textarea.
function displayEditor(editor, html, width, height) {
if(isEditable){
document.writeln('');
//create a hidden field that will hold everything that is typed in the textarea
document.writeln('');
//assign html (textarea value) to hiddeneditor
document.getElementById('hidden' + editor).value = html;
//call function designer
designer(editor, html);
}else{
document.writeln('< textarea name="' + editor + '" id="' + editor + '" cols="39" rows="10">' + html + '');
}
}
//this is designer function that enables designMode and writes defalut text to the text area
function designer(editor, html) {
var mainContent= "< html id=" + editor + ">< head >< /head >< body >" + html + "< /body >" ;
//assign the frame(textarea) to the edit variable using that frames id
var edit = document.getElementById(editor).contentWindow.document;
//write the content to the textarea
edit.write(mainContent);
edit.close();
//enable the designMode
edit.designMode = "On" ;
document.getElementById(editor).contentDocument.designMode = "on";
}
//To execute command we will use javascript function editorCommand.
function editorCommand(editor, command, option) {
// first we assign the content of the textarea to the variable mainField
var mainField;
mainField = document.getElementById(editor).contentWindow;
// then we will use execCommand to execute the option on the textarea making sure the textarea stays in focus
try {
mainField.focus();
mainField.document.execCommand(command, false, option);
mainField.focus();
} catch (e) { }
}
function updateEditor(editor) {
if (!isEditable) return;
//assign the value of the textarea to the hidden field.
var hiddenField = document.getElementById('hidden' + editor);
if (hiddenField.value == null) hiddenField.value = "";
hiddenField.value = document.getElementById(editor).contentWindow.document.body.innerHTML;
}
PHP File
Most important part of the PHP code is the phpSafe function. This function makes sure that quotes are displayed appropriatly. See comments for details.
// from the form we are getting the hidden field value and sending it to the phpSafe function
$hiddencontent = phpSafe($_REQUEST['hiddencontent']);
function phpSafe($strText) {
//removes backslash created by php from the string
$tmpString = $strText;
$tmpString = str_replace(chr(92), "", $tmpString);
return $tmpString;
}
echo $hiddencontent;
Save all files in the same folder and upload to your server. Play with the code and try adding more functionality or buttons. Here are some helpfull resources:
Do you like this or find it useful? Drop me a note or treat me to a double-espresso from my favorite coffee shop.
Comments
January 26th 2010
El Oscuro - Fantastic post! Please, change 'name' options to 'id' inside the article - getElementById fails otherwise. Demo works fine.
November 15th 2009 // JavaScript // Permalink
Create a Scrolling Text Box using JavaScript
This can be easily done using jQuery or similar JavaScript libraries. But sometimes you may choose not to load the whole library for a simple task like scrolling text.
Javascript scrolling text function
Create a javascript function and place it either inside the element using < script > tag, or inside a separate javascript file.
//Define a variable (pos) to store the current scroll position.
var pos = 100;
function Scroll(){
//get the id of the scrolling text box.
obj=document.getElementById('scrolltextlayer');
//subtract 1 from pos and check pos value using offsetHeight, which retrieves the height of the object relative to the layout.
pos -=1;
if(pos < 0 - obj.offsetHeight+130) return;
//set a new height value using JavaScript style object.
obj.style.top=pos;
//finally the function calls itself using a timeout..
window.setTimeout( "Scroll();" , 30);
}
HTML
HTML is pretty simple:
- Create outer div that will act as a "frame"
- Create inner (scrolling) div
OUTER DIVINNER DIVEND OUTER DIVEND INNER DIVLorem ipsum dolor sit amet, consectetuer adipiscing elit. Cras hendrerit mauris eget nunc. Proin dapibus eros in quam. Nunc nulla nunc, nonummy auctor, scelerisque non, cursus et, leo.
Nullam egestas nulla feugiat orci. Integer lorem sapien, ullamcorper dapibus, cursus eu, sagittis vel, dolor. Mauris tincidunt, magna in congue bibendum, sem quam tincidunt tortor, in consectetuer turpis odio a libero.
Link to scroll again
Implementation
Just call the function from "onload" attribute inside the tag.
< body onLoad="Scroll();">
Do you like this or find it useful? Drop me a note or treat me to a double-espresso from my favorite coffee shop.
Comments
February 6th 2010
Mainuddin - I want to continue the scrolling instead of stopping after once. Please give me the suggestions.
Mainuddin - I want to continue the scrolling instead of stopping after once. Please give me the suggestions.
November 9th 2009 // JavaScript // Permalink
Dynamicaly generate a Web Safe Color palette with JavaScript
Generating web safe color palette can be easily done using JavaScript. Web safe palette contains 256 colors that we can come up with by mixing some basic colors.
Here is the code
//first lets start with the table that will contain the palette t='
| #'+l+' | '; } t +='
That's it. Pretty simple!
Here is the example
Do you like this or find it useful? Drop me a note or treat me to a double-espresso from my favorite coffee shop.
Comments
No Comments
November 9th 2009 // JavaScript // Permalink
Javascript location Object explained
Javascript scripts can manipulate the Web pages and it's contents using a hierarchy of parent and child objects called the DOM (Document Object Model). Those objects are organized into a tree-like structure and represent all of the components of a web page. Objects in the DOM have properties, which describe the Web page, and methods, which allow you to work with parts of the Web page.The window object is the parent object for all the objects. One of the objects under window is the location object.
Location Object
Location object stores information about the current URL in the window. For example this statement loads emirplicanic.com website in the current browser window.
window.location.href = "http://www.emirplicanic.com";
The href property contains the entire URL, but you can use various properties to access portions of the URL.
Properties
Let's take following URL apart: http://www.emirplicanic.com:80/55.php?id=12#headline
- location.protocol would give us the protocol part of the URL (http: )
- location.hostname would give us host name of the URL (i.e. www.emirplicanic.com)
- location.port would give us the port number of the URL (80)
- location.pathname would give us the filename part of the URL (55.php)
- location.search would give us the query part (if any) of the URL (id=12)
- location.hash would give us the anchor name used in the URL (#headline)
Methods
The location object has two methods:
location.reload()- reloads the current page. It acts the same as the browser reload button. You can include a parameter true to ignore the browser's cache and force a reload whether the document has changed or not.
location.replace()- replaces the current location with a new one. It's pretty much the same as changing the location properties, except that it doesn't affect the browser's history. So, if you use replace method you can't use browser's back button to go to previous location. This is mostly used for temporary pages or splash screens.
Example
Let's say you are using an AJAX script to load a page based on the search query in the URL. You could create a function:
function getSearch()
{
return document.location.search;
}
or just use document.location.search somewhere within the function that handles AJAX calls.
If you want to pass a url to the getSearch function modify the code like this:
function getSearch(url)
{
return url.location.search;
}
and call it like this:
Pass a URLThere you have it a quick overview of the DOM's location object.

Comments
February 26th 2010
Srinivas - Hi, The above code is not working for me.. Of course, I executed http://www.jankoatwarpspeed.com/post/2010/01/26/dynamic-tabs-jquery.aspx this. If i uses ur code it is redirecting instead of showing webpage in particular Panel. And I want this Operation In frames.I.e If i click on the link in the left Frame i want to show tabs in Right Frame... Please Help Me . If U have a Sample, Then Please Provide Me... Regards, Srinivas I Sr. Developer
Reply
March 6th 2010
john - have u figured out how to avoid adding duplicate tabs??
Reply
March 6th 2010
naxim - u can fix it by modifying ".addtab" function as follows... $(".addtab").click(function(){ var href=$(this).attr("href"); var title=$(this).attr("title"); var tabID=$(this).attr("id"); // check whether the tab already exists if($("span[id^=span-"+ tabID +"]").length > 0) { //tab is already loaded so find the href of the tab and load var addedTab = $("span[id^=span-"+ tabID +"]").parent().parent(); var addedTabHref = $(addedTab).attr("href"); $("#tabs").tabs('select', addedTabHref); } else { //tab not loaded so add a new one $("#tabs").tabs("add", href + '?' + tabID,title+' '); } return false; });
Emir - Thanks. I'll add your code to the post. Also, try latest jQ UI as it includes an example off dynamic tabs.
Reply