Call a function after loading an URL - javascript

I want to execute a certain function after an specified URL loads.
I tried to set an interval to detect the url I want, but it isn't working so far.
here's the code I have for calling the function:
pub.startup = function() {
var currURL = window.top.getBrowser().selectedBrowser.contentWindow.location.host;
window.setInterval(currURL, 1000);
if (currURL == 'www.google.com')
FunctionToCall();
}
Hope to get some help.

pub.startup = function() {
function checkCurrURL() {
var currURL = window.top.getBrowser().selectedBrowser.contentWindow.location.host;
if (currURL == 'www.google.com')
FunctionToCall();
}
window.setInterval(checkCurrURL, 1000);
};

window.setInterval expects a function (or arbitrary code) to execute. You supply it with a variable, which won't work.
See https://developer.mozilla.org/en/window.setInterval

Related

Avoid Jquery self calling function

I got below a Jquery function to switch between two buttons simultaneously but it's a "dirty" way of writing the code my boss will say. I don't wanna call the functions or no passing in Jquery parameter, is the there a simple or better way to write this function since i'm totally new to programming?
Below the Jquery
var startStopBtn = function () {
var startBtn = $('#timerStart');
var stopBtn = $('#timerStop').hide();
var Start = function () {
startBtn.hide();
stopBtn.show();
};
var Stop = function () {
var remarks2 = $(".textArea-one").val();
if (remarks2 !== "") {
startBtn.show();
stopBtn.hide();
}
};
return {
Start: Start,
Stop: Stop
};
}(jQuery);
jQuery('#timerStart').on('click', startStopBtn.Start);
jQuery('#timerStop').on('click', startStopBtn.Stop);
I think code could be done in many ways, this is just one of them.
Looks like first you want to hide the stopBtn so create a function to do this. Call that function on page load or create a funtion and call it when the page loads. Here I create a function that you should call whenever you want. If you don't want to do that, just delete that function.
Then make two diferent functions that are done when you "click" #timerStart or #timerStop.
This is my version but i'm sure it can be improved:
function startStopBtn(){
$('#timerStop').hide();
};
$('#timerStart').on('click', function(){
$('#timerStart').hide();
$('#timerStop').show();
});
$('#timerStop').on('click', function(){
var remarks2 = $(".textArea-one").val();
if (remarks2 !== "") {
$('#timerStart').show();
$('#timerStop').hide();
}
});

setInterval function only running once

I am currently playing about with the LastFM API and trying to get a Recently Played Tracks list to update as I play tracks through Spotify and ITunes. I have got the initial code working through a combination of JS and Handlebars so that a static list of tracks is loaded in on page load which is current at the time of page load.
However I want the list to update as I select a new track without refreshing the page. So I thought I could just use a setInterval function to call my original function every 5 seconds or so. However for some reason my setInterval function is only running once on page load.
I know that this is a real simple error but I can't work out why? Help!!
var clientname = {};
clientname.website = (function(){
var
initPlugins = function(){
var setupLastFM = (function(){
/* Create a cache object */
var cache = new LastFMCache(),
/* Create a LastFM object */
lastfm = new LastFM({
apiKey : '6db1989bd348bf91797bad802c6645d8',
apiSecret : '155270f02728b1936ed7699e9f7b8de9',
cache : cache
}),
attachTemplate = function(data, handlebarsTemplateID){
var template = Handlebars.compile(handlebarsTemplateID.html());
$(".container").append(template(data));
}
/* Load some artist info. */
lastfm.user.getRecentTracks({user: 'jimmersjukebox'}, {
success: function(data){
var trackData = data.recenttracks.track,
tracks = $.map(trackData, function(track) {
if(track['#attr']){
var isCurrentTrack = true;
}
return {
currenttrack: isCurrentTrack,
song: track.name,
artist: track.artist['#text']
};
});
attachTemplate(tracks, $("#trackInfo"));
}, error: function(code, message){
}}),
intervalID = window.setInterval(console.log("test"), 1000);
}());
}
return{
init: function(){
initPlugins();
}
};
})();
$(window).load(clientname.website.init);
You are running console.log("test") immediately. Try encapsulating this in anther function, but do not instantiate it by including the parenthesis ().
intervalID = window.setInterval(function(){
console.log("test");
}, 1000);
You should not call the function in setInterval. It needs a callback.
Say like bellow
intervalID = window.setInterval(function(){
console.log("test");
}, 1000);
I would recommend to use setTimeout: Use a function to contain the setTimeout, and call it within the function:
$(function() {
var current = $('#counter').text();
var endvalue = 50;
function timeoutVersion() {
if (current === endvalue) {return false;} else {
current++;
$('#counter').text(current);
}
setTimeout(timeoutVersion, 50);
}
$('a').click(function() {
timeoutVersion();
})
})​
JS Fiddle
You used a function call instead of a function reference as the first parameter of the setInterval. Do it like this:
function test() {
console.log("test");
}
intervalID= window.setInterval(test, 1000);
or you can do this also:
intervalID= window.setInterval( function() {
console.log("test!");
}, 1000);

