Javascript: change CSS element if jquery GET failed - javascript

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
}

Related

Notify JS with element Selector Doesn't works 100%

I'm using Notify JS from here :
http://notifyjs.com/
And this is my HTML :
<div>
<p><span class="elem-demo">aaaa</span></p>
<script>
$(".elem-demo").notify(
"Hello Box",
{
autoHide:false
}
);
</script>
</div>
It doesn't work correctly. I can see the arrow, but not the message.
I've check using my browser "inspect element", the class notifyjs-container has "display:none" and when i try change it into "display:inline" via my own css, the message does appear, but without its animation.
Anybody can help ?
Here I attach the image of the small arrow i said earlier :
You need to put the notify setup inside the doc ready, ie:
$(function() {
$(".elem-demo").notify("Hello");
});
What is happening is that the .notify() script is running before the page has fully rendered, so the .elem-demo does not yet exist when $(".elem-demo") tries to find it, so the .notify() has nothing to attach itself to.
$(function() { ...
is shorthand for
$(document).ready(function() { ...
which is jquery's way of saying - don't run this script until the page elements have completely finished loading.
It's generally a good idea to put all your scripts into a ready function like this (multiple $(function() { ... can be called, they don't need to be all in the same one).
More info on the jquery learning page: https://learn.jquery.com/using-jquery-core/document-ready/

modify CSS of elements created via .load()

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.

Inserting html in div with JQuery removes Anchor tags

Im trying to do something that should be very simple yet my head is about to explode considering I cannot get it to work.
In my asp.net MVC app, I make an Ajax call to the server, and the server sends back a message (as a string), which includes a link.
The message basically looks like this : Action failed, Learn more..
I am inserting this returned message in a div that shows the alerts from the server.
However, whatever I try, the 'Learn more.' part will never be inserted.
If I do alert(returnedMessage), it shows the correct html, but as soon as I do
$(mydiv).html(returnedMessage), the anchor-tag is gone. I tried unescaping, normal jscript innerHtml...not sure what I'm missing.
Thanks!
**UPDATE with some extra code **
I have the ajax call that returns a message. I have a method that then sets the message into the div and shows the alert.
the ajax call handling:
success: function (result) {
if (result.Message) {
showAlert(result.Message);
}
},
The javascript:
function showAlert(message) {
// neither setting the actual div, nor the span works
alert(message);
$('#server-message').html(message)
//$('#server-message span').html(message);
$('#server-message').fadeIn(100);
};
the html:
<div id="server-message">
<span></span>
</div>
also worth trying if you are escaping the double quotes properly :)
var returnMessage = 'Learn more.';
You should your message to .html() function $(mydiv).html(returnedMessage) if you doing $(mydiv).html = you only overwriting html property in this object.

Div is not created before javascript run

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.

JQuery load() will break facebook like button/comment box. How to workaround?

I am coding a big website but I have cut down my problem into the following tiny html file:
http://dl.dropbox.com/u/3224566/test.html
The problem is that if I (re)load with JQuery a content that features a facebook code, the latter won't appear, even if I reload the script (leading to a duplication of that all.js script, which is another issue).
How can I fix this?
Regards,
Quentin
Use the FB.XFBML.parse() docs after you load the new content
function loadPage() {
$('#test').load('test.html #test', function() {
FB.XFBML.parse( );
}).fadeOut('slow').fadeIn('slow');
}
Note, that loading a fragment with id test in a div with id test will create multiple (two) elements with the same id (nested in each other) in the page, which should never happen as it is invalid.
To avoid this use the more verbose $.get method
$.get('test.html',
function(data) {
var temp = $('<div>').html(data).find('#test');
$('#test').html(temp.html());
}
);

Categories