Initialize more than one html element using jQuery and Javascript - 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');
});
})

Related

load javascript after the html has rendered

The below script works perfectly fine if the p tag is placed above and script placed below
<p id="dom_intro">Hello</p>
<script>
x=document.getElementById("dom_intro");
document.write("<p>This is the text of dom intro" + x.innerHTML + "Howzzat </p>");
</script>
If the same code where the script is placed first and html p tag is placed below the script it does not work, I am getting error x is null or undefined
<script>
x=document.getElementById("dom_intro");
document.write("<p>This is the text of dom intro" + x.innerHTML + "Howzzat </p>");
</script>
<p id="dom_intro">Hello</p>
I tried pasting the script in external javascript file and placed at the head section
I am getting the same error. Is there any javascript or jquery script to load the javascript file after the html has rendred
jquery:
$(document).ready(){function(){
//yourcode
});
And Javascript
window.onload=function(){
//your code
}
The document ready in jquery executes the function when the DOM is ready, that means before some images are downloaded.
Window.onload is fired when page is completely ready, that is when all images are finished loading.
you need to access the element once the dom is ready. you are getting this error because your trying to access the p tag before the dom getting loaded.
this may fix your problem
window.onload = function(){
// your javascript here
x=document.getElementById("dom_intro");
document.write("<p>This is the text of dom intro" + x.innerHTML + "Howzzat </p>");
}
Browsers are rendering your code as they see it (lineary). The here problem is that your script tries to access something that doesn't exists yet so it's common practice to wait until all DOM elements are ready and then execute script.
Please look here: http://api.jquery.com/ready/
$(document).ready(function() {
// Handler for .ready() called.
});
Which is equivalent to calling:
$(function() {
// Handler for .ready() called.
});
The <script> content is executed where you place it, so in the second case, you are trying to use "dom_intro" before it is declared. But you're trying to load the javascript AFTER the html has rendered, so you don't want to write the script BEFORE the html content, right?
The usual way to load JS files are just before the </body> close tag. That way you'll be sure that any html won't be downloaded before all your HTML is loaded.
And if you want to wait for the HTML to finish loading before executing any JS, you must do something like this:
Plain javascript:
window.onload = function () {
// do_whatever_you_want
}
Jquery:
$(document).ready(function() {
// do_whatever_you_want
}

Call JS function with attributes from another file

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 :)

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.

jQuery not working in external JavaScript

I am new to jQuery and am stuck at some strange issue. I am using jQuery's change and click methods. They are working fine when used in my HTML file in the <script> tag.
Like:
<script>
$("select,input").change(function ()
{
// My code and some alerts
});
</script>
When I copied the same in external JavaScript code without <script> and imported that in my HTML it was not at all working.
Are there any changes which are needed to use jQuery in external JavaScript code?
PS: Some other non-jQuery functions present in same external JavaScript code are successfully called from HTML.
First off, you don't want a <script> tag in an external JavaScript file, if that's how I'm reading your post.
The trick with jQuery is that your code is set to execute immediately.
You want to wrap your script so that it loads when the document is ready, in something like:
$(document).ready(function(){
$("select,input").change(function ()
{
// My code and some alerts
})
});
And you want to make sure that your file is loaded after jQuery (otherwise the $ global will not be set).
Additions:
Here is what your HTML should look like:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script type="text/javascript" src="jscript/myExternalJs.js"></script>
Here is what your JavaScript code should look like (note there is no script tag inside the JavaScript file):
$(document).ready(function(){
$("select,input").change(function ()
{
// My code and some alerts
})
// Other event handlers.
});
As far as your other script... it sort of depends on what you're doing. The most important thing is to not try to hook event listeners up to objects that don't yet exist, which is why we use document.ready.
Did you make sure jquery is defined before your own jquery code?
You should also make sure the DOM is ready when dealing with jquery:
$(document).ready(function() {
$("select,input").change(function() {
// my code and some alerts
});
// more code here if needed, etc.
});

jQuery ready() and script sequence

I'm an jQuery noob and I'm wondering how fix this issue:
I have an external .js script, let's take reflection.js as example.
Reflection.js creates canvas reflection for every class="reflect" image.
I'm appending a few images trough different JS script that starts when ('document').ready.
Of course reflection.js doesn't work for images created by the script above.
How to avoid that?
I guess I'll need callback (?). Unfortunately I'm not getting idea of callbacks idea even after reading documentation.
[edit]
<script src="js/reflection.js" type="text/javascript"></script>
<script type="text/javascript">
jQuery().ready(function() {
jQuery('#thumbs li').each(function(){
jQuery('.'+id+' a').append('<img src="' + imgURL + '" class="reflect" /></a>');
});
});
</script>
Image loading events do not bubble. You cannot hook into those.
Since your images have the class "reflect" it means you have some control over the source. So I recommend your reflection code publishes an API for you to call.
window.Reflect = function(img) {
...
};
...
var img = $("<img></img");
img.attr({
...
});
Reflect(img);
...
If you do not want to do this then you can poll the document for new images.
(function poll() {
var images = $("img.reflect");
...
images.removeClass("reflect")
setTimeout(poll, 500);
})();
If I understand this correctly, you have 2 functions under "ready" sequence and one script depends on other.
The way how I solved this problem, I have build my own includeJS as well as additional ready-checking layer on top of the one which jQuery has.
https://github.com/atk4/atk4/blob/master/templates/js/start-atk4.js
So my code looks like this:
$(function(){
$.atk4.includeJS('reflection.js');
$.atk4.includeJS('different.js');
$.atk4(function(){
$('.reflect').reflection();
});
});
What happens is, after document is ready, jQuery launches above code. It appends 2 scripts and evaluates them (by adding tag). When evaluation is complete, function atk4.get will execute readiness chain very similar to how jQuery does it.

Categories