I am using the below code to display a text in a text field which dissappears when you focus on it:
$(document).ready(function(){
$('.onfocus_rem_txt').each(function(){
$(this).val($(this).attr('defaultVal'));
$(this).css({color:'grey'});
});
$('.onfocus_rem_txt').focus(function(){
if ($(this).val() == $(this).attr('defaultVal')){
$(this).val('');
$(this).css({color:'black'});
}
});
$('.onfocus_rem_txt').blur(function(){
if ($(this).val() == ''){
$(this).val($(this).attr('defaultVal'));
$(this).css({color:'grey'});
}
});
});
How can I use .delegate in order to use it in every new.php p开发者_StackOverflow社区age that I open???
you can delegate the .focus
and .blur
events like so, shouldn't need to iterate with .each
, just pre-apply the value and text color when you create the input
element
example: http://jsfiddle.net/pxfunc/fLnjX/
var $container = $('#container');
$container.delegate('.onfocus_rem_txt', {
'focus': function() {
var $that = $(this);
if ($that.val() === $that.attr('defaultVal')) {
$that.val('').css('color', 'black');
}
},
'blur': function() {
var $that = $(this);
if ($that.val() === '') {
$that.val($that.attr('defaultVal')).css('color', 'grey');
}
}
});
You can use live in order to use this functionality at multiple places
$(document).ready(function(){
$('.onfocus_rem_txt').each(function(){
$(this).val($(this).attr('defaultVal'));
$(this).css({color:'grey'});
}).live({
'focus': function(){
if ($(this).val() == $(this).attr('defaultVal')){
$(this).val('');
$(this).css({color:'black'});
},
'blur': function(){
if ($(this).val() == ''){
$(this).val($(this).attr('defaultVal'));
$(this).css({color:'grey'});
}
});
});
精彩评论