javascript - jQuery function not working when placed on .js separate file -
i have php file jquery function working properly (basically identifies every '.limitcharacters'
elements, calculates width , height , makes stuff on them):
$('.tablecontent').find('.limitcharacters').each(function(){ var percent = ((($(this).width()) / ( $(this).closest('div').width()))*100); if (percent > 95 || $(this).height() > 40){ $(this).css('white-space','nowrap').css('color','red'); $(this).parent().css('width', '85%').css('display','inline-block').css('overflow','hidden'); $(this).parents().eq(1).css('height','36px'); } })
but when try move separate .js file (which has many functions inside being called php file, , works properfly), in order call php file whenever need it, not work. how i've created on separate .js file:
function limitcharacterswidth(actualwidth, actualheight, maxspace, newspace){ if (actualwidth > maxspace || actualheight > 40){ $(this).css('white-space','nowrap').css('color', 'red'); $(this).parent().css('width', newspace).css('display','inline-block').css('overflow','hidden'); $(this).parents().eq(1).css('height','36px');}}
and way call php file:
$('.tablecontent').find('.limitcharacters').each(function(){ var actualwidth = ((($(this).width()) / ( $(this).closest('div').width()))*100); var height = $(this).height(); limitcharacterswidth(actualwidth,height,'90','80'); })
theorically same, in second case pass variables .js separate file , should react same. missing?
your problem $(this)
, in original code $(this)
refers element .limitcharacters
, have separated function separate js file have pass reference of $(this)
function
try this, here have added new parameter obj
function limitcharacterswidth(obj, actualwidth, actualheight, maxspace, newspace){ if (actualwidth > maxspace || actualheight > 40){ $(obj).css('white-space','nowrap').css('color', 'red'); $(obj).parent().css('width', newspace).css('display','inline-block').css('overflow','hidden'); $(obj).parents().eq(1).css('height','36px');}}
usage
$('.tablecontent').find('.limitcharacters').each(function(){ var actualwidth = ((($(this).width()) / ( $(this).closest('div').width()))*100); var height = $(this).height(); limitcharacterswidth(this, actualwidth,height,'90','80'); //passed })
Comments
Post a Comment