Call JS function with attributes from another file - javascript

I have a JS file with a simple function, matching width\heights of divs.
How can I call this function using attributes from HTML file.
In other words, I want to write a function matchHeight(div1,div2) in an outside file but call it from wherever i want using the divs I want.
The function exists, I just don't know how to call it the way I want.
Sorry if I didn't explain myself clearly.
Thanks.

If you write your MatchHeights(d1,d2){ ... } function in a JS file and link the file in your HTML page like you normally would link any JS file, then you can call the function in any part of your page, as long as you call the function after the linked file has been loaded by the browser.
Infact, you could even call it in other JS files, as long as the original containing file is loaded before the other ones by the browser.
To get the function to run the moment the page loads, call the function in the onload event of the body tag:
<script type="text/javascript">
var div1 = (some code to get the element)
var div2 = (some code to get the element)
</script>
...
...
<body onload="matchHeight(div1,div2)">

You must link the .js file in your .html file like this:
<head>
<script src="yourJSFile.js" type="text/javascript"></script>
</head>
<body onLoad="yourFunction();">
</body>

A really common pattern in jQuery that you can apply is passing in the CSS selector. It's easiest if you can just pass in the div's IDs, but other solutions will work also.
First off take any arguments out of your init string. It's way to complicated. Try this instead:
<body onload="init()">
function init() {
matchHeight("id1", "id2");
}
Once you have that you get the actual div in those functions like this:
function matchHeight(id1, id2) {
var div1 = document.getElementById(id1)
var div2 = document.getElementById(id2)
// .. other stuff
}
If you're using jQuery I'd recommend simplifying this even more, by taking the init() function off of the body tag completely, replacing it with jquery(document).load(function() { and using normal CSS selectors instead....matchHeight("#id1", "#id2") and var $div1 = $(id1);, but either way will work :)

Related

Initialize more than one html element using jQuery and Javascript

I have tried to lead my html element to fire my customized JS file's method.
Third textarea appears nicely.
First and second textareas does not effect any of the settings i am trying to change in myJSFile.js file.
Here's my problem : js file loads the last textarea nicely, but cannot initialize previous ones properly using my js methods.
I'm doing something wrong with my JS file, and i'd appreciate if you help me.
P.S. : Initalizing some plugin and working on CKEditor.
Here's my HTML file :
<textarea id="myTextAreaID" name="myTextArea"></textarea>
<script type="text/javascript" src="../public/js/myJSFile.js"onload="setTextAreaValues('myTextAreaID')"></script>
<textarea id="myTextAreaID2" name="myTextArea2"></textarea>
<script type="text/javascript" src="../public/js/myJSFile.js"onload="setTextAreaValues('myTextAreaID2')"></script>
<textarea id="myTextAreaID3" name="myTextArea3"></textarea>
<script type="text/javascript" src="../public/js/myJSFile.js"onload="setTextAreaValues('myTextAreaID3')"></script>
Here's myJSFile.js file
var textAreaID;
$(function(){
var myTextArea = $('#'+textAreaID);
//something is being loaded here, and it is loaded fine.
});
function setTextAreaParameters(param){
textAreaID = param;
}
Thanks in advance.
This is not very good idea to do it like this, however it's interesting to understand why it happens. In your code below you are defining global variable textAreaID:
var textAreaID;
$(function() {
var myTextArea = $('#' + textAreaID);
//something is being loaded here, and it is loaded fine.
});
function setTextAreaParameters(param) {
textAreaID = param;
}
This script is injected three times into document. After the last script tag the value of textAreaID variable will be myTextAreaID3, because it's global and the last setTextAreaParameters invocation will override previous. Remember that scripts are loaded synchronously in your case (no async or deferred attribute), it means that onload callbacks don't wait and immediately set textAreaID to new values.
However DOMContentLoaded event has not yet fired. This is the event you are subscribing with this code:
$(function() {
// DOMContentLoaded
});
When it eventually does - only the third textarea will be processed - the one with id myTextAreaID3.
Better approach would be to have only one script tag and set textareas the same className attribute:
<textarea id="myTextAreaID2" name="myTextArea2" class="editor"></textarea>
Then in the script probably have some sort of map with configuration parameters for each individual textarea.
You are including the same script three times, but the browser is probably smart enough to only load it once (no reason to load the same script on the same page more than once).
What you need to do is to include the script only once, say before the end of the body tag
...
<script type="text/javascript" src="../public/js/myJSFile.js"></script>
</body>
and then in the JS file, wait for the document to load, and handle all text areas accordingly:
$(function() {
$('textarea').each(function(i, j) {
console.log('do something for the ' + i + 'th text area');
});
})

Scripts not running when using get function in jquery

I'm using the $.get() function to extract some data from my site. Everything works great however on one of the pages the information I need to extract is dynamically created and then inserted into a <div> tag.
So in the <script> tag, a function is run and then the data is inserted into <div id="infoContainer"></div>. I need to get the information from #infoContainer, however when I try to do so in the $.get() function, it just says it's empty. I have figured out that it is because the <script> tag is not being run. Is there another way to do this?
Edit:I am making a PhoneGap application for my site using jQuery to move content around so it's more streamlined for mobiles.
This is the code on my page:
$(document).ready(function () {
var embedTag = document.createElement("embed");
var infoContainer = document.getElementById("infoContainer");
if (infoContainer != null) {
embedTag.setAttribute("height", "139");
embedTag.setAttribute("width", "356");...other attributes
infoContainer.appendChild(embedTag);
});
});
As you can see, it puts content into the #infoContainer tag. However, when I try to extract info from that tag through the get function it shows it as empty.I have done the same to extract headings and it works great. All I can gather is the script tag is not firing.
This should provide you the contents of the element:
$('#infoContainer').html();
Maybe your script is executing before the DOM is loaded.
So if you are manipulating DOM elements you should wait till DOM is loaded to manipulate it. Alternately you can place your script tag at the end of your HTML document.
// These three are equivalent, choose one:
document.addEventListener('DOMContentLoaded', initializeOrWhatever);
$( initializeOrWhatever );
$.ready( initializeOrWhatever );
function initializeOrWhatever(){
// By the time this is called, the DOM is loaded and you can read/write to it
$.getJSON('/foo/', { myData: $('#myInput').val() }, onResponse);
function onResponse(res){
$(document).html('<h1>Hello '+res+'</h1>');
};
};
Otherwise... post more specifics and code
You have no ID to reference. Try setting one before you append
embedTag.setAttribute("id", "uniqueID");
It looks like you are wanting to use jQuery, but your example code has vanilla JavaScript. Your entire function can be simplified using the following jQuery (jsFiddle):
(function () {
var embedTag = $(document.createElement("embed"));
var infoContainer = $("#infoContainer");
if (infoContainer.length) {
embedTag.attr({"height": 139, "width": 356});
infoContainer.append(embedTag);
}
console.log(infoContainer.html()); // This gets you the contents of #infoContainer
})();
jQuery's .get() method is for sending GET requests to a server-side script. I don't think it does what you are wanting to do.

