Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

adding an event listener 1

Status
Not open for further replies.

1DMF

Programmer
Jan 18, 2005
8,795
GB
I've been searching for a simple cross-browser way of adding an event listner.

I've found these two methods, which is the best or are both required for cross browser functionality...

Code:
obj.attachEvent( 'onload', 'myfunc' );

[b]or[/b]

obj.addEventListener( 'onload', 'myfunc', false );


"In complete darkness we are all the same, only our knowledge and wisdom separates us, don't let your eyes deceive you."

"If a shortcut was meant to be easy, it wouldn't be a shortcut, it would be the way!
 
I've been trying to use a global method but am having problems..
Code:
document.getElementsByTagName('body')[0].onload=gat;

but it errors saying it is null or not an object?

What am i doing wrong?

"In complete darkness we are all the same, only our knowledge and wisdom separates us, don't let your eyes deceive you."

"If a shortcut was meant to be easy, it wouldn't be a shortcut, it would be the way!
 
Hi

Code:
[red]window[/red].onload=gat;
Being [tt]null[/tt] would mean the code you posted was included in the [tt]head[/tt] of the document, so executed when the [tt]body[/tt] was not created yet.

Feherke.
 
ah, you're one smart cookie!

Thanks, so obvious I was blinded!

"In complete darkness we are all the same, only our knowledge and wisdom separates us, don't let your eyes deceive you."

"If a shortcut was meant to be easy, it wouldn't be a shortcut, it would be the way!
 
doesn't solve my problem though!

_gat is still undefined even when i wrap it in an event listener that only triggers on body load (i moved document.getElementsByTagName('body')[0].onload=gat; to the bottom of the HTML)

I'm assuming onload , doesn't actualy wait for successful load.

hmm, how can you force a page to wait until it can load external source files?

"In complete darkness we are all the same, only our knowledge and wisdom separates us, don't let your eyes deceive you."

"If a shortcut was meant to be easy, it wouldn't be a shortcut, it would be the way!
 

"In complete darkness we are all the same, only our knowledge and wisdom separates us, don't let your eyes deceive you."

"If a shortcut was meant to be easy, it wouldn't be a shortcut, it would be the way!
 
Hi

I see no problem there which would lead to such error.

But I strongly recommend to set the [tt]onload[/tt] for [tt]window[/tt] :
Code:
[red]window[/red].onload=gat;
Because the browsers behavior related to [tt]document.body.onload[/tt] differs, but [tt]window.onload[/tt] works everywhere :
[ul]
[li]Mozillas ( FireFox, SeaMonkey ) - only [tt]window[/tt][/li]
[li]Opera - either [tt]window[/tt] or [tt]document[/tt] [sup](*)[/sup][/li]
[li]Konqueror - both [tt]window[/tt] and [tt]document[/tt][/li]
[li]Midori - only [tt]window[/tt][/li]
[/ul]
[sup](*)[/sup] - The later defined one overwrites the previously defined one.

I would expect to experience no more error after changing to [tt]window.onload[/tt].

Feherke.
 
No it's erroring intermittently most days lately..

It's the google analytics, it's constantly erroring saying
'_gat' is undefined

So I thought I'd wrap it in a onload event, the thought being it will only fire once the ga.js file has correctly loaded, but it doesn't seem to be the case.

I guess if a file cannot be reached, the browser ignores it and carries on rather than hanging the page load waiting for all content.

Is there a way round this?

"In complete darkness we are all the same, only our knowledge and wisdom separates us, don't let your eyes deceive you."

"If a shortcut was meant to be easy, it wouldn't be a shortcut, it would be the way!
 
Hi

I have no idea when is the [tt]document.body.onload[/tt] occurs.

But I know when [tt]window.onload[/tt] is fired :
MDC - window.onload said:
The load event fires at the end of the document loading process. At this point, all of the objects in the document are in the DOM, and all the images and sub-frames have finished loading.
This is why I would change it and why I expect positive results.

Of course there is no guarantee that loading of the resources finished successfully. So you can put an additional check to avoid the error messages :
Code:
function mygat()
{
  [red]if ('undefined'==typeof _gat) return;[/red]

  var pageTracker = _gat._getTracker("UA-5985078-1");
  pageTracker._trackPageview();
}
Note that addition ( + ) is not defined for [tt]undefined[/tt] and [tt]function[/tt] operands :
Code:
window.onload += mygat;


Feherke.
 
lol - G! support suggested similar , with a minor tweek of my own ;-)
Code:
    function mygat(){
        if(typeof(_gat) == 'object'){
            var pageTracker = _gat._getTracker("UA-5985078-1");
            pageTracker._trackPageview();
        }            
        else{alert("Google Analytics -> Broken Like Usual!");}
    }

    window.onload += mygat;

But this doesn't fix the problem, it just ignores any error or at least stops an error being thrown, it still means the GOAN doesn't fire and the visit isn't tracked, I'd hardly call that a fix, I might as well add an (on error ignore everything!)

Also using += is not erroring trying to append the event listener.

If I do window.load I guess I don't have to worry about other event listeners on the body tag?

"In complete darkness we are all the same, only our knowledge and wisdom separates us, don't let your eyes deceive you."

"If a shortcut was meant to be easy, it wouldn't be a shortcut, it would be the way!
 
Have you tried breaking your script into two, like Google do in their example usage? Something like:

Code:
<script type="text/javascript">
	var gaJsHost = (("https:" == document.location.protocol) ? "[URL unfurl="true"]https://ssl."[/URL] : "[URL unfurl="true"]http://www.");[/URL]
	document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script>
