Using JS function in another JS file - javascript

I have two JS files called main.js and load.js.
In main.js I have:
function removeItem() {
alert('Item removed');
}
(function($) {
$(document).ready(function() {
});
})(jQuery);
In load.js I have:
(function($) {
$(document).ready(function() {
removeItem();
});
})(jQuery);
My files are loaded in this order:
<script type='text/javascript' src='https://code.jquery.com/jquery-3.6.0.min.js?ver=3.6.0' id='script-jquery-js'></script>
<script type='text/javascript' src='url/wp-content/themes/theme/assets/js/main.js?ver=1.0' id='script-js'></script>
<script type='text/javascript' src='url/wp-content/themes/theme/assets/js/load.js?ver=1.0' id='script-load-js'></script>
It throws me an error:
removeItem() is not defined.
How can I use the function from main.js in load.js?

Related

Browser-based JS module import failing

Am trying to implement reusable code blocks in JS. According to the documentation at ExploringJS, the following approach should work:
<script language="javascript" type="module">
import declarePasswordEventHandlers from '/pathTo/password_event_handlers.js';
</script>
<script language="javascript">
$( 'document' ).ready( function() {
declarePasswordEventHandlers();
});
</script>
The imported module looks like this:
export default function declarePasswordEventHandlers() {
// event handlers being declared
}
When I load the page, I get the following error:
I've also tried:
<script language="javascript" type="module">
import { declarePasswordEventHandlers } from '/pathTo/password_event_handlers.js';
</script>
<script language="javascript">
$( 'document' ).ready( function() {
declarePasswordEventHandlers();
});
</script>
and:
<script language="javascript" type="module">
import * as passHandlerLib from '/pathTo/password_event_handlers.js';
</script>
<script language="javascript">
$( 'document' ).ready( function() {
passHandlerLib.declarePasswordEventHandlers();
});
</script>
Both used the selfsame export file as above, but with the default keyword removed from the export statement:
export function declarePasswordEventHandlers() {
// event handlers being declared
}
None of these approaches work; I get the same exact error shown in the attached screenshot.
What am I missing here?

How to call jquery function from file on pageload?

