Click to See Complete Forum and Search --> : using setAttribute to create unique attributes.


skribbs
November 6th, 2008, 09:12 AM
Alright please let me know if this is even possible.

I'm trying to load a javascript using javascript but I need some unique attributes.

Heres what I want:
<SCRIPT TYPE="text/javascript" for="CoolPlugin" event="specialEvent(methodName, parameters)" src="coolPlugin.js"> </SCRIPT>

Heres what I'm doing:
//I have a simple javascript file that gets loaded when the body loads, theres an 'init()' function that gets called and heres whats inside it:

init(){
var head = document.getElementsByTagName('head')[0];
var tag = document.createElement('script');
tag.setAttribute('type', 'text/javascript');
tag.setAttribute('src', 'coolPlugin.js');
tag.setAttribute('for', 'CoolPlugin');
tag.setAttribute('event', 'specialEvent(methodName, parameters)');
head.appendChild(tag);
}

What supposed to happen is that the event reacts to a key press (lets say when the user presses '1') and the font changes colors

From what it looks like, the 'for' and 'event' attribute dont seem to get appended.

Please let me know if you have any comments, suggestions, ideas, or any incite on solving this problem.

PeejAvery
November 6th, 2008, 10:32 AM
Since they are not valid attibutes, they can't be applied by setAttribute.

Xeel
November 6th, 2008, 11:07 AM
I'm not sure you even could use event attribute for script tag. It shouldn't work this way...

Here's an example I've just wrote. It adds a global listener event for onkeypress and changes background color when you press keys from '1' to '6'. The code works in both IE and non-IE browsers:
<body id="mbody">

<script type="text/javascript">
function blockA(e) {
var keycode = (e.keyCode)?e.keyCode:e.which;
var mbody = document.getElementById("mbody");

switch(keycode){
case 49:
mbody.style.backgroundColor = "#99CCFF";
break;
case 50:
mbody.style.backgroundColor = "#CCCCCC";
break;
case 51:
mbody.style.backgroundColor = "#CC99CC";
break;
case 52:
mbody.style.backgroundColor = "#FF9900";
break;
case 53:
mbody.style.backgroundColor = "#669966";
break;
case 54:
mbody.style.backgroundColor = "#FFFFFF";
break;
default:
return false;
break;
}
}
</script>
<!--[if IE]>
<script type="text/javascript">
document.attachEvent('onkeypress',blockA);
</script>
<![endif]-->
<script type="text/javascript">
document.captureEvents(Event.KEYPRESS);
document.onkeypress = blockA;
</script>

<p>text1</p>
<p>text2</p>

</body>
hope this helps...