Cannot load HTML in a div that was ajax'd in - javascript

Good afternoon, I am at a total loss on why this is happening. I have searched online and tried to understand what I'm doing wrong for 5+ hours and could find no solution. Here is the situation.
I have 3 pages (index.html, index.js, and stuff.html)
index.html is the main page and uses jQuery to load an HTML page into a div.
<html>
<head>
<script type="text/javascript" src="index.js"></script>
</head>
<body>
<div id="stuffHolder"></div>
<script type="text.javascript">
$(document).ready(function(){
$('#stuffHolder').load('stuff.html');
});
</script>
</body>
</html>
The stuff.html page loads just fine for me.
Inside the stuff.html I have 2 div's
1. One of the DIV's uses sprites as anchor tags to call a function named actOnStuff(options).
<div id="myStuff"><a class="myStuffSprite" href="Javascript:actOnStuff('newStuff')"><span>New Stuff</span></a></div>
<div id="yourStuff"><a class="yourStuffSprite" href="Javascript:actOnStuff('oldStuff')"><span>Old Stuff</span></a></div>
The other DIV is empty but will have innerHTML written to it later.
Inside index.js, which sits on the index.html page, I have a function
function actOnStuff(youSelected){
strHTML = "";
switch(youSelected){
case "newStuff":
strHTML += "<div id='newDIV'><span>You selected New</span></div>";
break;
case "oldStuff":
strHTML += "<div id='oldDIV'><span>You selected Old</span></div>";
break;
}
$('#placement').html(strHTML);
alert($('#placement').html());
}
My problem is that when I alert the innerHTML of the placement DIV it shows that the necessary DIV from the function as added in the alert. HOWEVER, nothing shows up in the placement DIV at all.
Any help you can provide would be wonderful as I am at a total loss as to what the problem is. Thanks in advance.

I'm not sure I can help solve the actual problem, but there's many issues and bad practices in your code that I'd like to point out for the greater good of the community.
Here's my take on your code:
HTML in body
<div id="stuff-holder"></div>
HTML in stuff.html
<div id="my-stuff">
<a class="my-stuff-sprite" href="#"><span>New Stuff</span></a>
</div>
<div id="your-stuff">
<a class="your-stuff-sprite" href="#"><span>Old Stuff</span></a>
</div>
Bad practice: CSS and HTML is most of the time not case-sensitive, so when naming IDs with camelcase such as fooBar, could create confusion with foobar or Foobar. Instead, use lowercase only and dash as separator (like in CSS).
JavaScript in index.js
I moved your ready function into index.js. I don't see a reason why you would want that in your HTML document when you already have a separate JavaScript file.
// Shorthand for ready
$(function(){
// Cache the selector
var $placement = $("#placement");
// Put function in the local scope so we don't clutter the global scope
function actOnStuff(youSelected) {
// Not declaring variables with var, makes it global (bad idea!)
var html = "";
switch (youSelected) {
case "my-stuff":
html += '<div id="new-div"><span>You selected New</span></div>';
break;
case "your-stuff":
html += '<div id="old-div"><span>You selected Old</span></div>';
break;
}
// Put new html in placement element
$placement.html(html);
// Use console.log to debug your code instead of alert
console.log($placement.html());
}
// Load stuff into stuff holder and bind event handler to load event
$("#stuff-holder")
.load("stuff.html")
.on("load", function() {
// After it has loaded, bind click events
$("#my-stuff .my-stuff-sprite, #your-stuff .your-stuff-sprite").click(function(e) {
// Prevent default click behavior
e.preventDefault();
// Get id of parent
var id = $(this).parent()[0].id;
// Execute function
actOnStuff(id);
});
});
});
Bad practice: Executing JavaScript within the href is a big no-no in todays environments. Even using onclick attributes et al is since long outdated.
Tip: Passing a function directly into jQuery is a shorthand for $(document).ready
Tip: Use console.log() instead of alert() to output everything from objects to strings to your log (might give you errors in older IE)
I still don't know where your placement element is located. Perhaps that's your culprit? If you have any questions about the above or anything else, don't hesitate to ask.
Also, check out jQuery Fundamentals which is a great resource for everyone using jQuery, from beginners to pros.
Edit: Check this jsFiddle for a demonstration of the above.

before
<script type="text/javascript" src="index.js"></script>
you should load jquery library first
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="index.js"></script>

