How can I split the same function in two parts? - javascript

Let's say I have the following structure, just an example:
(function number1( $ ) {
$.fn.abcd = function( options ) {
heyyou.find(".123").css({});
heyyou.find(".456").css({});
var delay = 1000;
var site = "http://url";
setTimeout(function(){ window.location.href = site; },delay);}
$("#button").on('click', function(){ window.location.href = site;});
return this;
}( jQuery ));
And what I believe I need to do is something like this:
//part1
(function number1( $ ) {
$.fn.abcd = function( options ) {
heyyou.find(".123").css({});
heyyou.find(".456").css({});
return this;
}( jQuery ));
//part2
(function number1( $ ) {
$.fn.abcd = function( options ) {
var delay = 1000;
var site = "http://url";
setTimeout(function(){ window.location.href = site; },delay);}
$("#button").on('click', function(){ window.location.href = site;});
return this;
}( jQuery ));
What I'm trying to achieve here is:
"part1" is going to be inside a js file that's going to be placed inside the header. "part2" is a function that I need to call from a <script></script> later on the DOM.
The thing is that both parts are using the same main function, one is continuing the other.
For example:
<script src="part1.js"></script>
<body>
<script>//part2</script>
<button id="button">Do something</button>
</body>
So basically I want the function to start in the js file, then I'll finish it from another part. I'm not sure how to explain this, it's just that I need the var site to be called separately, as I'm going to use the same script for different pages, I need each page to call for the var site with a different value.
Basically it's a redirect script, so I can't use the same redirection url for every page.
EDITED:
The structure needs to be like this:
mainjs.js:
<header>
<script>
//part1
(function number1( $ ) {
$.fn.abcd = function( options ) {
heyyou.find(".123").css({});
heyyou.find(".456").css({});
return this;
}( jQuery ));
</script>
</header>
Page 1:
//part2
var site google
Page 2:
//part2
var site bing
Page 3:
//part2
var site yahoo
"//Part1" is executed first and is executed in every page.
"//part2" is executed later and each page will have a different url to redirect to, inside "//part2" function.
In reply to Ehsan:
It would have to be like this:
<script type="text/javascript" >
function function1(site) {
//redirect to site
alert(site);
}
</script>
<script type="text/javascript" >
function function2() {
// Do your css thing here.
site = "http://somethingelse";
function2(site);
}
</script>
<button onclick="function2()">Click me</button>

Edit - 3
You are looking for something like this.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
alert(site);
});
</script>
<script type="text/javascript">
var site = "google.com";
</script>
You can create two separate functions, chain them and use global variables to pass the data between them.
<script type="text/javascript" >
var site = "http://url";
function function1() {
// Do your css thing here.
site = "http://somethingelse";
function2();
}
</script>
<button onclick="function1()">Click me</button>
<script type="text/javascript" >
function function2() {
//redirect to site
alert(site);
}
</script>
Edit: You can also pass data by using parameter in function, then you don't need to use the global parameter. It depends on the use case, but I assume passing as a parameter is a much cleaner option.
<script type="text/javascript" >
function function1() {
// Do your css thing here.
site = "http://somethingelse";
function2(site);
}
</script>
<button onclick="function1()">Click me</button>
<script type="text/javascript" >
function function2(site) {
//redirect to site
alert(site);
}
</script>

Related

how to create a js function and use it on another files [duplicate]

