Alert After jQuery Function is Finished - javascript

I'm trying very hard to figure out how to get a JS alert to appear only after a previous script (a glossary word replacement script) has finished. Getting this javascript/jquery to run in order is giving me a headache as it either runs out of order, or the second part doesn't run at all.
Here is the code that is presently working WITHOUT the alert:
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script src="jquery.zglossary.min.js" type="text/javascript"></script>
<script>
$(document).ready(function () {
$('body').glossary('listofwords.json');
//want alert('finished') to happen after glossary word replacement is finished replacing words here
});
</script>
</head>
I've tried a lot of different things trying to get an alert to happen where that comment is, and either the alert happens immediately before any words are replaced by the zglossary script, an example of that would be:
<script>
$(document).ready(function () {
$('body').glossary('listofwords.json');
alert('finished');
});
</script>
Or the script will replace all the words and no alert happens at all. An example of that would be:
<script>
$(document).ready(function () {
$('body').glossary('listofwords.json');
}, function() {
alert('finished');
});
</script>
Another example of that happening (words are replaced, but no alert happens) that I've tried would be:
<script>
$(document).ready(function () {
$('body').glossary('listofwords.json', function() {alert('finished');} );
});
</script>
I really just can't figure this out. I'd appreciate any help

I've never used this glossary plugin before - but I downloaded the source and I see the issue is clearly because the glossary plugin does not provide any callback after the JSON data is asynchronously downloaded. Any solution that is not hacky will require a slight modification to the library itself.
Here is a quick way you could do it
By adding this line
typeof options.callback == 'function' && options.callback();
At the end of the success: function(data) {
Then your code would simply be this:
<script>
$(document).ready(function () {
$('body').glossary('listofwords.json', {callback:function() {alert('finished');}} );
});
</script>
Which is similar to your last example, only it puts the callback into an options JSON which is what the plugin expects.

I have no idea what's "Glossary", but you might find a solution with Deferred object supplied by jQuery api. Deferred helps to handle json calls, especially the .done() method to set a caalback when the call is finished.

Related

Javascript document.ready in multiple files with Gulp [duplicate]

If I have a lot of functions on startup do they all have to be under one single:
$(document).ready(function() {
or can I have multiple such statements?
You can have multiple ones, but it's not always the neatest thing to do. Try not to overuse them, as it will seriously affect readability. Other than that , it's perfectly legal. See the below:
http://www.learningjquery.com/2006/09/multiple-document-ready
Try this out:
$(document).ready(function() {
alert('Hello Tom!');
});
$(document).ready(function() {
alert('Hello Jeff!');
});
$(document).ready(function() {
alert('Hello Dexter!');
});
You'll find that it's equivalent to this, note the order of execution:
$(document).ready(function() {
alert('Hello Tom!');
alert('Hello Jeff!');
alert('Hello Dexter!');
});
It's also worth noting that a function defined within one $(document).ready block cannot be called from another $(document).ready block, I just ran this test:
$(document).ready(function() {
alert('hello1');
function saySomething() {
alert('something');
}
saySomething();
});
$(document).ready(function() {
alert('hello2');
saySomething();
});
output was:
hello1
something
hello2
You can use multiple. But you can also use multiple functions inside one document.ready as well:
$(document).ready(function() {
// Jquery
$('.hide').hide();
$('.test').each(function() {
$(this).fadeIn();
});
// Reqular JS
function test(word) {
alert(word);
}
test('hello!');
});
Yes you can easily have multiple blocks. Just be careful with dependencies between them as the evaluation order might not be what you expect.
Yes it is possible to have multiple $(document).ready() calls. However, I don't think you can know in which way they will be executed. (source)
Yes it is possible but you can better use a div #mydiv and use both
$(document).ready(function(){});
//and
$("#mydiv").ready(function(){});
I think the better way to go is to put switch to named functions (Check this overflow for more on that subject).
That way you can call them from a single event.
Like so:
function firstFunction() {
console.log("first");
}
function secondFunction() {
console.log("second");
}
function thirdFunction() {
console.log("third");
}
That way you can load them in a single ready function.
jQuery(document).on('ready', function(){
firstFunction();
secondFunction();
thirdFunction();
});
This will output the following to your console.log:
first
second
third
This way you can reuse the functions for other events.
jQuery(window).on('resize',function(){
secondFunction();
});
Check this fiddle for working version
Yes you can.
Multiple document ready sections are particularly useful if you have other modules haging off the same page that use it. With the old window.onload=func declaration, every time you specified a function to be called, it replaced the old.
Now all functions specified are queued/stacked (can someone confirm?) regardless of which document ready section they are specified in.
Yes, it's perfectly ok.but avoid doing it without a reason. For example I used it to declare global site rules seperately than indivual pages when my javascript files were generated dynamically but if you just keep doing it over and over it will make it hard to read.
Also you can not access some methods from another
jQuery(function(){}); call
so that's another reason you don't wanna do that.
With the old window.onload though you will replace the old one every time you specified a function.
It's legal, but sometimes it cause undesired behaviour. As an Example I used the MagicSuggest library and added two MagicSuggest inputs in a page of my project and used seperate document ready functions for each initializations of inputs. The very first Input initialization worked, but not the second one and also not giving any error, Second Input didn't show up. So, I always recommend to use one Document Ready Function.
You can even nest document ready functions inside included html files. Here's an example using jquery:
File: test_main.html
<!DOCTYPE html>
<html lang="en">
<head>
<script src="jquery-1.10.2.min.js"></script>
</head>
<body>
<div id="main-container">
<h1>test_main.html</h1>
</div>
<script>
$(document).ready( function()
{
console.log( 'test_main.html READY' );
$("#main-container").load("test_embed.html");
} );
</script>
</body>
</html>
File: test_embed.html
<h1>test_embed.html</h1>
<script>
$(document).ready( function()
{
console.log( 'test_embed.html READY' );
} );
</script>
Console output:
test_main.html READY test_main.html:15
test_embed.html READY (program):4
Browser shows:
test_embed.html
You can also do it the following way:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#hide").click(function(){
$("#test").hide();
});
$("#show").click(function(){
$("#test").show();
});
});
</script>
</head>
<body>
<h2>This is a test of jQuery!</h2>
<p id="test">This is a hidden paragraph.</p>
<button id="hide">Click me to hide</button>
<button id="show">Click me to show</button>
</body>
the previous answers showed using multiple named functions inside a single .ready block, or a single unnamed function in the .ready block, with another named function outside the .ready block. I found this question while researching if there was a way to have multiple unnamed functions inside the .ready block - I could not get the syntax correct. I finally figured it out, and hoped that by posting my test code I would help others looking for the answer to the same question I had

