Jquery live, make your html “go live”

21 Jun

Jquery .live()

Description: Attach a handler to the event for all elements which match the current selector, now and in the future.

I want to show you how to make the default input value, adding the dom elements and using jquery live function, all blended together. Click add button to add more input value with default value included. Default text will disapper if focus in and reappear if focus out.

First, create the html


<div id="contentPan">
Hardcopy: <br>
<input name="hardcopy[]" size="50" type="text" value="Default text">
<a href="#" id="button-add-hardcopy">
<img src="add.png" border="0">
</a> <br>
<div id="add-hardcopy"></div>
</div>

Link your jquery and css files


<link href="div.css" rel="stylesheet" type="text/css">
<script src="jquery-1.6.1.js" type="text/javascript"></script>

Then, create the jquery code


<script type="text/javascript">
// Var
base_img = '';

$(document).ready(function(){

// Default input value
$('.hardcopy').live('focusin',
function() {
if ($(this).val() == 'Default text') {
$(this).val('');
}
}
);
$('.hardcopy').live('focusout',
function() {
if ($(this).val() == '') {
$(this).val('Default text');
}
}
);

// Html dom added
$("#button-add-hardcopy").click(function() {
var defVal    = $(this).prev('input.hardcopy').val();
var input     = '<span style="display:none"><input value="'+defVal+'" type="text" name="hardcopy[]" size="50" /> <a href="#"><img border="0" src="'+base_img+'delete.png" /></a></span>';

$("#add-hardcopy").append(input);
$(".span-add-hardcopy").slideDown("fast");

//bind element with event function
$(".button-delete-hardcopy").click(function() {
$(this).parent().slideUp("fast");
$(this).parent().empty().fadeOut('slow', function() {
$(this).remove();
})
});
});
});
</script>

And the last, create the css file


input{
background: url("input_background.png") repeat-x scroll left top #FFFFFF;
border: 1px solid #CCCCCC;
border-radius: 3px 3px 3px 3px;
font-family: Arial;
font-size: 11px;
padding: 3px;
}

.span-add-hardcopy {
margin-top: 5px;
}

#contentPan{
position: relative;
width: 400px;
background-color: #ccc;
padding: 20px;
}

Browser compatibility check including:

  • firefox 4.0.1
  • safari 5.0.2
  • chrome 12.0.742.100
  • ie 9

Full example can be download here.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: