modify CSS of elements created via .load() - javascript

First time using jQuery. I'm using it to load the content of an external element onto my page. It loads fine, but I'm finding that the normal traversal methods don't work on the loaded elements. For instance, what I have is:
<div id="area"></div>
<script type="text/javascript">
$("#area").load("externalPage.html #externalElement > *");
$("#area").find("ul").first().css("display","none");
</script>
The second line of the script appears to do nothing. Does this have something to do with the order in which operations are completed?
I'm loading this into a custom HTML module on the Blackboard LMS, which can sometimes behave strangely if scripting gets too complicated, so this could very well be another one of those times. Thank you for helping me figure it out!

The call to load() is asynchronous. This means that your find() is being run before the request completes and the elements are created in the DOM.
To workaround this you can put your logic in the callback parameter of load(). This means that it will not be called until the request completes and the DOM is in the state you expect. Try this:
$("#area").load("externalPage.html #externalElement > *", function() {
$("#area").find("ul").first().css("display","none");
});

.load() has a callback for when it's done. You can do what you want to the new markup in there.
$("#area").load('foo.html', function () {
/* Now you have access to foo.html's markup */
});

You need to put that second line in the callback to .load():
$("#area").load("externalPage.html #externalElement > *", function() {
$("#area").find("ul").first().css("display","none");
});
Things like $.get() and $.fn.load() are convenience functions built on the basic jQuery $.ajax() system. The process of loading content is inherently asynchronous.

Related

Ajax call not running onKeydown

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.

Javascript: change CSS element if jquery GET failed

I have a Javascript in my header that calls an external server to retrieve some information, like this:
$.getJSON("https://domain.tld/json/", function (something) {
var results = //stuff that formats the result, not relevant here;
window.$info = results;
}).fail(function(){
// here's where I need the code to make the warning appear
});
Then in the body I have a warning that should pop up in case the GET request failed:
<div id="warning">Warning text</div>
Problem: the javascript is in the header and I can't change the "warning" div because it has not been created yet.
If I use document.getElementById("warning").style.display='block'; I get an error message saying it is null.
So how do I use the .fail() part of the jquery GET function to make the warning div appear (that is created later) in case the GET function has failed? Or is that not possible? And some 'solution' I tried (don't remember what exactly) even delayed the loading of the whole page. I'd like to avoid that as well.
Thank you for helping me out.
You should hide your html element initialy
<div id="warning" style="display:none;">Warning text</div>
And you can call show() method to display hidden element when get request failed
$("#warning").show();
Your javascript is trying to execute and look for things before the DOM has loaded. You can solve this problem by making sure your javascript only fires when the DOM is ready. In jQuery you do that like this:
$(document).ready(function(){
//your code here
});
The native javascript version of this is much more complicated so I won't post that here. However you could also wait for the entire page to load before executing the code like so:
window.onload = function(){
//your code here
}

I want to make sure function comes after loading of external HTML

How do I make sure the alert comes after the loading of the external HTML?
function changeContent(){
$('#contentmain').load("contentmain.html", function(){
alert("something");
}
)}
I've been playing around with $(document).ready, but no luck so far.
Many thanks!
Update:
The result of this code is that it depends (on what, I don't know): sometimes the alert comes first, sometimes it comes second...
Your code is right.
From the jquery documentation:
Callback Function
If a "complete" callback is provided, it is executed after post-processing and HTML insertion has been performed. The callback is fired once for each element in the jQuery collection, and this is set to each DOM element in turn.
are you loading iFrames?
try the .load() function.
$('#iframeID').load(function(){
// I am totally loaded and lets begin the hunt now.
});
Alternatively, If you are loading content via ajax, you can use .ajaxComplete
$(document).ajaxComplete(function(){
// ajax call has completed and lets begin the hunt now.
});

extend jquery load() function to show spinner inside div

is there a way to alter .load behavior so that it load a spiner inside any div that is loading data ?
example
<div class='content lside'></div>
<script>
$(document).ajaxStart(function() {
$('body').append('<div class="notice" style="position:fixed;top:40%;left:30%;z-index:99999;"id="loadingspin">loading</div>'); });
$(document).ajaxStop(function() {
$('#loadingspin').fadeOut().remove();
});
$('.content').load("<?=base_url();?>booking/<?=$day?>");
</script>
i use above script.
but what i actually want is that when ever ajaxstart the content of $('.content') is replaced with spinner until it finish loading the new content.
so is there a way i can extend .load to do that by it self and replace the ajaxstart,
so where ever $(div).load() is called a $(div).html('spiner'); is fired.
if not, is there a way .ajaxstart can reference the div that the content will be loaded into ?
please note: im currently using .ajaxstart and .ajaxstop in my header script in all my webpage to handle showing the spinners in general, but i want to replace it/extend it with div specific solution that would still work on any page without further editing into each and every ajax request.
thanks
probably something like this should do the trick. Override jQuery's prototype and save the old function.
(function(){
var oldLoad = jQuery.fn.load;
jQuery.fn.load = function( url, data, complete ){
/*
* do your stuff
*/
oldLoad.call( jQuery, url, data, complete );
}
})();
That changes the globally available jQuery.load() method for the whole page so »your stuff« should be executed even if other scripts call that method, a least after your re-definition of that function is parsed.

Execute $(document).ready() after $.load(), is that possible or is there an Alternative

I have page with a form and a table (to show results of the saved data using the form).
The form uses ajax to submit the data, data saved and the table should be reloaded afterwards.
The problem is that the table (which is loaded using AJAX($.load)) is loaded after the execution of $(document).ready(). which implies that the table does not have the required functionality.
Is there any approach where i can postpone the execution of $(document).ready() until the AJAX finish its loading, or shall i use a complete different approach like using iframe?
below is an example of my problem:
$(document).ready(function(){
//some code here that needed for the html in table.html e.g. datepicker, chosen, jqueryui, etc
});
<form>
//Inputs with a button to submit using ajax, where the result is displayed using table.php
</form>
<div id="tableOfContent"></div>
<script>
$('#tableOfContent').load("table.php");
</script>
You can do
$('#tableOfContent').load("table.php",function(){
//completed load actions here
});
But you should note that if you load images, they will not be loaded yet. If that is the case, you can make the contents of table.php initially hidden and do the same again inside for $('#tableOfContent img').load(). This would work for 1 image; multiple images is a bit more complicated, but feel free to ask if that is what you are looking for :)
You can delay the ready event using jQuery.holdReady():
$.holdReady(true);
// Do your custom stuff... the document may already be loaded.
$.holdReady(false); // Now the ready event will fire as soon as the DOM is loaded.
See http://api.jquery.com/jQuery.holdReady/
document.ready is called when the HTML of the page has finished loading, there's no two ways about it.
What you can do, however, is use live binding, which will attach handlers to elements that are not yet on the page.
Example:
$(".datepicker").live("click", function() {
$(this).datepicker();
})
Updated for jQuery >1.7 (this is also faster)
$("#tableOfContent").on("click", ".datepicker", function() {
$(this).datepicker();
})
Load the table data from within the ready function and use the complete event of the load() function to call the remainder
$(document).ready(function() {
// click bindings etc ..
$('#tableOfContent').load("table.php",function() {
// things to do once the table is loaded
});
});
load() documentation
$(document).ready() should be used for scripts that should execute, well, when document is ready.
If you need to execute something after an ajax call, you may write everything within a function and call it with the ajax callback.
function what_i_need() {
// bla bla
}
<script>
$('#tableOfContent').load("table.php", {}, what_i_need);//code had syntax error; '{)'
</script>
I'm not sure. Plus, you can call the function when document is ready too.
$(document).ready(function(){
what_i_need();
});

Categories