How can I reliably run a jquery script after page load

I'm attempting to get some jquery code to run after a sharepoint page loads, the code being:
$(".ms-commentcollapse-icon").click();
I've been using the following to load the code after the page loads, but it does not seem to be very reliable (it will work sometimes and other times it wont):
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script type="text/javascript">
$(window).load(function () {
$(".ms-commentcollapse-icon").click();
});
</script>
are there any other good methods for achieving this? I'm not sure what's going on, sharepoint could be at fault, but I figured I would try fiddling around with the script a bit more first.
You could use an auto-executing function:
<script type="text/javascript">
(function () {
$(".ms-commentcollapse-icon").click();
} ());
</script>
If this is SharePoint 2010 or above, you can use ExecuteOrDelayUntilScriptLoaded(yourfunction,"SP.JS") to keep your code from firing until after the SP.JS library has loaded (or you can put any other library in the second parameter for a similar effect).
If this is in a web part and you don't want it to execute until other web parts on the page are fully loaded, make sure the web part containing the script is below the other web parts.
As a last resort, you could execute it on a delay using setTimeout or setInterval, but that's ugly.
You can prevent the default behaviour by using e.preventDefault(); within the function.
<script type="text/javascript">
$(".ms-commentcollapse-icon").click(function(e) {
// We're going to stop the default behavior
e.preventDefault();
//some code here
});
</script>

How to guarantee that a script in the middle of the body runs after all the DOM has finished load

