I have a php template. lets call it buildElement.php
. This element is called many times in many places in my application.
What I need to do is attach js function to the creation of the element.
Lets say that buildElement.php
creates some nested div's and one of them has the class name veryImportantClass
I also have a js file which is imported in the project (script src...you know it) and in this file I am trying to resize the font of the veryImportantClass
in function called autoResizeText
My problem is that this function autoResizeText
wont execute on creation of a new element.
I am not sure on what pages use that veryImportantClass
but when its loaded I wanna know and I wanna attach my js function to it.
So far I have $(document).ready() which executes the js when the page loads but if something is created dynamically without refresh I wont catch it.
Is there jQuery event I could use?
[EDIT] I cant post the whole php template as it has custom classes and variables which I cant begin to explain from where they come but here is an example of the final result in the browser with no variables
<div class='container>
<a href="{somewhere}">
<span class="veryImportantClass>Some text</span>
</a>
</div>
Here is what my js function tries to do
function resizeElement (element) {
let elementText = $(element).text();
elementText = elementText.trim();
if (elementText.length > 13) {
element = $(element).css('font-size', '10px');
}
return element;
}
It checks how many symbols are in the text and if there are too many it lowers the font-size.
I have also created another function that checks every current span and calls this one
function autoResizeText() {
console.log('I am resizing the text');
let elements = $('.veryImportantClass');
let result = [];
for (let i = 0; i < elements.length; i++) {
let element = elements[i];
element = resizeElement(element);
result.push(element);
}
return result;
}
So far this is how I make them work
$(document).ready(autoResizeText());
What I want is either to be capable to attach resizeElement
to every span
with class veryImportantClass
or when a span with this element is created I want to call autoResizeText()
which will take all current spans with that class and do the work.