I have the following function that I want to run on page load and re-run when you click div#trigger. When you click div#trigger everything is fine. However on page load the code
Your function need to be called in document.ready call
$(document).ready(function() {
textIndentFunc();
});
Wrap the function call in a document.ready handler like this...
$(function() {
textIndentFunc();
});
That makes sure that the DOM is loaded before trying to do anything to manipulate it, otherwise you'll get different results at different times, depending on what's loaded and what's not.
Try as below
$(document).ready(function () {
$('#trigger').click(function(){
textIndentFunc();
alert('fire');
});
});
function textIndentFunc () {
textString = $('#from-1 :selected').text();
$('#hidden').text(textString);
textWidth = $('#hidden').width();
inputWidth = $('#from-1 select').width();
indentMy = (inputWidth / 2) - (textWidth / 2);
$('#from-1').css('text-indent',indentMy);
}
textIndentFunc();
<div id="trigger">Hai</div>
If you already are calling textIndendFunc
in $(document).ready
and is still not getting what you're expecting, try moving textIndentFunc
to $(window).load
.
Do you have another function that also runs on page load? Because if this is the case maybe the 2 functions have a conflict...