Calculate text dynamic width Javascript

Hello, can someone show me how to change this into javascript to bubble element function. so I can use the published value to set dynamic margin for group focus targeting div inside of html element.

<script $.fn.textWidth = function(text, font) { if (!$.fn.textWidth.fakeEl) $.fn.textWidth.fakeEl = $('').hide().appendTo(document.body); $.fn.textWidth.fakeEl.text(text || this.val() || this.text()).css('font', font || this.css('font')); return $.fn.textWidth.fakeEl.width(); }; $('#inpt').on('input', function() { $('#'+this.id+'-width').html($(this).textWidth() + 'px'); }).trigger('input');

image
image

Well, it looks like it might be like the below, but don’t quote me on this!
Where are you getting it from anyway? Have you pulled out the console or something?
It doesn’t look like it’s complete as you’re missing the end < /script> tag.

$.fn.textWidth = function (text, font) {

	if (!$.fn.textWidth.fakeEl) {
		$.fn.textWidth.fakeEl = $('').hide().appendTo(document.body);
	}

	$.fn.textWidth.fakeEl.text(text || this.val() || this.text()).css('font', font || this.css('font'));
	return $.fn.textWidth.fakeEl.width();
};

$('#inpt').on('input', function () {
	$('#' + this.id + '-width').html($(this).textWidth() + 'px');
}).trigger('input');

Untested!

I found it on stackoverflow. it does work (look at the app) it’s missing script tag because discourse think im trying to make code injection. There are much better ways to prevent that… oh well.

edit: I need to use bubble_fn_functionname to use the value elsewhere. right?

In your script, you need to insert a command with this syntax: “bubble_fn_suffix( value goes here );” in order to pass the value back to a JavascripttoBubble element. In order for this to work, you also have to have “Publish value” checked for the JavascripttoBubble element.

In your case, you have:

JavascripttoBubble Element A
bubble_fn_suffix: textWidth
Publish value?: checked

Try inserting this line:

bubble_fn_textWidth($.fn.textWidth.fakeEl.width());

In your code right before this line:

return $.fn.textWidth.fakeEl.width();

I do not know JS, but if that doesn’t work, others on this forum may be able to help fix the JS for the ( value goes here ) part

Cheers but Its not working

What about using canvas
https://www.w3schools.com/Tags/canvas_measuretext.asp

Thanks but problem is still not sure how to get the value into bubble_fn

@Taiheta i nearly have it, use this expression, check app updated.

86 + $.fn.textWidth.fakeEl.width();
Just need to figure out how to update the value when the text changes.

2 Likes

This topic was automatically closed after 70 days. New replies are no longer allowed.