Is a JavaScript function defined in <script> block accessible by another JS function?

I have the following code in my HTML file:
<script src = "js/create.js"></script>
<script>
function show() {
//some code here
}
</script>
In the JavaScript file create.js, I want to call the function show() defined in the block, like this:
//File create.js
var a = show();
So is the function show() accessible in the file create.js?
Yes, you defined the function without putting it in a var so it will be hoisted to the most outer scope being the global scope.
But you run create before that function is declared so it wont see it, turn them around and see.
You could have just tried this one out, but I'll still try to briefly explain.
Since JavaScript is client side, it depends on the current state of the client side. Until the needed part is loaded, you won't be able to access it.
In your case, you first include your create.js file. When it is loaded, the next one isn't yet. So var a = show(); will look for the function named show(); however will throw an error saying null reference to the function, as it wouldn't be available in client yet.
The way you can avoid this is to check whether the parts of the documents were loaded. In jQuery, this is made with $(document).ready, in classic JavaScript you can somewhat depend on window.onload, body tag's onload.
There is also another casual way of doing this, see the following sheet.
<html>
<head>
<title>Test!</title>
<script type="text/javascript">
function show(){
alert("Hey there!");
}
</script>
</head>
<body>
<h1>Hey there!</h1>
<p>The alert box should appear after these lines are loaded in client, this will also mean the head is completed, so it's safe to call the function show()</p>
<script type="text/javascript">
show();
</script>
</body>
</html>
In that, we can certainly assume the function defined in the head was loaded until the point the second script, which calls the defined function can be runnable safely.
Yes, this is how add-in libraries like jQuery work. You include their .js file, and then call its methods.

