Castle
Castle

Reputation: 427

How to call a function in an html file from another html file

I'm trying to call a function from my html: tasks-div-upload.html to my other html: task-tareas-actualizadas.html.

I'm including my scripts on the script tags of the html files

I tried to call the function like this

First of all this is the html that calls the function: tasks-divs-upload.html

and the function is in task-tareas-actualizadas.html

I tried to call the function like i do in java that is

writing the class and then the function, for example: people.countPeople(5);

In this case, there are not classes because its an html file so what can I do?

//tasks-divs-upload.html

 function contadorTareas(){
   for(var x = 0; x < divs; x++){
     var numeroTareas = x;
   }
   prueba(numeroTareas);    // <---------
 } 

//task-tareas-actualizadas.html

function prueba(numero){
  console.log(numero);
}

Console shows this error "Uncaught ReferenceError: prueba is not defined"

Upvotes: 1

Views: 1556

Answers (2)

Mark Schultheiss
Mark Schultheiss

Reputation: 34227

This CAN be done but is mostly a bad idea and is not very common and has some specific requirements. It is best it NOT be done unless the user is aware of the interaction.

IF your task-tareas-actualizadas.html opens tasks-divs-upload.html in a new window then tasks-divs-upload.html can call window.opener.prueba() BUT, if the first window gets closed, it will not be there and they must both be of the same origin.

This interaction can also go the other way if the parent keeps a reference to the child window.

Better to create a JavaScript file say "myfunctions.js" that includes the functions you wish to use and include it in both pages UNLESS for some reason you need/want the pages to interact - say the child page alters the parent page DOM or some such.

Reference https://developer.mozilla.org/en-US/docs/Web/API/Window/opener and https://developer.mozilla.org/en-US/docs/Web/API/Window/open

Upvotes: 2

Nadir Latif
Nadir Latif

Reputation: 3773

Well scripts in HTML are JavaScript code. They need to be either defined in separate .js files or included in html using <script> tags.

It is not possible to define a JavaScript function in a html file and then use it in another html file. You need to define the function is a separate JavaScript file and then include this file in the html page.

You may also use JavaScript modules which are natively supported by modern browsers.

Upvotes: 0

Related Questions