probably moronic js syntax error. Object is null

var fbToggle = document.getElementById("fbToggle");
and later in the script
fbToggle.addEventListener("click", toggle("fbContainer"));
Console tells me that fbToggle is NULL
This is in the document though.
<input type="checkbox" id="fbToggle">
I wasnt using eventListener before, so maybe there is a special order of declaration i'm missing ?
EDIT :
entire js :
function toggle(target) {
var obj = document.getElementById(target);
display = obj.style.display;
if (display == "none") {display = "block"}
else {display = "none"}
}
function init() {
var fbToggle = document.getElementById("fbToggle");
var twitToggle = document.getElementById("twitToggle");
var pinToggle = document.getElementById("pinToggle");
console.log(fbToggle); // NULL
fbToggle.addEventListener("click", toggle("fbContainer"));
twitToggle.addEventListener("click", toggle("twitContainer"));
pinToggle.addEventListener("click", toggle("pinContainer"));
}
window.onload = init();
HTML is way too long.but JS is in head, called from external file. Also i'm not in quirk mode.
It is not clear where "later in the script" is. If it is in different scope definitely it is not going to work. Suggesting you to keep everything in a global object if possible so that you can access from different places in the script.
window.globals = {};
window.globals.fbToggle = document.getElementById("fbToggle");
window.globals.fbToggle.addEventListener("click", function () {
toggle("fbContainer")
});
function toggle(container) {
alert(container);
}
http://jsfiddle.net/ST938/
Another point is addEventListener expects a function or function idenitifier, NOT a function call.
addEventListener("click", toggle("fbContainer")); // wrong
addEventListener("click", toggle); // correct
So if you want to pass a parameter
window.globals.fbToggle.addEventListener("click", function () {
toggle("fbContainer")
});
function toggle(container) {
alert(container);
}
In JavaScript, putting brackets after a function name causes it to be called. If you want to reference a function without calling it you must not put brackets after the name:
window.onload = init(); // this calls init() immediately
window.onload = init; // this correctly stores init in window.onload
The same applies to toggle(). If you need to pre-specify some of the arguments you can wrap it in an anonymous function:
fbToggle.addEventListener("click", function() { toggle("fbContainer"); });
or you can use bind:
fbToggle.addEventListener("click", toggle.bind(null, "fbContainer"));

cannot access function within function in javascript

