My Random Number Generate code is
var randomnumber=Math.floor(Math.random()*99999)
Now I want to put this variable output in a image scr url..
Here is my url
<img src="http://www.myexample.com/get/image.php?vcid=14851&t=481" alt="" id="imge"/>
So what will my code?
<img src="http://www.myexample.com/get/image.php?vcid='+ randomnumber +'&t=481" alt="" id="imge"/>
??
Please help me
In pure Javascript you could do it like
var randomNumber = 1;
var image = document.getElementById("imageId");
var imageSrc = image.getAttribute("src");
image.setAttribute("src", imageSrc + randomNumber);
To put your number at the correct place you could use some string split functions, but since the order of query strings don't matter you should just put your vcid query at the end.
Try adding this in your <script>:
document.getElementById("imge").src = "http://www.myexample.com/get/image.php?vcid=" + randomnumber + "&t=481";
I'd personally suggest:
var img = document.getElementById('imge');
img.src = img.src.replace(/vcid=(\d+)/, function(){
return randomnumber=Math.floor(Math.random()*99999);
});
// purely to see the src has been changed, this is *not* relevant or required
img.title = img.src;
<img src="http://www.myexample.com/get/image.php?vcid=14851&t=481" alt="" id="imge"/>
References:
JavaScript Regular Expressions.
String.replace().
Related
I would like to improve a code that I have in the sidebar of wordpress, where what I want is that every time people enter randomly loads an image. At the moment with the code I have shown below it works, but when I put my page in google speed it says this:
Avoid use: document.write()
link = new Array();
link[0] = '<img src="" width="300" height="408"/>';
link[1] = '<img src="" width="300" height="408"/>';
link[2] = '<img src="" width="300" height="408"/>';
link[3] = '<img src="" width="300" height="408"/>';
random = Math.random() * (link.length);
random = Math.floor(random);
document.write(link[random]);
<div id="bloquewidget"></div>
There doesn't look to be any need for the array or randomness since the link HTMLs are all the same. Create an <a> with createElement, then use a CSS selector to insert it into the document at the appropriate point. You'll need some way to uniquely identify this <div> - use a class if it already has one, or give the div a class, such as link-container:
const a = document.createElement('a');
a.target = '_blank';
a.rel = 'noopener nofollow';
// do you want to add a non-empty src to the a here?
const img = a.appendChild(document.createElement('img'));
img.width = 300;
img.height = 408;
// do you want to add a non-empty src to the image here?
// insert <a> at the bottom of this div:
document.querySelector('.link-container').appendChild(a);
the
document.write(link[random]);
part can be replaced with:
document.body.innerHTML = document.body.innerHTML + link[random];
It is also worth looking into createElement for creating DOM objects like anchors.
Well I found another solution to my problem I leave the code here in case anyone else needs to put in a wordpress a widget with images that are randomly generated with their own link and not using the deprecated code document.write
<div id="bloquewidget">
<a id="a" rel="nofollow noopener noreferrer" target="_blank"><img id="image" /></a>
<script type='text/javascript'>
var images =
[
imageUrlPair = { ImgSrc:"your URL image here", Href:"your URL here" },
imageUrlPair = { ImgSrc:"your URL image here", Href:"your URL here" },
imageUrlPair = { ImgSrc:"your URL image here", Href:"your URL here" },
imageUrlPair = { ImgSrc:"your URL image here", Href:"your URL here" },
]
function randImg() {
var size = images.length;
var x = Math.floor(size * Math.random());
var randomItem = images[x];
document.getElementById('image').src = randomItem.ImgSrc;
document.getElementById('a').href = randomItem.Href;
document.getElementById("image").height = "408";
document.getElementById("image").width = "300";
}
randImg();
</script>
Say I have an image tag such as this:
<img src="smiley.gif" alt="Smiley face" height="42" width="42">
I know I can get the src by using myImageEl.src.
However, how do I get the type of the src (.gif in this case)?
Basically, my end goal is to pass the file type to window.URL.createObjectUrl()
let src = imageEl.src;
let srcType = src.type; // Here I need to get the type
let videoFile = new Blob([src], {type: srcType});
let videoSrc = window.URL.createObjectURL(videoFile);
var imgSrc = 'image.jpeg';
var ext = imgSrc.replace(/^.*\./, '')
I am not very good with regex, but using regex to fetch the extension of the image or video is the a good way of accomplishing this task.
For precision sake you could compare ext with a predeifined set of array
imgTag = ['jpg', 'jpeg', 'gif', 'png'];
vidTag = ['mp4', '3gp']
then you can compare using a forEach loop
From your tags I noticed you want to access image source type from javascript, if so you can use following codes base on what attributes we have for that image element:
for example if image element has id :
var imageElement = document.getElementById(id);
var imgsrc = imageElement.src;
var imgType = imgsrc.split('.').pop();
imgType will be the type of your image.
And if your image element doesn't have id, you can use document.getElementsByTagName("img") instead of document.getElementById(id) and code will look like this
var imageElement = document.getElementsByTagName("img");
var imgsrc = imageElement.src;
var imgType = imgsrc.split('.').pop();
Instead of having a ton of if statements, I would like the method to display the correlated image by name, fx. clicking BlackPicture4.gif will turn it into WhitePicture4.gif. The number of the picture is passed on to the method.
I'm new to javascript, so maybe indexes[] don't work as I thought they do.
I have an array of Whitepicures:
imgArray[1] = new Image();
imgArray[1].src = "WhitePicture1.gif";
...
function changePicture(int)
{
var image = document.getElementById('Img' + int); //works
image.src = imgArray[int] //doesn't work
var thefile = "imgArray" + int + ".gif" //also doesn't work
image.src = thefile;
}
I tried so many different ways, but could use help
html: //as requested, but that works fine
<img id="Img1" onclick="changePicture(1)" src="Blackpicture1.gif" width="50" height="50" >
<img id="Img2" onclick="changePicture(2)" src="Blackpicture2.gif" width="50" height="50" >
...
Edit: The problem is solved by adding .src to "= imgArray[int]"
Another thing I didn't think of was I had to assign the array elements INSIDE a function, rather than just on top of the file where I believe only declarations can be made.
This may work im not sure
imgArray[1] = new Image();
imgArray[1].src = "WhitePicture1.gif";
var x;
function changePicture(x) {
var image = document.getElementById('Img' + x);
image.src = imgArray[x].src;
}
I think what you're trying to do might be
function changePicture(int){
document.getElementById('Img'+int+'').setAttribute('src',imageArray[int].src);
}
In this example, the pic with id='1' will be converted into a pic with id='2':
$("img").click(function() {
var x = $(this).attr("id");
x++;
var y = $("#" + x).attr("src");
$(this).html("");
$(this).html("<img src='" + y "'>");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="pic1.jpg" id="1">
<img src="pictobereplaced.jpg" id="2">
I have:
var cnt = '
<img alt="pic1" src="/data/18139/1.jpg" />
<div>
<p>
<img alt="pic2" id="zwei" src="/data/18139/2.jpg" />
</p>
<img alt="pic3" src="/data/18139/3.jpg" />
</div>';
I want to get/set the alt attribute of an img tag by giving the src attribute, no matter how deep the img is.
I tried:
$(cnt).find("img[src$='"+pic+"']").attr('alt'); //can only get the object
$(cnt).filter("img[src$='"+pic+"']").attr('alt') //can only get the alt on the root of thre DOM.
Also tried some combinations and .find(function(... but I simply can´t work it out.
The special thing is, I can not work directly in the DOM. My HTML is stored in the cnt variable. So I´m calling a function like this:
function refreshEditorAlt(src,newalt){
var cnt=getEditorContent();
var newcnt = cnt.replace($("img[src$='"+src+"']", cnt).attr('alt'), newalt);
setEditorContent(newcnt);
}
You can try this code, note that jQuery methods can help you much:
var cnt = '<img alt="pic1" src="/data/18139/1.jpg" /><div><p><img alt="pic2" id="zwei" src="/data/18139/2.jpg" /></p><img alt="pic3" src="/data/18139/3.jpg" /></div>';
var $cnt = $("<div>" + cnt + "</div>");
//input
var src = "/data/18139/1.jpg";
var newAlt = "Xpic";
//update new alt
$cnt.find("img[src$='" + src + "']").attr('alt', newAlt);
//output
cnt = $cnt.html();
$('#out').text(cnt);
Demo.
Note that you should wrap the cnt into some element (such as a <div></div>) so that you can use jQuery to solve your problem.
Try this to get the value:
$(cnt).find("img[src$='"+pic+"']").attr('alt');
Try this to set the value:
$(cnt).find("img[src$='"+pic+"']").attr('alt', newValue);
I think your problem is with the line breaks where you've defined the variable cnt. So instead you want:
var cnt = '<img alt="pic1" src="/data/18139/1.jpg" /><div><p><img alt="pic2" id="zwei" src="/data/18139/2.jpg" /></p><img alt="pic3" src="/data/18139/3.jpg" /></div>';
And then something like this will work:
alert($(cnt).find("img[src$='/data/18139/2.jpg']").attr('alt'));
Obviously you're wanting to pass the value of src into a function or something, but hopefully this should solve your problem.
Quick demo to show it works this way http://jsfiddle.net/4z5Sh/
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( /^.+\// , '' ));