
Apu
February 13, 2023 ›
#dynamically
›
#HowTo
❌
JavaScript Change Script Src Dynamically
Today, I'm going to talk about how you can use JavaScript to dynamically change the src of a script tag.
For this, we have a page with three buttons, Button 1, Button 2 and Button 3. When each button is clicked, we want it to call different scripts. When Button 1 is clicked, we'll run src1.js, when Button 2 is clicked, we'll run src2.js and when Button 3 is clicked, we'll run src3.js
<script id="myScript"></script> <!--This will hold our current active script --> <button onclick="changeSrc('src1')">Button 1</button> <button onclick="changeSrc('src2')">Button 2</button> <button onclick="changeSrc('src3')">Button 3</button>
Now let's define our changeSrc() function in JavaScript so that it updates the src attribute of our #myScript element accordingly.
<script> function changeSrc(e){ let myScript = document.getElementById("myScript"); switch (e) { case "src1": myScript.setAttribute("src","/js/src1.js"); break; case "src2": myScript.setAttribute("src","/js/src2.js") ; break; case "src3": myScript.setAttribute("src","/js/src3.js") ; break; } console.log(myScript.src) } </script>
save
listen
AI Answer
JavaScript Change Script Src Dynamically
0
Today, I'm going to talk about how you can use JavaScript to dynamically change the s…
asked
Apu
0 answers
2915
Today, I'm going to talk about how you can use JavaScript to dynamically change the s…
Answer Link
answered
Apu