How can I dynamically name id's using javascript?
Something like this:
js:
var idName = "fruit";
html:
<img id="javascript:idName" src="banana.jpg">
var bananaImage = new Image();
bananaImage.id = "fruit";
bananaImage.src = "banana.jpg";
Using the jQuery framework you could do something like:
<img class="idName" src="banana.jpg"/>
<img class="idName" src="cherry.jpg"/>
The script ...
var idName = 'fruit';
$(function() {
$('img.idName').each(function(i) {
$(this).attr({id: idName+i});
});
});
... which results in:
<img id="fruit0" class="idName" src="banana.jpg"/>
<img id="fruit1" class="idName" src="cherry.jpg"/>
You can dynamically create elements, such as <img>, and set their attributes using JavaScript's DOM API.
or you can get the element any other way IE
imgs = container.getElementsByTagName("img");
foreach(imgs as img){
if(imgs.src == "banana.jpg") img.id = "fruit";
}
Note: foreach doesn't work in JS you'll need a for loop, but I'm too lazy :P
I think this is what your looking for. You need some sort of event to trigger the JavaScript. Since IMG doesnt have it, except for user events, you need something like:
<head>
<script language="JavaScript" type="text/javascript">
function nameMyIds() {
var idToName = "firstImageId";
var theImage = getImageBySrc("banana.jpg");
if (theImage!=null)
theImage.id = idToName;
}
function getImageBySrc(src) {
// using DOM, using jQuery would make this easier
var allImages = document.body.getElementsByTagName("IMG");
for (var i=0; i<allImages.length; i++ ) {
var img = allImages[i];
var i = img.src.indexOf(src);
if (img.src == src || img.src.indexOf(src) > 0) { return img };
}
}
</script>
</head>
<body onload="nameMyIds()">
<img src="banana.jpg">
</body>
Related
I have I array of images src ["http://src1", "http://src2", "http://src3"]. I want for get all images from that array and manipulate them, for example placing them into a div?
var imgSrc = ["http://src1,http://src2,http://src3"];
var string = imgSrc[0];
console.log(string);
var array = string.split(",");
console.log(array);
var inHTML = '';
console.log(array[0]);
$.each(array, function(key, value){
var html = '<img src="'+ value[key]+'" align="center">';
inHTML += html;
});
$('div#item').html(inHTML);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="item"></div>
You can append the dynamically created Images from the array to a perticular div. Hope this helps...
HTML
<html>
<head>
</head>
<body>
<h1>Images</h1>
<div id="content">
</div>
<script src="app.js"></script>
</body>
</html>
JS
var imageSources = ["http://src1,http://src2,http://src3"]
imageSources.forEach(element => {
var img = document.createElement("img");
img.width = '300';
img.height = '300';
img.src = element;
document.getElementById("content").appendChild(img)
};
I think your array is somewhat like:
["http://src1","http://src2","http://src3"]
If I am right then you can do something like:
var y = x.map((key,value)=>{return ('<div>'+key+'</div>')});
y will be an array with the div tags containing images.
Hope, I understood your problem.
I want for get all images from that array and manipulate them, for
example placing them into a div
You can dynamically generate img elements and add them to a div.
To iterate through the array you could use forEach, creating the img elements within the loop using createElement and appendChild to append the image to the div
See example below, which should get you started.
var images = ["https://placehold.it/50x50","https://placehold.it/25x25","https://placehold.it/75x75"];
var target = document.getElementById('target');
images.forEach(function(imgSrc){
var newImg = document.createElement("img");
newImg.src = imgSrc;
target.appendChild(newImg);
})
<div id="target"></div>
Creating an Array:
You must use the following syntax to to create a JavaScript Array:
var array_name = [ item1, item2, ... ];
Or Using the JavaScript Keyword new:
var array_name = new Array( item1, item2, ... );
So your array must be like this:
var image_source = [ 'http://src1', 'http://src2', 'http://src3' ];
Access the Elements of an Array:
You refer to an array element by referring to the index number. for example this statement accesses the value of the first element in cars:
var first_image = image_source[ 0 ];
Example:
var image_source = [ 'http://img1', 'http://img2', 'http://img3' ];
document.getElementById( 'demo' ).innerHTML = image_source[ 1 ];
<div id="demo"></div>
I want to store the jquery variable value to the html variable value.
Here is my code,
This is the javascript function which is in external javascript page
function createImage(settings) {
var kk = createCanvas(settings)[0].toDataURL('image/png');
}
Now, this is in html page
var karan = kk;
<img id="containerQrCode" src = "+ karan +" alt="qr image" />
Now, how can I move the kk value which is in external javascript page to the karan variable which is in html page.
Thanks In Advance.
I will suggest you work with the DOM. Some thing like the below if your are jQuery.
function createImage(settings) {
var kk = createCanvas(settings)[0].toDataURL('image/png');
$("#containerQrCode").attr("src", kk);
}
below can be tried if not using jquery
function createImage(settings) {
var kk = createCanvas(settings)[0].toDataURL('image/png');
document.getElementById("containerQrCode").setAttribute("src", kk);
}
try something like this:
<img id="containerQrCode" src = "
<script type="text/javascript>document.write(karan)</script>
" alt="qr image" />
Sorry misread about setting the variable as well, try this:
Edit the function to say this:
function createImage(settings) {
var kk = createCanvas(settings)[0].toDataURL('image/png');
return kk;
}
Then update where you set karan to this:
var karan = createImage();
You will also need to include the external javascript file in the project like this:
<script type="text/javascript" src="path/to/your/file.js"></script>
var karan = kk;
var img = document.getElementById('containerQrCode');
img.src = karan;
I want to access the Javascript variable value outside the Javascript tag.
function getprices(input) {
return input.match(/[0-9]+/g);
}
var subtotals = get_getprices('%GLOBAL_OrderTotal%');
var Grand_total = subtotals[0];
<img height="0" width="0" border="0" src="http://testing.com?merchantId=M1&orderNo=%%GLOBAL_OrderId%%&saleAmount=I want the Grand+Total Value here">
You'd need to update the src property on that img element. Let's suppose you gave the img an id (you don't have to, there are other ways to select it, but I'm keeping it simple):
<img id="the-image" height="0" width="0" border="0" src="http://testing.com?merchantId=M1&orderNo=%%GLOBAL_OrderId%%&saleAmount=I want the Grand+Total Value here">
Then:
function getprices(input) {
return input.match(/[0-9]+/g);
}
var subtotals = getprices('%%GLOBAL_OrderTotal%%'); // <=== Changed to `getprices`, was `get_getprices`
var Grand_total=subtotals[0];
var img = document.getElementById("the-image");
img.src = "http://testing.com?merchantId=M1&orderNo=%%GLOBAL_OrderId%%&saleAmount=" + Grand_total;
It looks like Grand_total will always be a number, but for the general case where it might not be, , be sure to use encodeURIComponent (it doesn't do any harm even if it is a number):
img.src = "http://testing.com?merchantId=M1&orderNo=%%GLOBAL_OrderId%%&saleAmount=" + encodeURIComponent(Grand_total);
If you didn't use an id on the img, that's fine, you can use any CSS selector via document.querySelector. That's supported by all modern browsers, and also IE8.
Note that there are other issues with that code, though, not least that getprices looks fairly suspect.
All you need to do is to assign your value to src of img in your javascript
$("#imgNeeded").attr("src",".../"+Globalvalue)
As T.J. Crowder said. make sure you encode URI if your variable contain something other than number
You can use
document.getElementsByTagName("img")[***index of the image tag***].src = "<THE STRING>"+<THE VARIABLE>+"<THE REMAINING STRING>";
or assign an id to the <img> and use
`document.getElementById("id of the image").src = ""++"";
The problem the provided approaches share is, that how they are, your image will get loaded with the unwanted source before changed:
<html>
<head>
<script>
function getprices(input){return input.match(/[0-9]+/g)};
function changeSrc(){
var tE = document.querySelector("img[src*='saleAmount=']");
var tS = getprices('anyPrice1');
if (tE && tS) tE.src += encodeURIComponent(tS[0]);
};
</script>
</head>
<body onload = 'changeSrc()'>
<img height = '0' width = '0' border = '0' src = 'http://JUSTTOSHOWtesting.com?merchantId=M1&orderNo=%%GLOBAL_OrderId%%&saleAmount=' onerror = 'console.log(this.src)'>
</body>
Your console will log two calls:
- GET http://justtoshowtesting.com/?merchantId=M1&orderNo=%%GLOBAL_OrderId%%&saleAmount= net::ERR_NAME_NOT_RESOLVED
- GET http://justtoshowtesting.com/?merchantId=M1&orderNo=%%GLOBAL_OrderId%%&saleAmount=1 net::ERR_NAME_NOT_RESOLVED
So what you could do is placing a placeholder, until you have the source you need:
<html>
<head>
<script>
function getprices(input){return input.match(/[0-9]+/g)};
function createSrc(){
var tE = document.querySelector("ins[src*='saleAmount=']");
var tS = getprices('anyPrice1');
if (tE && tS){
var tI = document.getElementById('iPlaceholder');
if (!tI){
tI = document.createElement('img');
tI.id = 'iPlaceholder';
tI.onerror = function(){console.log(this.src)};
tE.parentNode.insertBefore(tI, tE.nextSibling);
};
tI.src = tE.getAttribute('src') + encodeURIComponent(tS[0]);
};
};
</script>
</head>
<body onload = 'createSrc()'>
<ins src = 'http://JUSTTOSHOWtesting.com?merchantId=M1&orderNo=%%GLOBAL_OrderId%%&saleAmount='></ins>
</body>
</html>
Now your console will merely log one call:
- GET http://justtoshowtesting.com/?merchantId=M1&orderNo=%%GLOBAL_OrderId%%&saleAmount=1 net::ERR_NAME_NOT_RESOLVED
I have a next string like:
<img src="../uplolad/commission/ranks/avatar.jpg' . $row[$c_name] .'" width="50" height="50"/>
How can i get a image file name in javascript? I know only PHP regexes. Extention of a file can be different.
The result must be: avatar.jpg
Regex is not ideal for this. JavaScript can traverse the HTML as distinct objects more readily than as a long string. If you can identify the picture by anything, say by adding an ID to it, or an ID to a parent with that as the only image, you'll be able to access the image from script:
var myImage = document.getElementById('imgAvatar'); // or whatever means of access
var src = myImage.src; // will contain the full path
if(src.indexOf('/') >= 0) {
src = src.substring(src.lastIndexOf('/')+1);
}
alert(src);
And if you want to edit, you can do that just as well
myImage.src = src.replace('.jpg', '.gif');
Fetch it following coding which can help what you want to get.
<script type="text/javascript">
function getImageName(imagePath) {
var objImage = new RegExp(/([^\/\\]+)$/);
var getImgName = objImage.exec(imagePath);
if (getImgName == null) {
return null;
}
else {
return getImgName[0];
}
}
</script>
<script>
var mystring = getImageName("http://www.mypapge.mm/myimage.png")
alert(mystring)
</script>
Here's a shorter variation of David Hedlund's answer that does use regex:
var myImage = document.getElementById('imgAvatar'); // or whatever means of access
alert(myImage.src.replace( /^.+\// , '' ));
If i have "img" element id = "myimg".
Is posible to add link to "img" without edit html page using jQuery
<img id="myimg" src="image.png">
I like to make "myimg" have link like this.
<img id="myimg" src="image.png">
You can use wrap():
$("#myimg").wrap("<a href='test.html'></a>');
or
$("#myimg").wrap($("<a>").attr("href", "test.html"));
or:
var a = $("<a>").attr("href", "test.html");
$("#myimg").wrap(a);
I am not into jQuery. Using Javascript, you can do something like:
var parentEl = document.getElementById("myimg").parentElement;
var imgEl = parentEl.innerHtml;
parentEl.innerHtml = '' + imgEl + '';
$(document).ready(function() {
var src = "linkhere.html";
var a = $("<a/>").attr("href", src);
$("#myimg").wrap(a);
});