How to call $(document).ready(function() {…}); from another file JS - javascript

I would like to know how to call the function below without refactoring from another js file.
$(document).ready(function() {
check();
function check () {
setTimeout(function(){
location.reload(true);
}, 10000);
}
});
I saw a question exist for this issue very old one but I cannot understand how to use the answer for my function.
StackOverflow answer from another question
I would like to see an example with my function and the proposed solution from the link.
My example which does not work correctly:
//= require rspec_helper
//= require background_index
//= require sinon
describe("Background Index, timeout after 10s", function() {
// Tweak for testing
var doc_ready = $.readyList[0]();
it ("Reload the location", function(){
clock = sinon.useFakeTimers();
var check = doc_ready.check();
var set_timeout = doc_ready.setTimeout();
/*var stub_check = sinon.stub(check, "check");
var stub_timeout = sinon.stub(timeout, "setTimeout");*/
timedOut = false;
setTimeout(function () {
timedOut = true;
}, 1000);
timedOut.should.be.false;
clock.tick(10010);
timedOut.should.be.true;
clock.restore();
});
});

This is re-written from the answer you pasted.
$(document).ready(check);
function check () {
setTimeout(function(){
location.reload(true);
}, 10000);
}
// In the test file
TestFile.prototype.testDocumentReadyContents = function () {
check();
}
A better way would be to include all the JS-files in your HTML with <script src="./path-to-file"> and then just call the functions in the order you want them to be called.

Related

How to pass variable asyncronously through different scripts

I can't figure out how to do it.
I have two separate scripts. The first one generates an interval (or a timeout) to run a specified function every x seconds, i.e. reload the page.
The other script contains actions for a button to control (pause/play) this interval.
The pitfall here is that both sides must be asyncronous (both run when the document is loaded).
How could I properly use the interval within the second script?
Here's the jsFiddle: http://jsfiddle.net/hm2d6d6L/4/
And here's the code for a quick view:
var interval;
// main script
(function($){
$(function(){
var reload = function() {
console.log('reloading...');
};
// Create interval here to run reload() every time
});
})(jQuery);
// Another script, available for specific users
(function($){
$(function(){
var $playerButton = $('body').find('button.player'),
$icon = $playerButton.children('i');
buttonAction = function(e){
e.preventDefault();
if ($(this).hasClass('playing')) {
// Pause/clear interval here
$(this).removeClass('playing').addClass('paused');
$icon.removeClass('glyphicon-pause').addClass('glyphicon-play');
}
else {
// Play/recreate interval here
$(this).removeClass('paused').addClass('playing');
$icon.removeClass('glyphicon-play').addClass('glyphicon-pause');
}
},
buttonInit = function() {
$playerButton.on('click', buttonAction);
};
buttonInit();
});
})(jQuery);
You could just create a simple event bus. This is pretty easy to create with jQuery, since you already have it in there:
// somewhere globally accessible (script 1 works fine)
var bus = $({});
// script 1
setInterval(function() {
reload();
bus.trigger('reload');
}, 1000);
// script 2
bus.on('reload', function() {
// there was a reload in script 1, yay!
});
I've found a solution. I'm sure it's not the best one, but it works.
As you pointed out, I eventually needed at least one global variable to act as a join between both scripts, and the use of a closure to overcome asyncronous issues. Note that I manipulate the button within reload, just to remark that sometimes it's not as easy as moving code outside in the global namespace:
Check it out here in jsFiddle: yay! this works!
And here's the code:
var intervalControl;
// main script
(function($){
$(function(){
var $playerButton = $('body').find('button.player'),
reload = function() {
console.log('reloading...');
$playerButton.css('top', parseInt($playerButton.css('top')) + 1);
};
var interval = function(callback) {
var timer,
playing = false;
this.play = function() {
if (! playing) {
timer = setInterval(callback, 2000);
playing = true;
}
};
this.pause = function() {
if (playing) {
clearInterval(timer);
playing = false;
}
};
this.play();
return this;
};
intervalControl = function() {
var timer = interval(reload);
return {
play: function() {
timer.play();
},
pause: function(){
timer.pause();
}
}
}
});
})(jQuery);
// Another script, available for specific users
(function($){
$(function(){
var $playerButton = $('body').find('button.player'),
$icon = $playerButton.children('i'),
interval;
buttonAction = function(e){
e.preventDefault();
if ($(this).hasClass('playing')) {
interval.pause();
$(this).removeClass('playing').addClass('paused');
$icon.removeClass('glyphicon-pause').addClass('glyphicon-play');
}
else {
interval.play();
$(this).removeClass('paused').addClass('playing');
$icon.removeClass('glyphicon-play').addClass('glyphicon-pause');
}
},
buttonInit = function() {
$playerButton.on('click', buttonAction);
interval = intervalControl();
};
buttonInit();
});
})(jQuery);
Any better suggestion is most welcome.

