user4520762
user4520762

Reputation:

(document).ready is a global scope?

Guys i have this function inside my script.js:

$(document).ready(function() {
    function alert() {
      alert('AAAAAAAA');
    }
});

And i am trying to call here in my index.html:

$('.something').on('click', function() {
  e.preventDefault();
  alert();
});

But is showing my this error - alert is not defined.

But when i take off the document ready in the external script, the click handler will work. Why is that?

The document ready is creating a separate scope?

Upvotes: 4

Views: 3460

Answers (3)

Kevin Ji
Kevin Ji

Reputation: 10499

Using $(document).ready() creates a new function scope (note the function() after the .ready), so when you call

$(document).ready(function() {
    function alert() {
        alert('AAAAAAAA');
    }
});

alert is only defined within the document.ready block. There are two ways to solve this issue:

  1. Define the function outside of the document.ready block:

    function customAlert() {
        alert('AAAAAAAA');
    }
    
  2. Attach the function to the window object:

    $(document).ready(function() {
        window.customAlert = function() {
            alert('AAAAAAAA');
        };
    });
    

Upvotes: 6

Adrian Bolonio
Adrian Bolonio

Reputation: 517

Include the click event into the document.ready

Check it here http://jsfiddle.net/fbrcm45q/1/

$(document).ready(function() {
  function showAlert() {
    alert('AAAAAAAA');
  }
  $('.something').on('click', function(e) {
    e.preventDefault();
    showAlert();
  });
});

Upvotes: 1

Jafar Akhondali
Jafar Akhondali

Reputation: 1537

First of all e.preventDefault is a function so you have to add braces at the end:

e.preventDefault()

Second alert is a function in javascrpt, so you need to rename your function to something else, for example:

$(document).ready(function() {
    function special_alert() {
      alert('AAAAAAAA');
    }
});

and:

$('.something').on('click', function() {
  e.preventDefault();
  special_alert();
});

Upvotes: 0

Related Questions