<script type="text/javascript">
	var pageTracker = _gat._getTracker("UA-xxxxxxx-x");
	pageTracker._initData();
	pageTracker._trackPageview();
</script>

Then put your code in the second script. I don't know if it makes a difference, but I'm assuming there's a reason Google have split their code in two like that.

You could also set a timer going to test for the variable, and only run your code if the variable exists.

Dan



Coedit Limited - Delivering standards compliant, accessible web solutions

Dan's Page [blue]@[/blue] Code Couch:
Code Couch Tech Snippets & Info:
 
Have you tried breaking your script into two, like Google do in their example usage?
yup, that's how I normally install it, but it' sbeen driving me mad for weeks.

I guess I could create a timeout which keeps testing for _gat == object, when it does complete the code else create another settimeout.

Can you give me a heads up on settimeout, it only fires the once right and removed itself from memory once fired, is this correct?

Or do I set up a recursive call on a timer and then remove event listener once it finally works?


"In complete darkness we are all the same, only our knowledge and wisdom separates us, don't let your eyes deceive you."

"If a shortcut was meant to be easy, it wouldn't be a shortcut, it would be the way!
 
Have you tried breaking your script into two, like Google do in their example usage?
yup, that's how I normally install it, but it's been driving me mad for weeks.

I guess I could create a timeout which keeps testing for typeof(_gat) == object, when it does complete the code else create another settimeout.

Can you give me a heads up on settimeout, it only fires the once right and removes itself from memory once fired, is this correct?

Or do I set up a recursive call on a timer and then remove event listener once it finally works?


"In complete darkness we are all the same, only our knowledge and wisdom separates us, don't let your eyes deceive you."

"If a shortcut was meant to be easy, it wouldn't be a shortcut, it would be the way!
 
Hi

Well, if you hope that Google Analytics will still be loaded later, you can put it to check regularly :
Code:
function mygat()
{
  if ('undefined'==typeof _gat) {
    window.setTimeout(mygat,10000);
  } else {
    var pageTracker = _gat._getTracker("UA-5985078-1");
    pageTracker._trackPageview();
  }
}
window.onload=mygat;
And yes, only the last code assigned to [tt]window.onload[/tt] will be executed, but you still can not add multiple functions that way. This is why [tt]addEventListener()[/tt] and [tt]attachEvent()[/tt] were invented. However, there are old-school methods to add multiple functions. Google will show some.

Feherke.
 
is that checking every ten seconds ?

"In complete darkness we are all the same, only our knowledge and wisdom separates us, don't let your eyes deceive you."

"If a shortcut was meant to be easy, it wouldn't be a shortcut, it would be the way!
 
Hi

Yes. I would say it is more than enough. I see no chance to get it later. But if you want, you can force it :
Code:
var gaJsHost = (("https:" == document.location.protocol) ? "[URL unfurl="true"]https://ssl."[/URL] : "[URL unfurl="true"]http://www.");[/URL]
[red]var GAscript=null[/red]
function mygat()
{
  if ('undefined'==typeof _gat) {
    [red]if (GAscript!=null) GAscript.parentNode.removeChild(GAscript)
    GAscript=document.createElement('script')
    GAscript.src=gaJsHost+'google-analytics.com/ga.js'
    GAscript.type='text/javascript'
    document.getElementsByTagName('head')[0].appendChild(GAscript)[/red]
    window.setTimeout(mygat,10000);
  } else {
    var pageTracker = _gat._getTracker("UA-5985078-1");
    pageTracker._trackPageview();
  }
}
window.onload=mygat;

Feherke.
 
can't seem to post to my own question anymore?

"In complete darkness we are all the same, only our knowledge and wisdom separates us, don't let your eyes deceive you."

"If a shortcut was meant to be easy, it wouldn't be a shortcut, it would be the way!
 
Well I like to check vars the other way round, but that's just a personal thingy i guess, but I think we've cracked it, nice one Feherke.

I'm thinking there is sometimes a delay thing going on, and the timeout will resolve that, I think 10 seconds is too long, it needs to check every 3secs perhaps, 10 seconds is more than long enough for a bounce to happen, or navigation somewhere else before the code has actually tracked the page.

I don't think it is a loading JS issue, but more what ever ga.js does it isn't finsihing before the tracking code is run, so _gat isn't defined yet, so hopefully this will do the trick

my final code is...
Code:
<script type="text/javascript">

var gaJsHost = (("https:" == document.location.protocol) ? "[URL unfurl="true"]https://ssl."[/URL] : "[URL unfurl="true"]http://www.");[/URL]
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));

function mygat(){

  if (typeof(_gat) == 'undefined') {
    window.setTimeout(mygat,3000);
  } 
  else {
    var pageTracker = _gat._getTracker("UA-5985078-1");
    pageTracker._trackPageview();
  }
  
}

function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } 
  else {
    window.onload = function() {
      if(oldonload){oldonload();}
      func();
    }
  }
}

addLoadEvent(mygat);

</script>

I did actually do a G! search and found the webreference site regarding multiple onloads, but seings as there site was riddled with javascript errors itself, I didn't think i'd take JS lessons from them ;-)

I really appreciate your help on this, I'll post back to the G! forum, hopefully it will help a lot of other people going mad over this!

"In complete darkness we are all the same, only our knowledge and wisdom separates us, don't let your eyes deceive you."

"If a shortcut was meant to be easy, it wouldn't be a shortcut, it would be the way!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top