Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
179
rated 0 times [  184] [ 5]  / answers: 1 / hits: 110774  / 14 Years ago, tue, march 8, 2011, 12:00:00

I have this code:



    <script type=text/javascript>
function js() {
var getJs = document.getElementById(jogo);

if (JS == true) { //if button JS is pressed - it is correct?

< script type = text/javascript
src = file1.js >


} else < script type = text/javascript
src = file2.js >
</script>
}
</script>


it doesn't work. I gave two buttons, if the first is pressed, file1.js should be loaded. In case the second one is pressed, file2.js should be loaded.



How can I do that?


More From » javascript

 Answers
10

You cannot embed HTML in Javascript in that way. Basically, what you want is to embed a script element, pointing to a certain javascript file when clicking a button. That can be done with combining events with DOM:



<script type=application/javascript>
function loadJS(file) {
// DOM: Create the script element
var jsElm = document.createElement(script);
// set the type attribute
jsElm.type = application/javascript;
// make the script element load file
jsElm.src = file;
// finally insert the element to the body element in order to load the script
document.body.appendChild(jsElm);
}
</script>
<button onclick=loadJS('file1.js');>Load file1.js</button>
<button onclick=loadJS('file2.js');>Load file2.js</button>

[#93376] Monday, March 7, 2011, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
damiondenzelc

Total Points: 268
Total Questions: 116
Total Answers: 116

Location: North Korea
Member since Tue, Jun 16, 2020
4 Years ago
;