Make sure you only have ONE element with id="placement", IE will fail if you have more than one.
Also what is the output of alert(strHTML); putted just before $('#placement').html(strHTML); does it output the string right?

Related

Alternative to hide/show content with JS?

is there a better way to replace this kind of js function by simply collapse/toggle a div and show/hide its content?
$(function() {
$('#destselect').change(function(){
$('.dest').hide();
$('#' + $(this).val()).show();
});
});
The reason this is happening is because your js file is called on the head of your page.
Because of this, when you document.getElementsByClassName('collapsible');, colls result in an empty array, as your elements in body are not yet created.
You could either create a separate js file and add it at the end of your body (in that way you make sure your colls are created when your javascript is executed), or just wrap your code on a DOMContentLoaded event listener that will trigger your code once the document has completely loaded.
My guess would be that you are loading your script before browser finishes loading dom conetent and so when it runs the elements it is trying to add event listeners to, don't yet exist.
Try wrapping all you javascript in that file in this:
document.addEventListener("DOMContentLoaded", function(event) {
// all your code goes here
});
The above makes sure that your script is run after loading all elements on the page.
You could add a script tag to the header of your HTML file, this will import the JS file into your current page as follows
<script src="File1.js" type="text/javascript"></script>
Then call the function either in onclick in a button or in another script (usually at the bottom) of your page. Something like this:
<body>
...
<script type="text/javascript">
functionFromFile1()
</script>
</body>
Seems like your script is not executing properly due to a missing variable.
In this script https://www.argentina-fly.com/js/scripts.js
Naves variable in function UpdateDetailsDestination() is not defined.
I think you should resolve this first and then check your further code is working on not.
Please take a look into Console when running page. You'll see all JavaScript related errors there.

Access HTML element later in document through JavaScript

I am just starting out with JavaScript and I have a simple code that sends a value to an element with id p. I am currently declaring this function in a <script> in the <head> element of my document.
function writeP(resultSet) {
document.getElementById('p').innerHTML = resultSet.length;
};
writeP(results);
When I have this listed within the <head> element and run the webpage, firebug throws this error at me: TypeError: document.getElementById(...) is null.
However, if I move the code block into a <script> tag beneath the element and then reload the webpage, no problems and the script works as it should. Is there any reason for this, and a way I could make this work so I wouldn't have to define my functions beneath the element or include a onload on my body element?
Thanks for your help
Reason is that by the time your launch js code, DOM is not yet prepared, and JS can't find such element in DOM.
You can use window.onload (docs on W3schools) trigger to fire your functions after all elements are ready. It's same as having onload property on body element, but is more clear, as you can define it in your js code, not in html.
JS evaluates syncronically. Therefore, it does matter WHEN you declare the function. In this case, you're declaring it before the element actually exists.
Second, when you declare a function with that syntax, it does get eval'd inmediately. If you declared, instead
var writeP=function(resultSet) {
document.getElementById('p').innerHTML = resultSet.length;
};
you could save just the call to the end of the Doc, and leave the declaration at the beggining.
However, I would advise you to read a few jQuery tutorials to learn easier ways to deal with dom manipulation. Nobody runs raw JS for that task anymore.
jQuery includes an useful call to document ready event, which will save you a lot of headaches and is -IMHO- more efficient than the onload event. In this case, you would include the jQuery library somewhere in your code
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
and then add
<script>
jQuery(document).ready(function() {
var writeP=function(resultSet) {
jQuery('#p').html(resultSet.length);
};
writeP(resultSet);
});
</script>
just about anywhere in your document or an external js file, as it suits you.

HTML & JS Markup - better way possible?

I'm loading my html files into a #content div in order to avoid the complete page to reload when clicking on a link. I'm doing this by calling the following in my index.html:
[...]
<div id="content">
<script type="text/javascript">$("#content").load("home.html");</script>
</div>
The problem is that no javascript in my global.js will be executed if it's related to one of the html files that will be loaded into my #content div.
In order to handle that fact I simply put the js of the related html file right into that specific one by posting it with the <script> command, e.g. like this:
<script type="text/javascript">
$(document).ready(function () {
$(".faq").click(function () {
$(this).find(".faq_answer").toggle();
});
});
</script>
I'm totally unhappy with it and so my question is: is there a way I could put my js back in my global.js file?
If I understand correclty your question, you need to use even delegation to assign event handlers to elements that doesn't exist yet
$(document).on("click",".faq", function (){ ... })
Where document can be replaced by any container of .faq that exists at bind time.
For more details check "Direct and delegated" section here
Try to load the page through your global.js inside of keeping it in your html page.
Keep the script that will load the content first.
This should work

