<div id="3" class="dsi" onmousedown="test(3);" ondrop="checkImg('3');dropIt(event,3);" ondragover="event.preventDefault();">
<img src="1.gif" draggable="true" ondragstart="dragIt(event,4);" id="pic4" />
I want to change src value using javascript. There are nine dives and they already have 1 to 9 gif images. How can I add new src values leaving the rest of the things unchanged? (I mean draggable="true" ondragstart="dragIt(event,4);" id="pic4")
function ft1() {
var imgSrcs = ['2.gif', '1.gif', '3.gif', '4.gif', '5.gif', '6.gif', '7.gif', '8.gif'];
var myImages = [];
for (var i = 0 ;i <=((imgSrcs.length)-1);i++) {
var v = i;
var img = new Image();
img.src = imgSrcs[i];
var div0 = document.getElementById(v+1);
div0.appendChild(img);
myImages[v+1] = img;
}
Using this I can replace div images. But how can I remove first assigned src value and then replace new images?
As stated here, simply do:
document.getElementById("pic4").src="...";
Try this.
$('.img').attr('src','http://source');
Related
I am struggling to work out how to make all instances of images with the id="cover__thumb" rotate randomly through the predefined images.
Currently only the first id="cover__thumbs" will rotate, it has no affect on the other images with the same id.
There won't always be 4 images, sometimes more sometimes less. Is there a solution that works for any image with the this id?
Fiddle
https://jsfiddle.net/bpLdkhg0/
JS
function rotateImages()
{
var thumbImages = new Array( );
thumbImages[0] = "https://upload.wikimedia.org/wikipedia/commons/e/eb/Ash_Tree_-_geograph.org.uk_-_590710.jpg";
thumbImages[1] = "http://cdn.images.express.co.uk/img/dynamic/13/590x/magnolia-tree-630524.jpg";
thumbImages[2] = "http://cdn.images.express.co.uk/img/dynamic/109/590x/Oak-tree-580618.jpg";
var image = document.getElementById('thumb__cover');
var randomImageIndex = Math.floor( Math.random( ) * thumbImages.length );
image.src = thumbImages[randomImageIndex];
}
window.setInterval(rotateImages, 1000);
HTML
<img id="thumb__cover" src="http://pic.1fotonin.com//data/wallpapers/121/WDF_1633007.jpg" style="width:150px;">
<img id="thumb__cover" src="http://pic.1fotonin.com//data/wallpapers/121/WDF_1633007.jpg" style="width:150px;">
<img id="thumb__cover" src="http://pic.1fotonin.com//data/wallpapers/121/WDF_1633007.jpg" style="width:150px;">
<img id="thumb__cover" src="http://pic.1fotonin.com//data/wallpapers/121/WDF_1633007.jpg" style="width:150px;">
Use the class attribute if you want to select multiple DOM elements at once:
HTML:
<img class="thumb__cover" ... />
JS:
var images = document.querySelectorAll(".thumb__cover");
or
var images = document.getElementsByClassName("thumb__cover");
Now, images is a nodeList that can have any number of elements. To set the src attribute for each of them, you'll have to loop through the items in the list:
for (var i = 0; i < images.length; i += 1) {
var image = images[i];
var randomImageIndex = Math.floor(Math.random() * thumbImages.length);
image.src = thumbImages[randomImageIndex];
}
More about node lists: https://developer.mozilla.org/en/docs/Web/API/NodeList
Problem: The previously loaded images have to be changed dynamically when a new image is downloaded and detected by image.onload event. Say, picture1.png downloaded and immediately changed, picture2.png downloaded and immediately changed and so on. I have tried it as below, but it didn't work:
<script type="text/javascript">
loadImage = function(){
var imgs = new Array();
var IMG = document.getElementsByTagName('img');
for(var i=1;i<=IMG.length;i++)
{
imgs[i] = new Image();
imgs[i].src = "picture" + i + ".png";
imgs[i].onload = function(){
alert('picture'+i+' loaded');
IMG[i].setAttribute('src',imgs[i].getAttribute('src'));
}
}
}
</script>
<img src="sample.png" />
<img src="sample.png" />
<img src="sample.png" />
<img src="sample.png" />
<input type="button" value="Load Image" onclick="loadImage()">
How things will happen in the desired manner?
From this answer,
Well, the problem is that the variable i, within each of your
anonymous functions, is bound to the same variable outside of the
function.
What you want to do is bind the variable within each function to a
separate, unchanging value outside of the function:
So your code should look somewhat like this :
<script type="text/javascript">
var IMG = document.getElementsByTagName('img');
var imgs = new Array();
loadImage = function(){
for(var i=0;i<IMG.length;i++)
{
imgs[i] = new Image();
imgs[i].src = "http://dummyimage.com/150/000/fff&text=Image"+i;
imgs[i].onload = onloaded(i);
}
}
function onloaded(i) {
IMG[i].setAttribute('src',imgs[i].getAttribute('src'));
}
</script>
<img src="http://placehold.it/150" />
<img src="http://placehold.it/150" />
<img src="http://placehold.it/150" />
<img src="http://placehold.it/150" />
<input type="button" value="Load Image" onclick="loadImage()">
Note : array index of IMG starts with 0
If I understood your question correctly, you want to change the placeholder images as soon as the new images are completely loaded. By just passing the src attribute you rely on caching but the method below, although untested, should do the replacing in place. The i is kind of like a pointer which holds the growing value, so you can't use it as a reference in event callbacks.
function loadImage() {
var imgs = document.querySelectorAll("img");
for (var i = 0; i < imgs.length; i++) {
var newImg = new Image();
newImg.src = "picture" + i + ".png";
newImg.onload = function(img) { // Construct a callback for this <img>
return function() {
img.parentNode.replaceChild(newImg, img);
}
}(imgs[i]);
}
}
Edit: as said, I previously introduced another scoping issue in my code when fixing the original one. This is now fixed with a callback constructor function.
Because variables declared with the var keyword is function scoped and the onload function executes after the loop has finished variable i will not equal the value of i in that iteration when executing.
Replace your onload function with this code instead. It will create a new function scope.
imgs[i].onload = function(index) {
return function(index) {
alert('picture' + index + ' loaded');
IMG[index].setAttribute('src', imgs[index].getAttribute('src'));
}
}(i)
I would also change you're code to not loading the image twice.
function loadImage() {
var images = document.getElementsByTagName('img');
for (var i = 0; i <= images.length; i++) {
var newImg = new Image();
newImg.src = "http://dummyimage.com/150/000/fff&text=Image" + i;
newImg.onload = function(index, newImg) {
return function() {
var img = images[index];
img.parentNode.replaceChild(newImg, img);
}
}(i, newImg)
}
}
I am trying to insert image values into the html to replace the src according to the name so if the name for the templateName = Javascript I can make the src value = something like say (http://www.w3devcampus.com/wp-content/uploads/logoAndOther/logo_JavaScript.png) and do that for other categories as well using an if/else statement in javascript.
my script look like this but it has a few errors with the syntax
var imageChoosernator = function () {
if (#templateName == "Javascript")
{
img = <img src="htp://www.w3devcampus.com/wp-content/uploads/logoAndOther/logo_JavaScript.png">;
}
` }
Can someone guide me toward the proper solution?
# in #templateName is wrong. Know your allowed variable characters.
img = <img the <img is an unstarted String. Know how to enclose values into String.
` <<< you cannot have such character floating around your code (hopefully just an edit typo).
Since you didn't showed most of your code, a fix would be something like:
var img = "";
var templateName = "Javascript";
function imageChoosernator () {
if (templateName === "Javascript") { // remove unallowed #
img = '<img src="js.png">'; // enclose into String
} else {
img = '<img src="someting.png">';
}
// Finally append img to element #imgContainer
document.querySelector("#imgContainer").insertAdjacentHTML("beforeend", img );
}
imageChoosernator(); // Do the magic
You can use jQuery .prepend() method to replace the image src on loading the query into the page.
If in html you have given the id name as 'JavaScript' like-
div id="JavaScript"><img id="imgNew1" src="oldImg1.png" />
div id="templateName2"><img id="imgNew2" src="oldImg2.png" />
To change the image source following can be used-
$('#templateName1').prepend('<img id="imgNew" src="newImg1.png" />')
$('#templateName2').prepend('<img id="imgNew" src="newImg2.png" />')
You need to read the documentation here
To automatize the src change while creating intances of the same will go like-
<html>
<head>
<script type="text/javascript">
var slideimages = new Array() // create new array to preload images
slideimages[0] = new Image() // create new instance of image object
slideimages[0].src = "firstImg.png" // set image object src property to an image's src, preloading that image in the process
slideimages[1] = new Image()
slideimages[1].src = "secondcarImg.png"
slideimages[2] = new Image()
slideimages[2].src = "thirdImg.png"
</script>
</head>
<body>
<img src="firstImg.img" id="slide" width=100 height=56 />
<script type="text/javascript">
//variable that will increment through the images
var step = 0
var whichimage = 0
function slideit(){
//if browser does not support the image object, exit.
if (!document.images)
return
document.getElementById('slide').src = slideimages[step].src
whichimage = step
if (step<2)
step++
else
step=0
}
</script>
</body>
</html>
I am trying to make a image slide show and I am passing urls of the images through a List in a Model.
List<string>
Onload I want to assign these URL values to JavaScript variables.
var image1=new Image()
var image2=new Image()
var image3=new Image()
My question is, how can I assign this list of URLs to the above variables, normally I can do this:
image1.src="value.jpg"
How can assign the value using Razor within JavaScript?
This razor code will create an image object with the index for each element in your List of strings and will set its src property.
<script>
#for (var idx = 1; idx <= Model.ListOfImages.Length; ++ i) {
<text>
var image#(idx) = new Image();
image#(idx).src = '#Model.ListOfImages[idx]';
</text>
}
</script>
Of course you will want to wrap it in the script tag. The output will be JavaScript that looks something like this:
<script>
var image1 = new Image();
image1 = 'image1.jpeg';
var image2 = new Image();
image2 = 'image1.jpeg';
var image3 = new Image();
image3 = 'image1.jpeg';
</script>
A couple of ways to solve this:
Use Razor to generate JavaScript
<script type="text/javascript">
var images = [], image;
#foreach (var image in ListOfImages)
{
image = new Image();
image.src = #image.url;
images.push(image);
}
</script>
Use Razor to generate HTML, then have JavaScript use the HTML for the slideshow
<div class="slideshow">
<ol>
#foreach (var image in ListOfImages)
{
<li><img src="#image.url"></li>
}
</ol>
Prev
Next
</div>
<script type="text/javascript">
// some imaginary jQuery plugin to create a slideshow
$(".slideshow").slideshow();
</script>
I'm partial to solution #2. I try to avoid having a server side templating language generate code in more than one language if at all possible. In solution #2, Razor is just generating HTML.
Short of going for something like Galleriffic
and modifying, hiding and removing elements, what would be a way to add a function by which thumbnails can also be clicked to display the image?
Much obliged to anyone who can point me in the right direction. I'm using the following by Paul McFedries at mcfedries.com.
<script type="text/javascript">
<!--
// Use the following variable to specify
// the number of images
var NumberOfImages = 3
var img = new Array(NumberOfImages)
// Use the following variables to specify the image names:
img[0] = "yellow1.jpg"
img[1] = "blue2.jpg"
img[2] = "green3.jpg"
var imgNumber = 0
function NextImage()
{
imgNumber++
if (imgNumber == NumberOfImages)
imgNumber = 0
document.images["VCRImage"].src = img[imgNumber]
}
function PreviousImage()
{
imgNumber--
if (imgNumber < 0)
imgNumber = NumberOfImages - 1
document.images["VCRImage"].src = img[imgNumber]
}
</script>
in the html:
<div class="galleryarrows">
<A HREF="javascript:PreviousImage()">
<IMG SRC="previous.png" BORDER=0></A>
<A HREF="javascript:NextImage()">
<IMG SRC="next.png" BORDER=0></A>
</div>
A quick, basic solution: Save the full size versions of your images in a folder called say, 'full_images', with the same names as the thumbnails.
Add an onClick event into the element img elements that display your thumbnails in the html, so they look something like this.
<img src = "yellow1.jpg" name = "thumb[0]" style = "cursor:pointer" onClick = "Javascript:DisplayImage(0);" alt = "yellow"/>
<img src = "blue2.jpg" name = "thumb[1]" style = "cursor:pointer" onClick = "Javascript:DisplayImage(1);" alt = "blue"/>
<img src = "green3.jpg" name = "thumb[2]" style = "cursor:pointer" onClick = "Javascript:DisplayImage(2);" alt = "green"/>
In your javascript, add this function
function DisplayImage(id){
imgNumber = id;
document.images["VCRImage"].src = "full_images/" + img[id];
}
This will display in an element with the name 'VCRImage'.
Not my favourite solution this, but quick, and should work. If Javascript is new to you, then you might as well check out jQuery. It's a lot easier to use, and is way more cross-browser compatible.