1

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 appears to sometimes work but sometimes indent the the wrong amount, and the alert (which i just put in there for debugging purposes) never fires. Thanks

  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);

}

 $('#trigger').click(function(){
    textIndentFunc();
    alert('fire');
 });

textIndentFunc();

UPDATE - I should have mentioned this code runs on document.ready.

UPDATE - moving the code to window.load doesn't change anything.

Evanss
  • 23,390
  • 94
  • 282
  • 505

5 Answers5

2

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.

Reinstate Monica Cellio
  • 25,975
  • 6
  • 51
  • 67
2

Your function need to be called in document.ready call

$(document).ready(function() {
   textIndentFunc();
});
Josh Mein
  • 28,107
  • 15
  • 76
  • 87
1

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>
0

Do you have another function that also runs on page load? Because if this is the case maybe the 2 functions have a conflict...

Giorgos Manoltzas
  • 1,710
  • 5
  • 24
  • 34
  • Only other function hides the browser chrome: function hideChrome() { setTimeout(function() { window.scrollTo(0, 1) }, 100); } – Evanss May 14 '12 at 16:05
  • Im not sure if moving the code to window.load helped but for some reason when I also changed the order of my other function it fixed this. Thanks – Evanss May 14 '12 at 16:14
0

If you already are calling textIndendFunc in $(document).ready and is still not getting what you're expecting, try moving textIndentFunc to $(window).load.

kei
  • 20,157
  • 2
  • 35
  • 62