Artisan
Artisan

Reputation: 4112

Make a function call to functions inside jQuery closure

When working with HTML and JavaScript I just simply call to a function from my <a> tag using

<a href="#" onclick="helloWorld()">Hello World</a>

I also want to make an AJAX call so using jQuery is quite easier, but I also want to wait until the DOM finishes loading so I declare my function inside the jQuery closure.

<a href="#" onclick="helloWorld()">Hello World</a>
<br>
<a href="#" onclick="ajaxCall()">Make AJAX Call</a>

<script>
    function helloWorld() {
        alert('Hello World');
    }

    $(function() {
        function ajaxCall() {
            alert('AJAX Call');
        }
    });
</script>

The first link is working, but the second is not, how should I fix it? Please advise. Thanks.

Edited

jQuery event attachment is working fine, but <a onclick="functionName()"> would offer less coding (if it can be working)

So sorry I forgot to mention about I'm not looking for jQuery event attachment.

Upvotes: 1

Views: 77

Answers (2)

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85545

How about using it in ready?

$(document).ready(function(){

  // function declaration:
  function ajaxCall() {
    alert('AJAX Call');
  }

  // call the function using delegation because you use ajax call
  $( document ).on( 'click','#ajax',ajaxCall );
});

Upvotes: 1

shabeer
shabeer

Reputation: 1064

Remove `$(function() {. Because it uses when you are using jQuery.

<script>
        function helloWorld() {
            alert('Hello World');
        }

            function ajaxCall() {
                alert('AJAX Call');
            }
    </script>

    <a href="#" onclick="helloWorld()">Hello World</a>
    <br>
    <a href="#" onclick="ajaxCall()">Make AJAX Call</a>

Upvotes: 3

Related Questions