Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

240
Visualizações
Javascript external function from html gives 'function not defined'

I'm trying to call a function within the html page from an external loaded index.js file, but I always get

Uncaught ReferenceError: displayy is not defined

Inside my html page:

 <script type="text/javascript" src="index.js"></script>

<script>
    $( document ).ready(function() {
       displayy();
    });
</script>

The index.js file:

$( document ).ready(function() {
    alert('loaded');
      function displayy() {
    alert('executed');
    } 
 });

I've also tried:

<script>
    window.onload = function() {
        displayy();
    };
</script>

<script>

    document.addEventListener("DOMContentLoaded", function(event) {
        displayy();
    });
</script>
about 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

You need not run displayy again from the script. The following works:

$(document).ready(function() {
      alert('loaded');
      displayy();
      function displayy() {
        alert('executed');
      } 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

about 4 years ago · Santiago Trujillo Relatório

0

Inside your index.js you can call your function using the window object.

window.displayy = function(){ 
    return "hello!" 
}

and then you call it window.displayy(); or displayy();

A better solution is to declare your function in the higher scope like this:

var displayy;

$( document ).ready(function() {
      alert('loaded');
      displayy = function () {
       alert('executed');
      } 
 });

N.B: Using global variables are bad but it should solve your problem. Please take a look here: I've Heard Global Variables Are Bad, What Alternative Solution Should I Use?

about 4 years ago · Santiago Trujillo Relatório

0

Attach your functions to the window object. Something like this:

// Set the container!
window.app = {};

// Define the function.
window.app.say_hello = function(name) {
   alert(`Hello ${name}`);
};

// Call the function.
app.say_hello("Iran");

I tried everything. Only this solution worked. :)

about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda