0

I have a mysterious JS Problem: I activate different jQuery-Plugins with one function. It's called like this:

<script>
postAjaxCalls();
</script>

Then, the corresponding function looks like this:

function postAjaxCalls() {
    jQuery("[title]").tooltip(); 
    alert("this works great, tooltip not!");
    jQuery("select").selectbox();
} 

When I reload the page, everything works but the tooltip plugin. Now, if I fire the exact same Code into the JS Console, the plugin is activated:

jQuery("[title]").tooltip(); 

Why that? Why does it work when activated via console, but doesn't work when activated via a function?

Cheers!

gen_Eric
  • 223,194
  • 41
  • 299
  • 337
cukabeka
  • 530
  • 2
  • 9
  • 22

2 Answers2

3

Try your code within $(document).ready(function() { .. }) in short $(function() { .. }) to execute your code after DOM ready.

jQuery(document).ready(function() {

  function postAjaxCalls() {
    jQuery("[title]").tooltip(); 
    alert("this works great, tooltip not!");
    jQuery("select").selectbox();
  } 
  postAjaxCalls();

});

OR in short

jQuery(function() {

  function postAjaxCalls() {
    jQuery("[title]").tooltip(); 
    alert("this works great, tooltip not!");
    jQuery("select").selectbox();
  } 
  postAjaxCalls();

});
thecodeparadox
  • 86,271
  • 21
  • 138
  • 164
  • that's paradox: I got that problem with another project as well. I use your advice (jQuery(function() {..})), but it still doesnt work until I execute $('.datepicker').datepicker(); in console!? – cukabeka Sep 21 '12 at 17:06
0

You are probably calling postAjaxCalls before the DOM is ready. When you call it from the console, the DOM is ready, so it works.

Try this:

$(function(){
    postAjaxCalls();
});
gen_Eric
  • 223,194
  • 41
  • 299
  • 337