Gel
Gel

Reputation: 3036

Why is my my function not being called if its inside the document.ready function?

I have a function called myFunction its being called from the DOM. I have jquery also initialized

<script>
  $( document ).ready(function() {
    function myFunction() {
        window.open("survey.html");
    } 
      $( "#begin" ).on("click", function() {
        event.preventDefault();
        console.log( "ready!" );
        Materialize.toast('Be a friend!', 2000);      
      });       
  });      
</script>

heres my HTML

<section class="jumbotron">
    <div class="container">
        <div class="row">
            <div class="col s8 desc">
               <h1>Welcome to Friend Finder</h1>
               <h3>Take our survey find your match.</h3>
               <a href="" id="begin" class="btn-large waves-effect waves-light red" onclick="setTimeout(myFunction, 3000);">BEGIN SEARCH</a><br>
        </div>
    </div>
  </section>

MY GOAL: when I click on tag. IT will call the function myFunction and WAIT 3 seconds setTimeout to transfer browser to next page

window.open(survey.html).

Upvotes: 0

Views: 113

Answers (3)

Vadim Cool
Vadim Cool

Reputation: 121

You do realize that you can use a different type of an onClick event, right? And in many cases this would even be a more of a correct approach since $(document).ready() means that all those functions should only start working after the entire document has been loaded properly and that is what you would want in most cases. Therefore starting from the bottom is more of a correct approach than starting from the top.

$('#begin').click(function(){
    myFunction();
});

Upvotes: 0

Bradley Flood
Bradley Flood

Reputation: 10579

Declare the function myfunction()... outside of the $(document).ready(function()...

function myFunction() {
    window.open("survey.html");
} 

$( document ).ready(function() {
    $( "#begin" ).on("click", function() {
        event.preventDefault();
        console.log( "ready!" );
        Materialize.toast('Be a friend!', 2000);      
    });       
});   

Your problem is that myFunction is scoped within the ready function. So you don't have access to this globally.

Read more about scope and closures here.

Upvotes: 2

charlietfl
charlietfl

Reputation: 171690

Because onclick requires access to the function in the global window space.

However you declared it inside $(document).ready and it is only accessible within that callback due to "scope". Just move it outside of ready

  function myFunction() {
     window.open("survey.html");
  } 

  $( document ).ready(function() {
    $( "#begin" ).on("click", function() {
    ....

Upvotes: 3

Related Questions