Skip to content Skip to sidebar Skip to footer

How To Call A Function In One Html Page In Another Html Page

I have 2 pages. one.html and two.html The first html page contains a script tag with a java script function modify(d).In two.html i want to call this same function instead of retyp

Solution 1:

If you drop inline scripts (and it goes for inline styles too) and do like this, where you store functions (and rules) in a file of its own, you will be able to reuse it (them) like shown in below sample

File: one.html

<!DOCTYPE html><html><head><title>Page One</title><metahttp-equiv='content-type'content='text/html; charset=UTF-8' /><linkrel='stylesheet'type='text/css'href='css/style.css' /><scriptsrc="js/script.js"></script></head><body>
    Page one content  
</body></html>

File: two.html

<!DOCTYPE html><html><head><title>Page two</title><metahttp-equiv='content-type'content='text/html; charset=UTF-8' /><linkrel='stylesheet'type='text/css'href='css/style.css' /><scriptsrc="js/script.js"></script></head><body>
    Page two content  
</body></html>

File: style.css

body {
  background: url(../images/bkg.png);
}

File: script.js

functionmodify(d) {
  ....
}

And have your files located like this in your folder

/www/one.html
/www/two.html
/www/js/script.js
/www/css/style.css
/www/images/bkg.png

Solution 2:

You can extract your JavaScript script tag content into its own file and include that script in both HTML pages, so:

  • create a file somewhere in your folder structure (you can put it in the same path as your HTML files for ease at the moment) let's say it's called my script.js

  • in each one of your HTML files you can include your script using script tags:

    <scriptsrc="./script.js"/>

You can include the script tag in the <head> of your HTML files or as the last element within the <body> tag.

Solution 3:

You'll need to put the JS in its own file and reference it from both HTML file. Below is a pseudo code to explain better.

script.js

$('.box').click(function(e) {
  e.preventDefault();
  console.log('Box has been logged!');
});

index.html

<scriptsrc="./script.js"></script><divclass="box"></div

other.html

<scriptsrc="./script.js"></script><divclass="box"></div

Solution 4:

Use the concept of External Javascript. Refer the link. Using this, create a single Javascipt file and put the modify() method into it. Now load the javascript on both the forms.(i.e one.html and two.html)

Post a Comment for "How To Call A Function In One Html Page In Another Html Page"