How to Change the SRC of an Embed Tag in JavaScript
The “<embed>” tag embeds media on a Web page. These tags are most often used to embed music and videos. HTML tags are, by themselves, static and unchanging. A little JavaScript -- a programming language that runs in the user's browser -- can change any contents of your Web page's HTML tags. To change the “SRC” or “source” attribute of “<embed>” tags with JavaScript, you need to assign an ID to the tags so your script can load information about the tags and change them.
Instructions
-
-
1
Open your Web page in a code editor or Notepad and look for the “<embed>” tags in the code:
<embed src=”sample.mov” width=”300” height=”250” autoplay=”false”>
-
2
Add an ID name to your “<embed>” tag:
<embed src=”sample.mov” width=”300” height=”250” autoplay=”false” id=”myvideo”>
You can use any name for an ID, so long as it is unique. Pick a name that is easy to remember.
-
-
3
Go to the closing “</body>” tag of your Web page code and add “<script>” tags just above it:
<script type=”text/javascript”>
</script>
</body> -
4
Begin writing your JavaScript code between the “<script>” tags. Declare a variable and set its value to the URL for the media you want to embed:
var myVideo = “http://yourdomain.com/path/to/thevideo.mov”;
When specifying a URL as the value of a variable, always surround it in single or double quotes. In this example, “myVideo” is the name of the variable. The variable stores information that is changeable or “variable,” as the term suggests.
-
5
Start a new line under your variable and add this code:
var myEmbed = document.getElementById(“myvideo”);
This code places information about the “<embed>” tag inside a variable called “myEmbed.”
-
6
Set the “SRC” attribute of “myEmbed” to the variable containing your media's URL:
myEmbed.setAttribute(“src”, myVideo);
The first parameter inside the paranthesis is “SRC,” the name of the attribute you need to change. This information needs quotation marks, as shown. The next parameter, or piece of information, is the name of the variable containing the URL. Since this is a variable name, it does not need quotation marks. Here is the finished script:
var myVideo = “http://yourdomain.com/path/to/thevideo.mov”;
var myEmbed = document.getElementById(“myvideo”);
myEmbed.setAttribute(“src”, myVideo);
-
1