In my <body> I have a component that inserts a script that is supposed to run only after all the page has completely loaded:
<script>
$('<script id="smallPlacarScriptdId">\
$(window).load(function() {\
$(".main.right").hide();\
$("#rightzero").show();\
$(".comp.smallPlacard.firstChild").click(function () {\
var clicked = $(this).parent().attr("id");\
$("main.right").hide();\
$("#right"+clicked+"").show();\
});\
})\
<\script>').appendTo("body")
</script>
That's not happening and this script (1) is correctly inserted into the DOM but (2) is not working (not hiding .main.right nor showing #rightzero).
I though that by using this approach I would guarantee that it would be the same as just put this script at the bottom of the <body> but it isn't. In fact if I put it (not dynamically like this) in my page it produces the desired result.
I tried setTimeout() to validate my theory but I'm getting an error in jQuery and I'm lost.
That might be the problem:
<\script>').appendTo("body")
Browser might think you are actually closing your script tag. Change it to
</' + 'script>').appendTo("body")
Check this plunker out: http://plnkr.co/edit/Oc6yrFMdPoW2WV257CBQ?p=preview
Just use this code
<script id="smallPlacarScriptdId">
$(window).load(function() {
$("main.right").hide();
$("#rightzero").show();
$(".comp.smallPlacard.firstChild").click(function () {
var clicked = $(this).parent().attr("id");
$("main.right").hide();
$("#right"+clicked+"").show();
});
})
</script>
Sorry I didn't read you question well enough.
Javascript will allow you to access undeclared variables, so use that to your advantage. Check if a variable is set, undefined is treated as a false so no need for initialization. As soon as you enter the code just set it to true so nothing else will execute.
Hopefully this solves the problem for you, but you really should look at from the server avoiding the javascript, it will bloat the page.
<script>
if (!myScriptHasLoaded)
{
myScriptHasLoaded = true;
$(window).load(function() {
$("main.right").hide();
$("#rightzero").show();
$(".comp.smallPlacard.firstChild").click(function () {
var clicked = $(this).parent().attr("id");
$("main.right").hide();
$("#right"+clicked+"").show();
});
});
}
</script>

GET Request is driving me to drink

So heres the deal. I've got an html file, with an id="followers". I'm trying to make a get request with jQuery to get the xml tag from the twitter api:
(http://api.twitter.com/1/users/show.xml?screen_name=nightoutinc
and update the id with the accurate info.
I'm not getting any console errors with my jquery, which leads me to believe everything is hooked up right, I'm just not implementing the get request properly.
My Jquery looks like this:
(function ($){
getFollowers = function(){
$.get("http://api.twitter.com/1/users/show.xml?screen_name=nightoutinc", function(data){
$("followers").follower_count(data);
});
};
});
my html head looks like this
<script type="text/javascript" src="javascripts/jquery.js"></script>
<script type="text/javascript" src="javascripts/getfollowers.js">
$(document).ready(function(){
getFollowers();
});
</script>
please tell me, what is wrong?!?
-brian
Looks like you have scope issues. And it doesn't look like your function is being called; only defined. Try wrapping it up into one parent function that actually gets called.
(function($) {
function getFollowers() {
// Implementation here.
}
$(document).ready(function() {
getFollowers();
});
})(jQuery);
Your jquery object selecter seems wrong
$("followers")
Should be
$("#followers")
Notice the pound sign which indicates ID
did you define follower_count?
I guess it should be $("followers").html(data); NOT $("followers").follower_count(data);
You said the response was XML right? Then data is going to be an XML DOM not a string or HTML you can jsut insert into your page.
I can only find the docs for JSON but assuming the XML has parity:
$(function(){
$.get('http://api.twitter.com/1/users/show.xml?screen_name=nightoutinc', function(xml){
nbFollowers = $(xml).find('followers_count').text();
$('#followers').html(nbFollowers ? nbFollowers : 0);
});
});

Javascript injection after domready event is fired

I'm working in a Joomla environment but I think this is not the source of the problem.
I have a view which renders subviews (containing JavaScript code like <script type="text/javascript></script>) with AJAX. Problem is : the JavaScript code is ignored. I guess that's because it isn't in the document when it is loaded.
Here's the JavaScript code contained in one of the subview :
<script type="text/javascript">
window.addEvent('domready', function() {
$('annuler').addEvent('click', function() {
var a = new Ajax(
'{$url}',
{
method: 'get',
update: $('update')
}
).request();
});
});
</script>
Another basic example, if I load a subview with the following code in it, it won't work either :
<script type="text/javascript">
function test()
{
alert('ok');
}
</script>
<a id="annuler" onclick="test()">Annuler</a>
I'm getting the following error message : "test is not defined"
I can't find a solution to that problem so I'm starting to think that it is not a good way to use JavaScript...and, yes, I'm kind of new to event based JavaScript (with frameworks and so on).
I finally managed to put all the subviews and the JavaScript code into the same page. I'm using the CSS display property to hide/show a subview (<div>) (instead of loading it with Ajax).
Place the code you want to run in a function and call the function from an on ready block
EDIT:
Example:
$(document).ready(function() {
// put all your jQuery goodness in here.
});
Found here: http://www.learningjquery.com/2006/09/introducing-document-ready

Categories

Resources