including a javascript file at the end of the file doesn't work for some functions

In my file, a have many dom elements and an external javascript file that has some functions to manage events. The problem is that when i include the functions.js file at the end of my main file:
<script src="functions.js"></script>
That works for some elements but not for others. So i move that at the top of my file, and now it works for some elements but not the other either.
It doesn't works means that i got such error in the web console:
ReferenceError: oneOfMyFunctions is not defined
What is the best place to put that include? Thanx in advance.
EDIT:
In my html file (the main file), i did this:
<script>
window.onload = function(){
// start calling your function eg. functions.j();
myFunction();
};
</script>
Still get the same issue.
You can put your JavaScript file anywhere in page. But you should use window.onload method to start execution of your code.
<script>
window.onload = function(){
// start calling your function eg. functions.j();
};
</script>
If you invoke the function before its loaded, it doesn't know what to do. There are two solutions to this:
Use the window.onload option (or jquery $(document).ready(function(){ ... });
make the function call after you load the scripts.

Separating JQuery Scripts with Selectors in External file does not work?

I have a JQuery Selector and an event associates with it.I want to keep it in external file and just copy and directly save it. The thing which I see is that the external JavaScript that has the selector does not work. Can someone explain Why?
NOTE: I am able to use the same function within my HTML file but when externalize it. It just doesn't work .
The script that I have is as follows:-
$('#pervious').click(function() {
var presentSlide = $('.visible').attr('id');
var tempArr = presentSlide.split("-");
var persentSlideNo = tempArr[1];
var perviousSlideNo = Number(persentSlideNo) - 1; if (perviousSlideNo > -1)
{
var perviousSlide = "Slide-" + perviousSlideNo;
$('#' + presentSlide).fadeOut('slow',function(){
$(this).removeClass('visible').addClass('hidden');
});
$('#' + perviousSlide).fadeIn('slow',function(){
$(this).removeClass('hidden').addClass('visible');
});
}
});
How are you including this script?
Note that it needs to go below the definition of your id=pervious element, or it needs to go after it (e.g. document.ready), otherwise the element won't exist, and there won't be anything to bind to.
UPDATE
To restate, it needs to execute AFTER the pervious element gets created. Putting it in an external document is likely causing it to execute BEFORE the pervious HTML element is created, and therefore it doesn't work. You can put it in an external file, sure, just make certain that the element gets loaded, e.g.
$(document).ready(function() {
$.getScript('http://yoursite.com/extrascript.js');
});
After you have determined you are actually linking to it by doing an alert, wrap your code like so:
$(function(){
// place your code inside here for ready event
});
What you are doing is running your selector before the document is ready. The selector runs before the dom is there and there is no results in the selector so you don't attach anything.
You have to include scripts with the form of: (including the closure tag as such)
<script src="myexternal.js" type="text/javascript"></script>
Not any of these:
<script src="myexternal.js" type="text/javascript" />
<script src="myexternal.js" />
<script src="myexternal.js" ></script>
form or it will not always get rendered properly and thus not execute.
and of course, since you are using jQuery, you should put YOUR code AFTER the jQuery library link AND include your code in a document ready as others have demonstrated.

Categories