How to Put a Variable in an Src Attribute

How do I put a variable in an src attribute?

With javascript:

  • you can add and remove elements to and from documents; and
  • you can add and remove attributes to and from elements

So if in your markup you have something like:

<div id="my-div"></div>

You can add an img element as a child of the div element, like so:

var myDiv = document.getElementById('my-div'); // grabs #my-div
var myPath = 'img/image.png'; // initialises string variable myPath
var myImg = document.createElement('img'); // creates a new img element


myImg.setAttribute('src', myPath); // adds a src attribute (with the value myPath) to myImg
myDiv.appendChild(myImg); // adds a child element (myImg) to myDiv

How to add variable to src attribute

Use ng-src so that the browser doesn't attempt to download the resource before AngularJs has re-rendered the DOM.

<img ng-src='http://...../{{element}}'/>

How can I use a variable in the src of a script tag?

How do you pass a variable as a part of an URL?

Easy! Since you don't mind using javascript a simple solution is as follows

var scriptElement = document.createElement("script");
scriptElement.src = "http://markets.financialcontent.com/stocks?Module=snapshot&Ticker=" + encodeURIComponent("$SPX+" + sym) + "&Output=JS";
document.head.appendChild(scriptElement);

This code creates an script element with the source being "http://markets.financialcontent.com/stocks?Module=snapshot&Ticker=" + encodeURIComponent("$SPX+" + sym) + "&Output=JS". Then it appends it to the head of the webpage.

The final HTML being:

<script>
var sym = "MSFT";
document.write("\<script src='" + "http://markets.financialcontent.com/stocks?Module=snapshot&Ticker=" + encodeURIComponent("$SPX+" + sym) + "&Output=JS" + "'\>\</script\>");
</script>

The reason that this solution won't work is as follows:

Codepen is an HTTPS site which means it WILL NOT serve HTTP content. To be honest I have no idea why Codepen serves the HTTP script. How to fix this? Well, there really is only one easy solution:

Instead of using Codepen use a local HTML file and just open that, if you have your own HTTP server you can use that.

Quick how-to guide:

1) Open a text editor

2) Type the following

<html>
<head>
<script>
var sym = "MSFT";
document.write("\<script src='" + "http://markets.financialcontent.com/stocks?Module=snapshot&Ticker=" + encodeURIComponent("$SPX+" + sym) + "&Output=JS" + "'\>\</script\>");
</script>
</head>
<body>
</body>
</html>

3) Now hit the "Save As" button and save it as a .html file

4) Open it!

5) Have fun :)

use variable inside src attribute with jquery

here you go, just change where the quote is, and remove the initial extension:

var src = $(this).attr('data-src').replace('.jpg', '');
$(this).attr('src', src + '-228x170.jpg' );

Per question in comments:

var src = $(this).attr('data-src').replace('.jpg', '');
var specialChars = ('fooo'); //this can be set dynamically

$(this).attr('src', src + '-228' + specialChars + '.jpg' );

HTH,
-Ted

How to add variable to src source in JS script?

Well, you can do that using client-side code, but not using HTML:

<script>
var username="John";
var script = document.createElement('script');
script.src = "chat/script.php?room=1&username="+username+"&draggable=1";
document.getElementsByTagName('script')[0].parentNode.appendChild(script);
</script>

Pass variable to this.src

With jQuery by using mouseover() and mouseout() and attr() methods.

$(document).ready(function(){
var file_name='your_file_name';
var new_source_for_image ="/prestashop_1.7.0.3/modules/se_daynight/img/" + file_name + ".png";
var new_source_for_image_with_glow = "/prestashop_1.7.0.3/modules/se_daynight/img/" + file_name + "_glow" + ".png";

$("img#visit_image").attr('src',new_source_for_image);
$("img#visit_image").mouseover(function(){
$(this).attr('src',new_source_for_image_with_glow);
});

$("img#visit_image").mouseout(function(){
$(this).attr('src',new_source_for_image);
});
});

Add javascript variable to javascript src?

What you're trying to do is called called JSONP. Since you can't use a regular Ajax call to fetch JSON from another domain (it would have security implications), you have to add a script that will call the callback function you specify, and pass it the JSON. As other answers say, you have to create the script tag programmatically. I wouldn't use document.write for that, because it won't work after page load (the new script would replace the whole document). But there is a very simple alternative:

function youtubeFeedCallback1(data) {
var s = '';
var k = '';
s += data.entry.title.$t;
k += data.entry.media$group.media$thumbnail[2].url;
vidtitle1=s;
vidthumb1=k;
}

var script = document.createElement('script');
script.src = "http://gdata.youtube.com/feeds/api/videos/" + vidid[0] + "?v=2&alt=json-in-script&callback=youtubeFeedCallback1";
document.body.appendChild(script);

One last recommendation: I see you have global variables on your callback, vidtitle1 and vidthumb1. Whatever you need to do with their values, do it from the callback (and preferably get rid of the global variables), or chances are it won't work. The data will be loaded asynchronously, so the variables are only guaranteed to contain their values after the callback runs.



Related Topics



Leave a reply



Submit