I need to know what I am doing wrong because I cannot call the internal functions show or hide?
(function()
{
var Fresh = {
notify:function()
{
var timeout = 20000;
$("#notify-container div").get(0).id.substr(7,1) == "1" && (show(),setTimeout(hide(),timeout));
var show = function ()
{
$("body").animate({marginTop: "2.5em"}, "fast", "linear");
$("#notify-container div:eq(0)").fadeIn("slow");
},
hide = function()
{
$("#notify-container div").hide();
}
}//END notify
}
window.Fresh = Fresh;
})();
Fresh.notify();
thanks, Richard
UPDATE
If you wanted to be able to do something like: Fresh.notify.showMessage(), all you need to do is assign a property to the function notify:
var Fresh = {notify:function(){return 'notify called';}};
Fresh.notify.showMessage = function () { return this() + ' and showMessage, too!';};
Fresh.notify();//notify called
Fresh.notify.showMessage();//notify called and showMessage, too!
This will point to the function object here, and can be called as such (this() === Fresh.notify();). That's all there is too it.
There's a number of issues with this code. First of all: it's great that you're trying to use closures. But you're not using them to the fullest, if you don't mind my saying. For example: the notify method is packed with function declarations and jQuery selectors. This means that each time the method is invoked, new function objects will be created and the selectors will cause the dom to be searched time and time again. It's better to just keep the functions and the dom elements referenced in the closure scope:
(function()
{
var body = $("body");
var notifyDiv = $("#notify-container div")[0];
var notifyDivEq0 = $("#notify-container div:eq(0)");
var show = function ()
{
body.animate({marginTop: "2.5em"}, "fast", "linear");
notifyDivEq0.fadeIn("slow");
};
var hide = function()
{//notifyDiv is not a jQ object, just pass it to jQ again:
$(notifyDiv).hide();
};
var timeout = 20000;
var Fresh = {
notify:function()
{
//this doesn't really make sense to me...
//notifyDiv.id.substr(7,1) == "1" && (show(),setTimeout(hide,timeout));
//I think this is what you want:
if (notifyDiv.id.charAt(6) === '1')
{
show();
setTimeout(hide,timeout);//pass function reference
//setTimeout(hide(),timeout); calls return value of hide, which is undefined here
}
}//END notify
}
window.Fresh = Fresh;
})();
Fresh.notify();
It's hard to make suggestions in this case, though because, on its own, this code doesn't really make much sense. I'd suggest you set up a fiddle so we can see the code at work (or see the code fail :P)
First, you're trying to use show value when it's not defined yet (though show variable does exist in that scope):
function test() {
show(); // TypeError: show is not a function
var show = function() { console.log(42); };
}
It's easily fixable with moving var show line above the point where it'll be called:
function test() {
var show = function() { console.log(42); };
show();
}
test(); // 42
... or if you define functions in more 'traditional' way (with function show() { ... } notation).
function test() {
show();
function show() { console.log(42); };
}
test(); // 42
Second, you should use this instead:
... && (show(), setTimeout(hide, timeout) );
... as it's the function name, and not the function result, that should be passed to setTimeout as the first argument.
You have to define show and hide before, also change the hide() as they said.
The result will be something like this:
(function()
{
var Fresh = {
notify:function()
{
var show = function()
{
$("body").animate({marginTop: "2.5em"}, "fast", "linear");
$("#notify-container div:eq(0)").fadeIn("slow");
},
hide = function()
{
$("#notify-container div").hide();
},
timeout = 20000;
$("#notify-container div").get(0).id.substr(7,1) == "1" && ( show(), setTimeout(hide,timeout) );
}//END notify
}
window.Fresh = Fresh;
})();
Fresh.notify();
I think order of calling show , hide is the matter . I have modified your code . It works fine . Please visit the link
http://jsfiddle.net/dzZe3/1/
the
(show(),setTimeout(hide(),timeout));
needs to at least be
(show(),setTimeout(function() {hide()},timeout));
or
(show(),setTimeout(hide,timeout));

how to set to call a function from the current object using settimer

function Something() {
this.var1 = 0;
this.var2 = 2;
this.mytimer;
this.getCars=function() {
//some code
};
this.start = function(l) {
this.updateTimer=setInterval("this.getCars();" , 5000);
};
}
var smth = new Something();
smth.start();
When I type in this.getCars() it does not work. if the function is global declared and i put in for example just getCars it works.
I don't know how to work out this problem because setInterval becomes as parameter a String.
Can somebody help me put with this?
var me = this
setInterval(function() {me.getCars()}, 5000)
if you happen to be using prototype, you could also use the handy bind method:
setInterval(this.getCars.bind(this), 5000)
Try this:
function Something() {
this.var1 = 0;
this.var2 = 2;
this.mytimer;
var me = this;
this.getCars = function() {
console.log(me.var2);
};
this.start = function(l) {
me.updateTimer = setInterval(me.getCars, 1000);
}
}
var smth = new Something();
smth.start();
The console.log() bit is Firefox/Firebug. Replace it with something else if you're not using that (although I would highly recommend developing with it).
Basically the problem is that when you call a function, even a method of an object, the way you call it determines the value of this. See Method binding for more details. So what you do is fix the value of this as I've done in the above example (for methods).

Categories

Resources