Reputation: 1540
I have a php file with this jQuery function working properly (basically it identifies every '.limitCharacters'
elements, calculates its width and height and makes some 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 I try to move it to my separate .js file (which has already many functions inside being called from this php file, and works properfly), in order to call it from my php file whenever I need it, it does not work. This is how I've created it on my 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 this is the way I call it from my 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 it is the same, just that in the second case I pass variables to my .js separate file and it should react the same. What am I missing?
Upvotes: 0
Views: 96
Reputation: 133403
Your problem is $(this)
, In your original code $(this)
refers to the element .limitCharacters
, As you have separated the function to separate JS file you have to pass the reference of $(this)
to your function
Try this, Here I 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 this
})
Upvotes: 3