...

View Full Version : setAttribute doesn't seem to work



uxair
01-04-2007, 05:15 PM
I've a page that contains a DIV whose id is 'divExposure', what I want to do is to set the "onscroll" event whenever user scroll on the div, to achieve this objective I write this code, but with no luck...

can anyone help me out what I'm missing, below is the code


<script language="javascript">

document.getElementById( 'divExposure' ).setAttribute( "onscroll", "emp()" );
function emp()
{
//here goes my function logic...
}

</script>

to check whether the onsroll att. is set I've done this


alert( String( document.getElementById( 'divExposure' ).onscroll ) );

and this alerts with emp() written on it.

koyama
01-04-2007, 06:05 PM
Which browser did you test in? I think that it would work in FF, but not in IE. I'm not 100% sure, but I think that you indeed are allowed to do this kind of thing although unusual, but who knows?

Instead, normally you would probably be writing:


document.getElementById('divExposure').onscroll = emp;

This should work in IE too.

liorean
01-04-2007, 06:11 PM
Attributes are one thing, event handlers are another thing. Your way changes the attribute, but not the event handler. To change the event handler, the cross browser way to do it is this way:

element.onevent=theFunctionYouWantToHandleTheEvent
So...
document.getElementById('divExposure').onscroll=function(){
emp();
}
function emp(){
//here goes my function logic...
}




// or...
document.getElementById('divExposure').onscroll=emp;
function emp(){
//here goes my function logic...
}




// or...
document.getElementById('divExposure').onscroll=function(){
//here goes my function logic...
}

uxair
01-05-2007, 05:03 AM
thanks mate

Arbitrator
01-05-2007, 10:10 PM
Just to clarify the issue, the short story is that it doesnít work in Internet Explorer; setAttribute() is broken for event attributes in that browser. Based upon a look at Internet Explorerís DOM, it will set the attribute, but will ignore the event.

The more correct way to do it would be to use addEventListener(), but Internet Explorer doesnít support that either.


document.getElementById("divExposure").addEventListener("scroll", emp, false);

Thus, you end up using the traditional, non‐standard method koyama and liorean mentioned, which does work in Internet Explorer as well as in the browsers that understand the above methods.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum