I have somehow a beginner's question about the following structure:
<body>
<p id="text_object">Some text</p>
<button id="button_change_text">change text on click</button>
// Individual script on page template
// ----------------------------------
<script type="text/javascript">
var object = $('#text_object');
changeTextOnLoad(object);
</script>
// Footer from included footer.php with universal main.js file
// ------------------------------------------------------------
<footer>
<script type="text/javascript" src="main.js">
</footer>
</body>
My main.js contains the following:
// declaration of function for writing new text into text object on load
function changeTextOnLoad(object) {
object.text('New text');
}
// declaration of click function
$('#button_change_text').on('click', function() {
$('#text_object').text('New text');
});
My problem: My console tells me that changeTextOnLoad() is undefined. But clicking on the button and changing the text by this way works perfectly fine. Where is the reason? Why in my main.js file does the click function get fired but not the changeTextOnLoad function?
-
2because you call the function before your main.js file has loaded, put your main.js include before the script that executes changeTextOnload, or put the call in an onload event like window.onloadPatrick Evans– Patrick Evans2014年08月23日 08:42:18 +00:00Commented Aug 23, 2014 at 8:42
-
is it possible to put the entire main.js in an onload event? how do i do that?Claudius Rehme– Claudius Rehme2014年08月23日 08:45:31 +00:00Commented Aug 23, 2014 at 8:45
-
1why dont you use document.ready()Vinay Pratap Singh Bhadauria– Vinay Pratap Singh Bhadauria2014年08月23日 08:47:21 +00:00Commented Aug 23, 2014 at 8:47
2 Answers 2
You are calling your changeTextOnLoad function before the main.js file has loaded. Either put the function call in an onload event callback or put the include above the call
window.onload = function(){
var object = $('#text_object');
changeTextOnLoad(object);
};
//Or using addEventListener
window.addEventListener("load",function(){
var object = $('#text_object');
changeTextOnLoad(object);
});
//Or since you are using jQuery
$(document).ready(function(){
var object = $('#text_object');
changeTextOnLoad(object);
});
//Or
$(function(){
var object = $('#text_object');
changeTextOnLoad(object);
});
OR
<script type="text/javascript" src="main.js"></script>
<script type="text/javascript">
var object = $('#text_object');
changeTextOnLoad(object);
</script>
Comments
because main.js is another file, browser takes time to download it. But you run changeTextOnLoad(object); before that.