1

I am starting in web desing, and I have a problem with a javascript function in external file: My function javascript is like this:

function log()
{
    alert("something"); 
    $('#content').load('mod/lo.php');   
}

And I call this function in html like this:

<script>log()</script>

and the script only shows the alert, the function load is ignored. But if I call the function like this:

<script>$(log);</script>

It works fine, the alert is showed and the load works.

What's the difference of these forms of calls? I have search about this, but almost all the pages say that to call a function only put <script>function();</script> Can anyone explain me the diferrence of this forms of call? there are problem when parameters are used? Thanks and sorry for my bad English.

1
  • What is the output in console? Commented Jun 8, 2015 at 15:49

2 Answers 2

8

$ syntax is a jQuery shorthand, what it actually means is call this function when the document has loaded. It's exactly the same as writing:

$(document).ready(function() {
   alert("something"); 
   $('#content').load('mod/lo.php');   
});

This probably indicates that the DOM item with the ID content doesn't yet exist when the script executes. The affect of this is the jQuery selector $('#content') will return 0, which prevents load() ever being called. Once the document has fully loaded however it will be present and your load() will execute.

Sign up to request clarification or add additional context in comments.

2 Comments

Oohh!! Thanks for the answer, now I understand it.
@DanteLR great, if you feel like it answered your question please feel free to accept it as the answer :)
1

The difference is, when you call <script>$(log);</script> you're actually calling $(document).ready(log() {}); and Jquery executes its code. In the case of <script>log()</script> the page isn't already loaded and doesn't execute the jquery code.

Check this page

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.