I am pretty new to JavaScript so I don't know the ins and outs of the language but I do have some knowledge of it. I created a self invoked function that would sort an array of zip-codes and then output it to a div element in the html file.
Unfortunately, the output isn't going into the div element because the function is executed before the html elements is ready, therefor it doesn't exist.
Is there anyway that I could access the div element within the function without having to use Window.Load, etc?
Thank you! click on the link below to view my function.
Screenshot of function
Is there anyway that I could access the div element within the
function without having to use Window.Load, etc?
Just move that code to the end of your html - after elements in question.
For example after </body>
From what I know, you can't access the DOM if it doesn't exist in that moment.
I know I know, don't use window.onload. But I assure you this is different than waiting for the DOM to load and then follow up with your calculations.
You can have a function evaluate something, then actually hang on the result and wait, and then finally fill the innerHTML when the DOMContentLoaded event has fired... or perhaps something of similar flavour, have a look at this.
<script>
const calculations = (function () {
// Super smart calculations...
var output = "Result of smart calculations";
function findWhereOutputGoes() {
return document.getElementById('output-div');
}
return {
output: output,
findWhereOutputGoes: findWhereOutputGoes,
}
})();
document.addEventListener('DOMContentLoaded', function(){ // Fires as soon as DOM has loaded
calculations.findWhereOutputGoes().innerHTML = calculations.output;
});
</script>
<div id="output-div">
</div>
Related
I have this ajax call that's suppose to run when a key is pressed on a specific textbox. Once in the call, it runs a function that fires an alert. But, its doesn't work. Maybe it's cause I wrote the call using an old forum post as reference. Assume, I called the jquery library cause on my test I did but I didn't post it here.
This is what I've tried so far:
<script>
$("#<% =tb.ClientID%>").keydown
(
function ()
{
debugger; alert("hello");
}
);
</script>
<body>
<asp:TextBox Id = "tb" runat = "server"/>
</body>
I'm new to these kind of calls. I'm very familiar with js functions, but I've never done this. Any explanations and suggestions, would be greatly appreciated.
HTML is processed line by line. So when it processes the contents of that script tag, it hasn't yet processed anything further down, such as the body tag or its contents.
Inside the script, you're running $("#<% =tb.ClientID%>"). It'll try to find an element by its ID, but since the body hasn't been processed yet, it will yield no results. With no results, it has nothing on which to set the listener for .keydown.
It's in cases like these that using jQuery's $(document).ready function or its equivalents becomes incredibly important and crucial to the code. $(document).ready accepts a function, and it will wait until the DOM is fully loaded before executing that code. So putting $("#<% =tb.ClientID%>").keydown.... inside of a $(document).ready will ensure that the element has a chance to enter the DOM before the .keydown listener is attached to it.
You can find the docs for $(document).ready() here.
I want to use boomrang framework in Jquery to get the bandwidth of the user's network which has to be displayed on the screen as "connection : fair/poor/good".
With on ready,on load, etc.., javascript function will be called only after the elements are ready to be accessed. But, I want the boomrang call to be called quite before that. Please tell me which event I have to use so that function call can happen before the elements of the page loads. Thanks in advance.<>
Note: I have tried by putting script tag at the top of the head tag. But still page elements are getting evaluated first (along with their el expressions).
If you want your function to be called before DOM creation then you dont need to call your function in any onload or on(document).ready, what you have to do is just call your function inside the script tag
For example (Script on the top of the page)
<script>
function abc()
{
// function desc
}
abc(); //Will be called as soon as the url is opened
$(document).ready(function()
{
abc(); // will be called when the DOM is ready
});
</script>
Use bw plugin from boomrang freamework
http://yahoo.github.io/boomerang/doc/howtos/howto-3.html
I have the following in my javascript file:
var divId = "divIDer";
jQuery(divId).ready(function() {
createGrid(); //Adds a grid to the html
});
The html looks something like:
<div id="divIDer"><div>
But sometimes my createGrid() function gets called before my divIder is actually loaded onto the page. So then when I try to render my grid it can't find the proper div to point to and doesn't ever render. How can I call a function after my div is completely ready to be used?
Edit:
I'm loading in the div using Extjs:
var tpl = new Ext.XTemplate(
'<div id="{divId}"></div>');
tpl.apply({
});
You can use recursion here to do this. For example:
jQuery(document).ready(checkContainer);
function checkContainer () {
if($('#divIDer').is(':visible'))){ //if the container is visible on the page
createGrid(); //Adds a grid to the html
} else {
setTimeout(checkContainer, 50); //wait 50 ms, then try again
}
}
Basically, this function will check to make sure that the element exists and is visible. If it is, it will run your createGrid() function. If not, it will wait 50ms and try again.
Note:: Ideally, you would just use the callback function of your AJAX call to know when the container was appended, but this is a brute force, standalone approach. :)
Thus far, the only way to "listen" on DOM events, like inserting or modifying Elements, was to use the such called Mutation Events. For instance
document.body.addEventListener('DOMNodeInserted', function( event ) {
console.log('whoot! a new Element was inserted, see my event object for details!');
}, false);
Further reading on that: MDN
The Problem with Mutation Events was (is) they never really made their way into any official spec because of inconcistencies and stuff. After a while, this events were implemented in all modern browser, but they were declared as deprecated, in other words
you don't want to use them.
The official replacement for the Mutation Events is the MutationObserver() object.
Further reading on that: MDN
The syntax at present looks like
var observer = new MutationObserver(function( mutations ) {
mutations.forEach(function( mutation ) {
console.log( mutation.type );
});
});
var config = { childList: true };
observer.observe( document.body, config );
At this time, the API has been implemented in newer Firefox, Chrome and Safari versions. I'm not sure about IE and Opera. So the tradeoff here is definitely that you can only target for topnotch browsers.
To do something after certain div load from function .load().
I think this exactly what you need:
$('#divIDer').load(document.URL + ' #divIDer',function() {
// call here what you want .....
//example
$('#mydata').show();
});
Through jQuery.ready function you can specify function that's executed when DOM is loaded.
Whole DOM, not any div you want.
So, you should use ready in a bit different way
$.ready(function() {
createGrid();
});
This is in case when you dont use AJAX to load your div
inside your <div></div> element you can call the $(document).ready(function(){}); execute a command, something like
<div id="div1">
<script>
$(document).ready(function(){
//do something
});
</script>
</div>
and you can do the same to other divs that you have.
this was suitable if you loading your div via partial view
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.
I have a question about javascript/html.
First, I have this:
var post = document.body.getElementsByClassName("post");
var x=post[i].getElementsByClassName("MyDiv")[0].innerHTML;
I get from the debugger that x is not defined, it doesn't exists.
This javascript function runs onload of the body. I am sure that I gave the right classnames in my javascript, so it should find my div.
So, I read somewhere that sometimes javascript does not find an element because it is not yet there, it is not yet created in the browser ( whatever that means).
Is it possible that my function can't find the div with that classname because of this reason?
Is there a solution?
So, I read somewhere that sometimes javascript does not find an element because it is not yet there, it is not yet created in the browser ( whatever that means).
Browsers create the DOM progressively as they get the markup. When a script element is encountered, all processing of the markup stops (except where defer and async have an effect) while the script is run. If the script attempts to access an element that hasn't been created yet (probably because its markup hasn't been processed yet) then it won't be found.
This javascript function runs onload of the body.
If that means you are using something like:
<body onload="someFn()"...>
or perhaps
<script>
window.onload = function() {
someFn();
...
}
</script>
then when the function is called, all DOM nodes are available. Some, like images, may not be fully loaded, but their elements have been created.
If it means you have the script in the body and aren't using the load event, you should move the script to the bottom of the page (e.g. just before the closing body tag) and see if that fixes the issue.
Okay, instead of calling functions with
body onload, use jQuery's ready() function, or, if you don't want to use jQuery, you can use pure javascript, but this is up to you:
// jQuery
$(document).ready(function() {
var post = document.getElementsByClassName("post"),
x = post[i].getElementsByClassName("MyDiv")[0].innerHTML;
});
// JavaScript
window.onload = function initialization() {
var post = document.getElementsByClassName("post"),
x = post[i].getElementsByClassName("MyDiv")[0].innerHTML;
}
A few side notes, I don't know what the use of innerHTML
is, and also if you're doing a for loop with i then definitely
post that code, that's kind of important.
After some discussion, my answer seems to have worked for you, but you can also place your script at the end of your body tag as #RobG has suggested.