Search code examples
jquerywindow-load

jQuery code that manipulates DOM on window.load doesn't always run


I need to center text in a select list. There is no cross browser and device method using CSS only, so ive used JavaScript to set a text indent.

The code takes the text from the select list, adds it to a span (which with css makes the text the same size), and measures the width of the span. With that value it takes some simple maths to work out what the text indent needs to be.

$(window).load(function() {
  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); 
}
$('#from-1 select').change(function() {
    textIndentFunc();
});
textIndentFunc();
});

Most of the time this code works fine but sometimes doesn't appear to do anything, in which case refreshing the page normally fixes it. Why is this code being so temperamental? Is it to do with having to manipulation the dom?

Thanks


Solution

  • Do $(document).ready() not $(window).load()

    When invoking $(document).ready() your function is called once the DOM is processed and ready to be manipulated while load() will callback once all the assets are loaded(images, sounds).