I have one image (img.png), with its content changing after a combo box changes.
The problem is the content of the image doesn't change when I change the combo box on the page.
I tried to use JavaScript like this:
function SwitchPic(pic) {
pic.src = "img.png";
}
and the img tag is:
<img src='img.png' id='img1' name='img1'>
and the combo box tag is:
<select name="users" onchange="show(this.value);SwitchPic(img1);">
<option value="">Select a Number:</option>
<option value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>
</select>
It worked the first time I change the option, but when I re-change the option, it keeps the image without changing it.
How can I solve this?
Might be just a cache problem
Instead of just using the filename, add a random part to it, like 'img.png?random', that way you'll force the browser to look for the image again on the server, but the ?random part will be discarded anyway and the file will still be found
Easiest way to do this is to add the date/time after the extension
You are attempting to pass your image tag as smg1 but you don't declare that that is your image element.
try this:
SwitchPic('img1');
and then in your handler:
function SwitchPic(picID) {
var pic = document.getElementById(picID);
pic.src = "img.png";
}
In this scenario you pass the ID of the element you want to change then acquire the actual element inside your handler.
I think your problem is that there is :
An image by the name of img.png.
A function keeps changing the actual img.png with other image but with the same name img.png
You re-assign the image tag src attribute but the image doesnt refresh.
If that is the case then it is an issue of image caching of browser.
refer to the links below :
How to reload/refresh an element(image) in jQuery
how to force chrome not to reload images with same url till the page is refreshed ,like firefox
How to force a web browser NOT to cache images
hope it helps!
Two problems:
Your function only changes it to that image, rather than toggling it.
You're passing a variable img1, which is not defined. You need to pass the image's ID and then use that to get the node.
So, you need to use document.getElementById() to get your image and then you need to toggle each time:
var clicked = false;
function SwitchPic(pic) {
var image = document.getElementById(pic);
if(!clicked){
image.src = "otherImg.png";
clicked = true;
}else{
image.src = "img.png";
clicked = false;
}
}
Demo
Related
I have an assignment where I need to make a photo appear when I click on another photo. I need to put each image in an array and call on it to appear when I click on the corresponding photo. When I click on another photo, I need to remove the existing photo and replace it with another one. I need to do it with Javascript and the DOM. I'm unsure how exactly I would do this. Here's my code so far:
var photoDiv = getElementById("photos");
document.getElementById("0").addEventListener("click", function () {
var img = createElement("img");
photoDiv.appendChild(img);
})
I know it's completely wrong but I don't know what to do to fix it :(
You have to add the image source of your image.
After this line:
var img = document.createElement("img");
img.src = 'pathto/yourimg.png_or_jpg'; // You need this.
Also, it's always a good practice to use document.getElementById() (or putting the parent) instead of just getElementById().
Instead of creating a new image you can also replace only the src of the image element, something like this:
// get the image
var imgElement = document.getElementById("myImage");
// add the listener
imgElement.addEventListener("click",
function () {
// update the src of the image
imgElement.src = "https://www.w3schools.com/html/img_girl.jpg";
});
and that's all, you should not create a new element and append it to the DOM element.
I'm making an extension that grabs an image URL within the "uCW" div on an HTML page.
Currently, I have:
var uCW = jNode.closest("div._q7o");
var image = uCW[0].children[1].getElementsByTagName("img")[0].src;
console.log(image);
That finds the image by going into the div/children and pulling the image. Unfortunately, this method is problematic, since it stops working if the children change, which they regularly do.
Instead, I want to select the image by searching the div and all its children (there are a lot of them) for the first image/string that starts with "https://external" (all the images I want start this way, and that doesn't seem to change.)
This is what I tried:
var uCW = jNode.closest("div._q7o");
var image = $(uCW).find([name^="https://external"]).src;
console.log(image);
This doesn't work. The console just prints "undefined."
You could do it like this, if ucw is a classname (if it's an id, you would write $("#ucw") instead):
var image = $(".ucw").find('[src^="https://external"]').attr("src");
console.log(image);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="ucw">
<img src="https://external/1.jpg"/>
</div>
If your images have a name attribute with the source of the image as value, you can also adjust your attempt to fetch the images via their name attribute like you did:
var image = $(".ucw").find('[name^="https://external"]').attr("src");
I'm trying to make some basic image slider as a part of JS excersises, and I've noticed something weird when I ran this script.
The source of an image stored in array under the 0 index is changing when I'm trying to change source image in html code with 'setAttribute' method, so when I want to get back from fifth image to one, this proto-slider (nothing is sliding at the moment) is stuck at second image.
My files are named 0.jpg - 5.jpg.
I've preloaded the images to be displayed smoothly without flicker and I'm displaying one image after the page loads, and then I'm trying to change source of this image to source of next image in array of images. Is this the right way to do it?
Here's the code:
var images = new Array(5);
var i=0;
function addImages(){
for (var j=0;j<images.length;j++){
images[j] = new Image();
images[j].src = j+".jpg";
console.log(images[j].src);
}
var article = document.getElementById("article");
article.insertBefore(images[0], document.getElementById("nav"));
}
function next(){
if (i<images.length-1){
document.getElementsByTagName('img')[0].setAttribute('src',images[++i].src);
console.log(images[0].src);
}}
function prev(){
if (i>0){
document.getElementsByTagName('img')[0].setAttribute('src', images[--i].src);
console.log(images[0].src);
}
}
What is the best way to do such a this as dynamically changing image sources?
I've thought about this:
article.removeChild(document.getElementsByTagName("img")[0]);
article.insertBefore(images[++i], document.getElementById("nav"));
I want to know if this isn't considered as a bad practice and what are the other ways to do it in single line of code.
Thanks in advance and sorry for grammar mistakes.
You could just insert empty image
<img id="someid">
and then use document.getElementById("someid").src=images[0].src
If you'd like to be sure that images[0] is completely loaded, use onload function, like:
images[0].onload=function()
{
document.getElementById("someid").src=images[0].src;
}
I'm looking for a solution to render image before uploading via input URL.
My code
<input name="thumbnail" placeholder="Post image URL here" />
I've been trying methods like this. Adding onchange="readURL(this);" to above mentioned code does nothing. It appears they only work with local files only.
use the value of the input as the source for an image tag. You can hide and show the image tag, create a new image each time, wait for the load event and show a spinner, use a default image, the possibilities are endless.
$('[name="thumbnail"]').on('change', function() {
$('img.preview').prop('src', this.value);
});
FIDDLE
You could use canvas.
var oCanvas = doc.getElementById('imgThumb'),
oContext = oCanvas.getContext('2d');
oContext.drawImage(this, 0, 0, nWidth, nHeight);
Try out my fiddle http://jsfiddle.net/aliasm2k/tAum2/
Couldn't find a punctual answer for this simple task and your help is highly appreciated
We have an image we want to switch based on user's color selection.
Tried several methods, none worked.
This is the idea:
$('#YourButton').click(function() {
var oldSrc = 'images/Image1.png';
var newSrc = 'images/Image2.png';
$('img[src="' + oldSrc + '"]').attr('src', newSrc);
});
Just change the image source with javascript by clicking your button with another color
Note: it´s jquery so you have to include the js file..
Just bind a click listener to your button and change the src attribute of your image.
$('#colorButton').click( function() { //choose a new color
$('#imageIcon').attr('src', 'path/to/new/image.png'); //change the img's source
});
EDIT (response to questions):
If you want this code to apply to all of your buttons, give each of your buttons a similar class instead of an ID:
<div class="colorButton"></div>
Then you can use the following selector to apply the above click listener to all of these divs:
$('.colorButton')
Naturally, you want to change your image as simply as possible. You could map all of your colors to their corresponding image file, but as far as design goes this might get messy and unwieldy. I would create a directory that stores all of your image files (for example, /your/color/swatches) and give each of them a name consistent with their color, like 'ff0000.png' for red, '0000ff.png' for blue, etc.
Why would we do this? So that we can switch your image based on the background-color attribute of your buttons. Let's say that you have the following buttons:
<div class="colorButton" style="background-color: '#ff0000'"></div>
<div class="colorButton" style="background-color: '#0000ff'"></div>
You can use the same click listener, but it will have to be modified a bit since we are mapping the background color to an image:
$('.colorButton').click( function() {
var color = $(this).css('backgroundColor');
//(You'll need to modify your color string here)
$('#imageIcon').attr('src', 'your/color/swatches/' + color + '.png');
});
BUT this won't work yet. Since most browsers return "rgb(xx, yy, zz)" from .css('backgroundColor'), you need to convert that string into hex. This post on SO gives a more or less effective way to do so, but you'll need to modify it to fit your model where I have indicated.