I want to my jquery function initDatePicker() into a js file. The function should require a parameter. I want the function being called on pageload.
Tried the following, but I'm probably missing some pieces here?
datepicker.js:
$(function initDatePicker(startDate) {
...
});
html:
<script type="text/javascript" src="#{/js/datepicker.js}">
$(function() {
initDatePicker('-1d');
});
</script>
Is my function definition correct in datepicker.js?
How do I correctly call the function on pageload with providing a parameter?
With the help of #deltab I could solve it as follows:
function initDatePicker(startDate) {
...
};
<script type="text/javascript" src="#{/js/datepicker.js}"></script>
<script type="text/javascript"><
$(function() {
initDatePicker('-1d');
});
</script>
<script type="text/javascript">
$(document).ready(function () {
initDatePicker('-1d');
}
</script>

Difference between init events in js file or html template

Is there a difference between lauch js functions from same JS file where they declared after page load, or in html template? When both signed into $(document).ready(function () {...}).
I assume that no, but I ran into a problem when replace my ExampleService.init() function from template to separate JS file.
For example i have that construction:
common.js
var ExampleService= {
catalogSpinner: '',
init: function() {
this.initEvents();
},
initEvents: function() {
var self = this;
$('.example-button').on('click', function() {
//do some logic, append spinner...
self.removeSpinner();
});
},
removeSpinner: function() {
$(this.catalogSpinner).fadeOut('slow', function() {
$(this).remove().css({display: 'block'});
});
}
}
index.html
<script src="js/common.js"></script>
<script>
$(document).ready(function () {
ExampleService.catalogSpinner = '<div class="spinner"></div>'; // css3 animation
ExampleService.init();
});
</script>
That way all works perfect, my catalogSpinner overriden from template, and i can use them like DOM element.
But! if i move ExampleService.init(); to common.js file, like that:
common.js
var ExampleService= {
...
// all the same...
...
};
$(document).ready(function () {
'use strict';
ExampleService.init();
});
index.html
<script src="js/common.js"></script>
<script>
$(document).ready(function () {
ExampleService.catalogSpinner = '<div class="spinner"></div>';
});
</script>
That way it wouldn't work. And throw console error Uncaught TypeError: this.catalogSpinner.fadeOut is not a function
Why it's happens? After all in both cases init functions starts only after full page load, and no matters that i override my variable after starting base functions. What im doing wrong?
About orders in which inits will executed. How i understand its no matter. Cause in any case, second document.ready from template file, always ovverride empty catalogSpinner variable from JS file, before click event happens
It's almost certainly a timing issue. What guarantee do you have that $(document).ready in common.js will fire after the same event handler in your html file (which is what needs to happen according to your implementation)?
Or, you need to make sure that when it occurs in common.js, that code can somehow retrieve the catalogSpinner value.
Also, catalogSpinner needs to be a valid jQuery object, not a string.
It will and it does work in both the cases. To use jQuery methods over DOM elements, you must have valid jQuery selectors which will return objects binded with jQuery methods.
Try this:
case 1:
common.js
var ExampleService= {
catalogSpinner: '',
init: function() {
this.initEvents();
},
initEvents: function() {
var self = this;
$('.example-button').on('click', function() {
//do some logic, append spinner...
self.removeSpinner();
});
},
removeSpinner: function() {
this.catalogSpinner.fadeOut('slow', function() {
$(this).remove().css({display: 'block'});
});
}
};
index.html
<!doctype html>
<html>
<head>
<script src="jquery.min.js"></script>
<script src="common.js"></script>
<style>
</style>
</head>
<body>
<div class="spinner">Spinner</div>
<button type="button" class="example-button">Remove</button>
<script type="text/javascript">
$(document).ready(function () {
ExampleService.catalogSpinner = $('.spinner');
ExampleService.init();
});
</script>
</body>
</html>
case 2:
common.js
var ExampleService = {
catalogSpinner: '',
init: function () {
this.initEvents();
},
initEvents: function () {
var self = this;
$('.example-button').on('click', function () {
//do some logic, append spinner...
self.removeSpinner();
});
},
removeSpinner: function () {
this.catalogSpinner.fadeOut('slow', function () {
$(this).remove().css({display: 'block'});
});
}
};
$(document).ready(function () {
'use strict';
ExampleService.init();
});
index.html
<!doctype html>
<html>
<head>
<script src="jquery.min.js"></script>
<script src="common.js"></script>
<style>
</style>
</head>
<body>
<div class="spinner">Spinner</div>
<button type="button" class="example-button">Remove</button>
<script type="text/javascript">
$(document).ready(function () {
ExampleService.catalogSpinner = $('.spinner');
});
</script>
</body>
</html>

Call to function in parent from .JS file from inside iframe

I have JS file with uploader functionality.
This file called from an iframe window.
I need to show alerts to user according to his actions.
Here is what I've done and it's not works:
From JS file:
$('#btnUpload').on('click', function(){
parent.CallToParent();
});
And from UploaderWindow call to:
function CallToParent()
{
parent.ShowAlert();
}
And on main window:
function ShowAlert()
{
alert('some alert');
}
I think you are doing it correct. Don't know if the parent.CallToParent() in the click event really refers to the function in the parent window. If it doesn't then you could do something like.
From JS file:
$(document).ready(function () {
$('#btnUpload').on('click', function() {
callParent();
})
});
And from iframe:
<script type="text/javascript" src="/common/jq.js"></script>
<script type="text/javascript" src="c.js"></script>
<script>
function callParent() {
parent.fn();
}
</script>
<input id="btnUpload" type="button" />
Main File
<script>
function fn() {
console.log('Parent function called');
}
</script>
<iframe src="b.html"></iframe>
To my knowledge, there's no interoperability of scripts between these two contexts.
If you have control of the iframe contents then you could implement a 'middle-man' service to pipe messages.

Execute javascript from bundles in Document.ready

I use the MVC4 default template.
I add a script : MyScript.js in /Scripts/MyApp/ with a function :
function Testing()
{
alert('test');
}
In the global.asax :
bundles.Add(new ScriptBundle("~/bundles/myapp").Include(
"~/Scripts/MyApp/MyScript.js"));
I'd like call this method in /Views/Home/Index.cshml
I tried the code below but without success:
<script type="text/javascript" lang="javascript">
$(document).ready(function () {
Testing();
});
</script>
#Scripts.Render("~/bundles/myapp")
When I look the source code the link to MyScript.js is there and I can navigate to it (go to the source)
But the Testing() method in the $(document).ready is not executed.
Update1
<script type="text/javascript" lang="javascript">
$(document).ready(function () {
alert("test");
});
</script>
Try putting you inline script after the bundle inclusion. Also the lang attribute on the script tag is deprecated:
#Scripts.Render("~/bundles/myapp")
<script type="text/javascript">
$(document).ready(function () {
Testing();
});
</script>
UPDATE:
OK, I think you forgot to include jquery, so the $ function not defined :-)
So if you want to do it with bundles:
bundles.Add(new ScriptBundle("~/bundles/myapp").Include(
"~/Scripts/jquery-{version}.js", "~/Scripts/MyApp/MyScript.js")
);
or if you don't want to use bundles:
<script type="text/javascript" src="~/scripts/jquery-1.7.1.js"></script>
<script type="text/javascript" src="~/scripts/MyScript.js"></script>
<script type="text/javascript">
$(document).ready(function () {
Testing();
});
</script>

Categories