I wanted to call a function defined in a first.js file in second.js file. Both files are defined in an HTML file like:
<script type="text/javascript" src="first.js"></script>
<script type="text/javascript" src="second.js"></script>
I want to call fn1() defined in first.js in second.js. From my searches answers were if first.js is defined first it is possible, but from my tests I haven't found any way to do that.
Here is my code:
second.js
document.getElementById("btn").onclick = function() {
fn1();
}
first.js
function fn1() {
alert("external fn clicked");
}
A function cannot be called unless it was defined in the same file or one loaded before the attempt to call it.
A function cannot be called unless it is in the same or greater scope then the one trying to call it.
You declare function fn1 in first.js, and then in second you can just have fn1();
1.js:
function fn1 () {
alert();
}
2.js:
fn1();
index.html :
<script type="text/javascript" src="1.js"></script>
<script type="text/javascript" src="2.js"></script>
You could consider using the es6 import export syntax. In file 1;
export function f1() {...}
And then in file 2;
import { f1 } from "./file1.js";
f1();
Please note that this only works if you're using <script src="./file2.js" type="module">
You will not need two script tags if you do it this way. You simply need the main script, and you can import all your other stuff there.
1st JS:
function fn(){
alert("Hello! Uncle Namaste...Chalo Kaaam ki Baat p Aate h...");
}
2nd JS:
$.getscript("url or name of 1st Js File",function(){
fn();
});
You can make the function a global variable in first.js
and have a look at closure and do not put it in document.ready put it outside
you can use ajax too
$.ajax({
url: "url to script",
dataType: "script",
success: success
});
same way you can use jquery getScript
$.getScript( "ajax/test.js" )
.done(function( script, textStatus ) {
console.log( textStatus );
})
.fail(function( jqxhr, settings, exception ) {
$( "div.log" ).text( "Triggered ajaxError handler." );
});
declare function in global scope with window
first.js
window.fn1 = function fn1() {
alert("external fn clicked");
}
second.js
document.getElementById("btn").onclick = function() {
fn1();
}
include like this
<script type="text/javascript" src="first.js"></script>
<script type="text/javascript" src="second.js"></script>
use "var" while creating a function, then you can access that from another file. make sure both files are well connected to your project and can access each other.
file_1.js
var firstLetterUppercase = function(str) {
str = str.toLowerCase().replace(/\b[a-z]/g, function(letter) {
return letter.toUpperCase();
});
return str;
}
accessing this function/variable from file_2.js file
firstLetterUppercase("gobinda");
output => Gobinda
It should work like this:
1.js
function fn1() {
document.getElementById("result").innerHTML += "fn1 gets called";
}
2.js
function clickedTheButton() {
fn1();
}
index.html
<html>
<head>
</head>
<body>
<button onclick="clickedTheButton()">Click me</button>
<script type="text/javascript" src="1.js"></script>
<script type="text/javascript" src="2.js"></script>
</body>
</html>
output
Try this CodePen snippet: link .
Please note this only works if the
<script>
tags are in the body and NOT in the head.
So
<head>
...
<script type="text/javascript" src="first.js"></script>
<script type="text/javascript" src="second.js"></script>
</head>
=> unknown function fn1()
Fails and
<body>
...
<script type="text/javascript" src="first.js"></script>
<script type="text/javascript" src="second.js"></script>
</body>
works.
This is actually coming very late, but I thought I should share,
in index.html
<script type="text/javascript" src="1.js"></script>
<script type="text/javascript" src="2.js"></script>
in 1.js
fn1 = function() {
alert("external fn clicked");
}
in 2.js
fn1()
Use cache if your server allows it to improve speed.
var extern =(url)=> { // load extern javascript
let scr = $.extend({}, {
dataType: 'script',
cache: true,
url: url
});
return $.ajax(scr);
}
function ext(file, func) {
extern(file).done(func); // calls a function from an extern javascript file
}
And then use it like this:
ext('somefile.js',()=>
myFunc(args)
);
Optionally, make a prototype of it to have it more flexible. So that you don't have to define the file every time, if you call a function or if you want to fetch code from multiple files.
first.js
function first() { alert("first"); }
Second.js
var imported = document.createElement("script");
imported.src = "other js/first.js"; //saved in "other js" folder
document.getElementsByTagName("head")[0].appendChild(imported);
function second() { alert("Second");}
index.html
<HTML>
<HEAD>
<SCRIPT SRC="second.js"></SCRIPT>
</HEAD>
<BODY>
method in second js<br/>
method in firstjs ("included" by the first)
</BODY>
</HTML>
window.onload = function(){
document.getElementById("btn").onclick = function(){
fn1();
}
// this should work, It calls when all js files loaded, No matter what position you have written
});
// module.js
export function hello() {
return "Hello";
}
// main.js
import {hello} from 'module'; // or './module'
let val = hello(); // val is "Hello";
reference from https://hype.codes/how-include-js-file-another-js-file
My idea is let two JavaScript call function through DOM.
The way to do it is simple ...
We just need to define hidden js_ipc html tag.
After the callee register click from the hidden js_ipc tag, then
The caller can dispatch the click event to trigger callee.
And the argument is save in the event that you want to pass.
When we need to use above way ?
Sometime, the two javascript code is very complicated to integrate and so many async code there. And different code use different framework but you still need to have a simple way to integrate them together.
So, in that case, it is not easy to do it.
In my project's implementation, I meet this case and it is very complicated to integrate. And finally I found out that we can let two javascript call each other through DOM.
I demonstrate this way in this git code. you can get it through this way. (Or read it from https://github.com/milochen0418/javascript-ipc-demo)
git clone https://github.com/milochen0418/javascript-ipc-demo
cd javascript-ipc-demo
git checkout 5f75d44530b4145ca2b06105c6aac28b764f066e
Anywhere, Here, I try to explain by the following simple case. I hope that this way can help you to integrate two different javascript code easier than before there is no any JavaScript library to support communication between two javascript file that made by different team.
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/style.css" />
</head>
<body>
<div id="js_ipc" style="display:none;"></div>
<div id="test_btn" class="btn">
<a><p>click to test</p></a>
</div>
</body>
<script src="js/callee.js"></script>
<script src="js/caller.js"></script>
</html>
And the code
css/style.css
.btn {
background-color:grey;
cursor:pointer;
display:inline-block;
}
js/caller.js
function caller_add_of_ipc(num1, num2) {
var e = new Event("click");
e.arguments = arguments;
document.getElementById("js_ipc").dispatchEvent(e);
}
document.getElementById("test_btn").addEventListener('click', function(e) {
console.log("click to invoke caller of IPC");
caller_add_of_ipc(33, 22);
});
js/callee.js
document.getElementById("js_ipc").addEventListener('click', (e)=>{
callee_add_of_ipc(e.arguments);
});
function callee_add_of_ipc(arguments) {
let num1 = arguments[0];
let num2 = arguments[1];
console.log("This is callee of IPC -- inner-communication process");
console.log( "num1 + num2 = " + (num1 + num2));
}
better late than never
(function (window) {const helper = { fetchApi: function () { return "oke"}
if (typeof define === 'function' && define.amd) {
define(function () { return helper; });
}
else if (typeof module === 'object' && module.exports) {
module.exports = helper;
}
else {
window.helper = helper;
}
}(window))
index html
<script src="helper.js"></script>
<script src="test.js"></script>
in test.js file
helper.fetchApi()
I have had same problem. I have had defined functions inside jquery document ready function.
$(document).ready(function() {
function xyz()
{
//some code
}
});
And this function xyz() I have called in another file. This doesn't working :) You have to defined function above document ready.
TLDR: Load Global Function Files first, Then Load Event Handlers
Whenever you are accessing an element within a JS file or <script> block, it is essential to check to make sure that element exists, i.e., jQuery's $(document).ready() or plain JS's document.addEventListener('DOMContentLoaded', function(event)....
However, the accepted solution does NOT work in the event that you add an event listener for the DOMContentLoaded, which you can easily observe from the comments.
Procedure for Loading Global Function Files First
The solution is as follows:
Separate the logic of your JS script files so that each file only contains event listeners or global, independent functions.
Load the JS script files with the global, independent functions first.
Load the JS script files with event listeners second. Unlike the other previous files, make sure to wrap your code in document.addEventListener('DOMContentLoaded', function(event) {...}). or document.Ready().

jquery - ajaxStop is not consistently executing javascript redirect

I am using jquery 1.9.1. I have logout code where I need to post to multiple pages then do a redirect:
<script type="text/javascript">
window.onload=function(){
$( document ).ajaxStop(function() {
logoutRedirect();
});
logoutOfApps();
}
</script>
These methods are in a different javascript file (but I think that is irrelavent).
function logoutOfApps(){
$.post("/app1/logout");
$.post("/app2/logout");
}
function logoutRedirect(){
var redirectOnLogoutURL = null;
redirectOnLogoutURL = "/mylogoutdisplaypage";
top.location = redirectOnLogoutURL;
}
SECOND TRY: This also doesn't work consistently:
<script type="text/javascript">
window.onload=function(){
logoutOfApps();
logoutRedirect();
}
</script>
Make sure both requests have finished before you redirect
function logoutOfApps(){
return $.when(
$.post("/app1/logout"),
$.post("/app2/logout")
)
}
logoutOfApps().done(logoutRedirect);
Just for completeness thought I would document exactly how I changed it, which took a little while to get just right. Thank you adeneo for your answer that I accepted.
<script type="text/javascript">
window.onload=function(){
onLoadOfPage();
}
</script>
This is in the second file (I preferred all jquery code in one file):
function onLoadOfPage(){
$( document ).ajaxStop(function() {
logoutRedirect();
});
logoutOfApps().done(logoutRedirect);
}
function logoutOfApps(){
return $.when(
$.post("/app1/logout"),
$.post("/app2/logout")
)
}
function logoutRedirect(){
var redirectOnLogoutURL = null;
redirectOnLogoutURL = "/mylogoutdisplaypage";
top.location = redirectOnLogoutURL;
}

jQuery and YUI load

I am using jQuery and YUI-3.6.0 in my application. I am using YUI history module. I trie to create a wrapper on YUI history as below. (This is saved in "history-wrapper.js")
var MyHistory;
(function() {
YUI().use('history', function (Y) {
var history = null;
MyHistory = function() {
history = new Y.History();
};
MyHistory.prototype.save= function() {
history.add({
data : "some data"
});
};
MyHistory.prototype.load= function() {
var data = (history.get("data");
//process data
};
});
})();
I am using this wrapper with following lines of code
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="yui/yui/yui-min.js"></script>
<script type="text/javascript" src="js/history-wrapper.js"></script>
<script type="text/javascript">
var jQ = jQuery.noConflict();
jQ(document).ready(function() {
var history = new MyHistory();
history.save();
});
</script>
I am using same code in two different application.
In one application, everything works fine as Wrapper is loaded first.
In other application it throws "MyHistory is not defined" as "jQ(document).ready" function is called before wrapper is loaded.
I have no idea what causes this behavior. Can anyone help me?
The callback function "function(Y){... where you define MyHistory...}" in the YUI.use() is only executed when the dependendies (history) are loaded.
Then, you have no assurance MyHistory is defined when you try to use your wrapper.
The solution may be you put your JQuery code in the the YUI.use() too. You can make the YUI loader load jquery and the history module, you the no longer need to wrap the Histroy plugin.
I'm not sure it is exactly like this (cannot check it now).
<script type="text/javascript" src="yui/yui/yui-min.js"></script>
YUI({
modules: {
'jquery': {
path: 'js/jquery.js'
}
}
}).use('history', 'jquery' , function (Y) {
var jQ = Y.jQuery.noConflict(); //or juste jQuery.noConflict();
jQ(document).ready(function() { //it is likely the document will already be ready
var history = new Y.History();
history.save();
});
});

How to call function on page load in JS?

I have a js function which looks like this
function showProducts(){
document.getElementById("shopList").innerHTML = "<ul><li>Test Text</li></ul>";
}
It's a function that has to show an array of my products. I've made an div with id="shopList" in my html page
<div id="shopList">
</div>
But how can I call the function to show me the text in the div? It works when I use this as my body tag but I'm not allowed to write any js code in my html or to use onload or onclick. I'm trying to do it with listeners for almost 4 hours and I still did not find a solution. Could someone help me?
<body onload="showProducts()">
Using pure javascript:
window.onload = function(){
};
(or
function doLoad() {
//Do stuff on load
}
window.onload = doLoad;
With Jquery
$(document).ready(function(){
});
It's not difficult with listeners. Here is a solution (not cross-browser):
document.addEventListener("DOMContentLoaded", showProducts);
Really, assigning to onload is just shorthand for doing it with listeners. This should work , though I haven't tested it.
window.addEventListener("load", showProducts);
With Jquery you could do something like this :
$(document).ready(function(){
showProducts();
});
It waits untill the page is loaded and then executes the function.
You just put it in an external .js file and include it in your page.
(For the people downvoting this answer because it's Jquery, he said he couldn't use onload() so I just mentioned this option. )
Just place the script at the bottom:
<body>
...
<script type="text/javascript">
myFunction();
</script>
</body>
John Resig's simplified version from "Pro JavaScript Techniques". It depends on addEvent.
var ready = ( function () {
function ready( f ) {
if( ready.done ) return f();
if( ready.timer ) {
ready.ready.push(f);
} else {
addEvent( window, "load", isDOMReady );
ready.ready = [ f ];
ready.timer = setInterval(isDOMReady, 13);
}
};
function isDOMReady() {
if( ready.done ) return false;
if( document && document.getElementsByTagName && document.getElementById && document.body ) {
clearInterval( ready.timer );
ready.timer = null;
for( var i = 0; i < ready.ready.length; i++ ) {
ready.ready[i]();
}
ready.ready = null;
ready.done = true;
}
}
return ready;
})();
window.onload would work, but it is a different beast. jQuery's $(document).ready() is much more complex and better in most scenarios.
Given your criteria of "no script in the HTML" and "no onload or onclick listener", you can put the function into a separate file and run it from a script element at the foot of the page:
<script type="text/javascript" src="showproducts.js"></script>
so now you have no script in the page and no listeners. The code will be executed when the element is added to the DOM, so as long as it is after the related DIV, you're fine.
Incidentally, you don't even need a function, you can just put the statements from the function body into the file.

jquery - call function in external js file

If I have this code in a file called custom.js:
var kennel = function(){this._init();};
kennel.prototype = {
_init: function() {
this.setListeners();
},
setListeners: function(){
...
},
getCats: function(){
alert("Get cats");
}
};
How do I call getCats() from some arbitrary html file?
First of all you would include the javascript by using the <script> tag, generally in the <head>, then after that you can create another <script> tag which you can place your own javascript code in that is specific to the page, and which uses the functionality made available by the included file. For example:
<head>
<script type="text/javascript" src="path/to/custom.js"></script>
<script type="text/javascript">
var myKennel = new kennel();
myKennel.getCats(); // alerts "Get cats"
</script>
</head>
Also, the code you have posted has nothing to do with jQuery - it is plain old, vanilla javascript.
This should be enough:
<script>
var k = new kennel();
k.getCats();
</script>
Here's a sample of it working: http://jsfiddle.net/NHaBb/
​

Categories