Passing functions between RequireJS files

I've got a file which needs to run on page load (randomise_colors.js), but also needs to be called by another file as part of a callback function (in infinite_scroll.js). The randomise_colors script just loops through a list of posts on the page and assigns each one a color from an array which is used on the front-end.
Infinite Scroll loads new posts in to the DOM on a button click, but because the randomise_colors.js file has already ran on page load, new content loaded is not affected by this so I need it to run again. I'm open to other suggestions if it sounds like I could be tackling the problem in a different way, I'm no JS expert.
Currently I'm getting Uncaught ReferenceError: randomise_colours is not defined referring this line of infinite_scroll.js:
randomise_colours.init();
I'm calling all files that need be loaded on document.ready in app.js
require(['base/randomise-colours', 'base/infinite-scroll'],
function(randomise_colours, infinite_scroll) {
var $ = jQuery;
$(document).ready(function() {
infinite_scroll.init();
randomise_colours.init();
});
}
);
This is infinite_scroll.js which initialises Infinite Scroll and features the callback. The callback function runs whenever new items are loaded in via AJAX using the Infinite Scroll jQuery plugin. I've put asterix around the area where I need to run the randomise_colors.init() function from randomise_colors.js.
define(['infinitescroll'], function() {
var $ = jQuery,
$loadMore = $('.load-more-posts a');
function addClasses() {
**randomise_colours.init();**
};
return {
init: function() {
if($loadMore.length >= 1) {
this.setUp();
} else {
return false;
}
},
setUp: function() {
this.initInfiniteScroll();
},
initInfiniteScroll: function() {
$('.article-listing').infinitescroll({
navSelector : '.load-more-posts',
nextSelector : '.load-more-posts a',
itemSelector : '.standard-post'
}, function(newItems) {
addClasses();
});
//Unbind the standard scroll-load function
$(window).unbind('.infscr');
//Click handler to retrieve new posts
$loadMore.on('click', function() {
$('.article-listing').infinitescroll('retrieve');
return false;
});
}
};
});
And this is my randomise_colors.js file which runs fine on load, but needs to be re-called again after new content has loaded in.
define([], function() {
var $ = jQuery,
$colouredSlide = $('.image-overlay'),
colours = ['#e4cba3', '#867d75', '#e1ecb9', '#f5f08a'],
used = [];
function pickRandomColour() {
if(colours.length == 0) {
colours.push.apply(colours, used);
used = [];
}
var selected = colours[Math.floor(Math.random() * colours.length)];
var getSelectedIndex = colours.indexOf(selected);
colours.splice(getSelectedIndex, 1);
used.push(selected);
return selected;
};
return {
init: function() {
if($colouredSlide.length >= 1) {
this.setUp();
} else {
return false;
}
},
setUp: function() {
this.randomiseColours();
},
randomiseColours: function() {
console.log('randomise');
$colouredSlide.each(function() {
var newColour = pickRandomColour();
$(this).css('background', newColour);
});
}
};
});
You would have to reference randomiseColours inside the infiniteScroll file. So you need to change your define function to the following:
define(['infinitescroll', 'randomise-colours'], function(infiniteScroll, randomise_colours)
Remember that when using require you need to reference all variables through the define function, otherwise they will not be recognised.

JavaScript/jQuery clearInterval being set in .each

So I have an interval I create for each of my posts, the issue is that I load new posts and remove the old ones, so obviously I'd like to stop the interval for the previous posts. However I can't seem to figure out how to do this. Could someone explain to me how to properly go about doing this? I'm completely lost.
$(".post").each(function(){
myInterval = setInterval("postStats('"+$(this).attr('id')+"')", 500);
});
function postStats(pid) {
//do some stuff
}
$(".button").click(function(){
clearInterval(myInterval);
});
You can store the interval ID in a data attribute:
$(".post").each(function () {
var that = this;
var myInterval = setInterval(function () {
postStats(that.id);
}, 500);
$(this).data("i", myInterval);
});
and clear the interval specific to each .post like so:
$(".button").click(function () {
// assuming the button is inside a post
clearInterval($(this).closest(".post").data("i"));
});
and like SiGanteng said, you should pass a function object to setInterval rather than a string, which only gets eval'd.
You need to keep one handle for each interval that you start:
var myIntervals = [];
$(".post").each(function(){
var id = $(this).attr('id');
var handle = window.setInterval(function(){
postStats(id);
}, 500);
myIntervals.push(handle);
});
function postStats(pid) {
//do some stuff
}
$(".button").click(function(){
$.each(myIntervals, function(i, val){
window.clearInterval(val);
});
myIntervals = [];
});

Javascript Conflict ajax mail and scriptaculous

I've added a javascript element I found in a guide. It is as follows
$(document).ready(function ()
{
$('.dropdownbutton').click(function ()
{
$.post("send.php", $(".mycontactform").serialize(), function (data)
{
});
$('#success').html('Message sent!');
$('#success').hide(2000);
});
});
The existing javascript was
function toggleDisplayWait(divId, imgId, durationmSec) {
if(!$(divId).visible()) {
move = Effect.BlindDown;
newImage = "./img/minus.png";
}
else {
move = Effect.BlindUp;
newImage = "./img/plus.png";
}
move(divId, {duration: durationmSec / 1000.0 });
setTimeout(function() { $(imgId).src = newImage; }, durationmSec)
}
function BDEffect(divId, imgId)
{
/* new Effect.BlindDown(element, {duration:3});
}*/
if(!$(divId).visible())
{
move = Effect.BlindDown;
newImage = "./img/feedbacktab_open.png";
setTimeout(function() { $(imgId).src = newImage; }, 0)
}
else
{
move = Effect.BlindUp;
newImage = "./img/feedbacktab.png";
setTimeout(function() { $(imgId).src = newImage; }, 2)
}
move(divId, {duration:2});
/*setTimeout(function() { $(imgId).src = newImage; }, 0)*/
}
</script>
But neither the OLD code nor the NEW code works now.
Error console now reporting "$(divId).visible is not a function" when i try to use the old script
The old code looks like it's using the Prototype framework, and the new code is using jQuery.
When you use the two together, you need to use jQuery's noConflict() so that they don't both try to use the $ variable.
First, after including the jQuery library, add a script like this:
<script>
jQuery.noConflict()
</script>
Then modify your jQuery code to look like this:
jQuery(function ($) {
$('.dropdownbutton').click(function() {
$.post("send.php", $(".mycontactform").serialize(), function(data) {});
$('#success').html('Message sent!');
$('#success').hide(2000);
});
With noConflict, everywhere you want to use jQuery, you must use the jQuery variable instead of $. However, you can still pass $ in as a local variable, and it will not conflict with Prototype.
Also, note that I changed your document.ready(function() { ... }) function into jQuery's shorthand version: jQuery(function() { ... }). The function will also get passed the jQuery object, which I name $ for convenience.

jQuery function attr() doesn't always update img src attribute

Context: On my product website I have a link for a Java webstart application (in several locations).
My goal: prevent users from double-clicking, i. e. only "fire" on first click, wait 3 secs before enabling the link again. On clicking, change the link image to something that signifies that the application is launching.
My solution works, except the image doesn't update reliably after clicking. The commented out debug output gives me the right content and the mouseover callbacks work correctly, too.
See it running here: http://www.auctober.de/beta/ (click the Button "jetzt starten").
BTW: if anybody has a better way of calling a function with a delay than that dummy-animate, let me know.
JavaScript:
<script type="text/javascript">
<!--
allowClick = true;
linkElements = "a[href='http://www.auctober.de/beta/?startjnlp=true&rand=1249026819']";
$(document).ready(function() {
$('#jnlpLink').mouseover(function() {
if ( allowClick ) {
setImage('images/jetzt_starten2.gif');
}
});
$('#jnlpLink').mouseout(function() {
if ( allowClick ) {
setImage('images/jetzt_starten.gif');
}
});
$(linkElements).click(function(evt) {
if ( ! allowClick ) {
evt.preventDefault();
}
else {
setAllowClick(false);
var altContent = $('#jnlpLink').attr('altContent');
var oldContent = $('#launchImg').attr('src');
setImage(altContent);
$(this).animate({opacity: 1.0}, 3000, "", function() {
setAllowClick(true);
setImage(oldContent);
});
}
});
});
function setAllowClick(flag) {
allowClick = flag;
}
function setImage(imgSrc) {
//$('#debug').html("img:"+imgSrc);
$('#launchImg').attr('src', imgSrc);
}
//-->
</script>
A delay can be achieved with the setTimeout function
setTimeout(function() { alert('something')}, 3000);//3 secs
And for your src problem, try:
$('#launchImg')[0].src = imgSrc;
Check out the BlockUI plug-in. Sounds like it could be what you're looking for.
You'll find a nice demo here.
...or just use:
$(this).animate({opacity: '1'}, 1000);
wherever you want in your code, where $(this) is something that is already at opacity=1...which means everything seemingly pauses for one second. I use this all the time.
Add this variable at the top of your script:
var timer;
Implement this function:
function setFlagAndImage(flag) {
setAllowClick(flag);
setImage();
}
And then replace the dummy animation with:
timer = window.setTimeout(function() { setFlagAndImage(true); }, 3000);
If something else then happens and you want to stop the timer, you can just call:
window.clearTimeout(timer);

Categories