executing javascript function from HTML without event

I wish to call a javascript function from an HTML page and I do not want it dependent on any event. The function is in a separate .js file since I wish to use it from many web pages. I am also passing variables to it. I've tried this:
HTML:
<script type="text/javascript" src="fp_footer2.js">
footerFunction(1_basic_web_page_with_links, 1bwpwl.html);
</script>
The function in fp_footer2.js:
function footerFunction(path, file) {
document.write("<a href=" + path + "/" + file + " target='_blank'>Link to the original web page for this assignment.</a>");
return;
}
(I have also tried putting the fp_footer2.js file reference in the header, to no avail. I'm not sure if I can put it 'inline' like I did in this example. If not, please let me know.
PS: I know I can do this with a simple 'a href=""' in the HTML itself. I wanted to see if this could work, for my own curiosity.
If a <script> has a src, then the external script replaces the inline script.
You need to use two script elements.
The strings you pass to the function also need to be actual strings and not undefined variables (or properties of undefined variables). String literals must be quoted.
<script src="fp_footer2.js"></script>
<script>
footerFunction("1_basic_web_page_with_links", "1bwpwl.html");
</script>
JavaScript will run while your page is being rendered. A common mistake is to execute a script that tries to access an element further down the page. This fails because the element isn't there when the script runs.
So includes in the <head> will run before any DOM content is available.
If your scripts are dependent on the existence of DOM elements (like a footer!) try to put the script includes after the DOM element. A better solution is to use the document ready event ($(document).ready() in jQuery). Or window.onload.
The difference between documen ready and window onload is that document ready will fire when the DOM has been rendered; so all initial DOM elements will be available. Where as window onload fires after all resources have loaded, like images. window onload is useful if you're doing things with those images. Usually document ready is the right one.
Maybe I misunderstand your question, but you should be able to do something like this:
<script type="text/javascript" src="fp_footer2.js"></script>
<script type="text/javascript">
footerFunction(1_basic_web_page_with_links, 1bwpwl.html);
</script>
Have you tried calling it from a document.ready?
<script type="text/javascript">
$(document).ready(function() {
footerFunction(1_basic_web_page_with_links, 1bwpwl.html);
});
</script>

How to set the value for an HTML element from external javascript

I'm using an external javascript file (eg:myjs.js) with function setval() to set the innerText property of a HTML lable.
I have PHP page with <lable id="abc"></lable> and I have included myjs.js in <head> section. myjs.js is included in <head> section of one more PHP file and I'm calling setval() from this file, so when it runs it must set the innerText of lable in the first PHP file.
Is it possible to achieve? Any suggestions are greatly appreciated.
I hope I made question clear.
Thanks
Ideally, move your include of myjs.js to the bottom of the page (just before or after the closing </body> tag). Then it's just:
document.getElementById("abc").innerText = /* ...the text */;
Live example | source
If you can't move the include for some reason, you can put the above code in a function, e.g.:
function updateTheLabel() {
document.getElementById("abc").innerText = /* ...the text */;
}
...and then put this script just after the label:
<label id="abc"></label>
<script>
updateTheLabel();
</script>
Live example | source
If you don't want to do that (and it's a bit ugly, mixing script tags into your markup like that), you could wait for some kind of event that occurs when the page is ready. Search for "javascript dom ready event" and you'll see a lot of discussion of this, and lots of solutions. If you're using a library jQuery, Prototype, or any of several others, odds are high (but not 100%) that the library will have something for you. You probably don't want to wait for the window load event, because that fires very late in the page load process (after all external resources — images and such — are loaded).
(Can't do a live example of the above without knowing what library, if any, you're using; but again, there are dozens of "dom ready" solutions out there.)
Or I suppose worst case, you could poll, using this in myjs.js:
function updateTheLabel() {
var elm = document.getElementById("abc");
if (elm) {
elm.innerText = /* ...the text */;
}
else {
setTimeout(updateTheLabel, 50);
}
}
setTimeout(updateTheLabel, 0);
Live example | source

Categories

Resources