Multiple Id's calling on same JavaScript function - javascript

I am trying out a JavaScript where it takes Id of an image and onclick of the image it performs some function. But I have multiple Id's of same image where the id of the onclick'ed image should be processed by JavaScript and the operation should be performed.
Problem is I am not able to get the right id based on the click.
here is my code
1)myhtml
<div class="col-md-3 col-sm-6">
<div class="sub-process-block quantity">
<h3>choose quantity</h3>
<div id="example" onclick="changeImage()">
<img src="img/carton-empty.png" id="myImage">
<img src="img/carton-empty.png" id="myImage1">
<img src="img/carton-empty.png" id="myImage2">
</div>
</div>
2)javascript
<script>
function changeImage() {
var imageArray=["myImage","myImage1","myImage2"];
for(var i=0;i<imageArray.length;i++ ){
image = document.getElementById(imageArray[i]).onclick;
}
if(image.src.match("selected")) {
image.src="img/carton-empty.png";
}else{
image.src = "img/carton selected.png";
}
}

Why don't you add an event listener to your images in JS? Then you can check if it's selected or not and update the source accordingly
// get all images and put them in an array
var images = [].slice.call(document.querySelectorAll('img'));
// loop through images and add event listener
images.forEach(function(image) {
image.addEventListener('click', onImageClick);
});
// on click, check if image is selected and update src
function onImageClick(e) {
var image = e.target;
if (image.src.match("selected")) {
// is selected, now unselected it and update src
image.setAttribute('src', 'img/carton-empty.png');
} else {
// is not selected, now select it and update src
image.setAttribute('src', 'img/carton selected.png');
}
}
https://jsfiddle.net/0qzdsf8r/4/
Inspect the image elements in the dev tools and see the class and src change.

Try this ;)
function changeImage(){
var imageArray = ["myImage", "myImage1", "myImage2"];
for(var i = 0; i < imageArray.length; i++){
var image = document.getElementById(imageArray[i]);
if(image.src.match("selected")){
image.src = "img/carton-empty.png";
}else{
image.src = "img/carton selected.png";
}
}
}
You placed condition outside for loop;

Related

Javascript - How to select an image loaded from an array

So, I have four images that I put on the page from an array using a loop. Now I have the four images on the page, but I am looking for a way to allow the user to click on any of the images and display a large version of whichever one they click. I was thinking of using a new empty array, using push? to store the clicked image, but I don't know how to click on the images (because I 'm not using an img tag) and load the one that is clicked.
var arrayarray= [
"1.jpg",
"2.jpg",
"3.jpg",
"4.jpg"
];
var clicked =[];
function asdasd (){
for (var i = 0, j = arrayarray.length; i < j; i++) {
var fmg = document.createElement('img');
fmg.setAttribute("src", arrayarray[i]);
fmg.setAttribute("class", "fmss");
container.appendChild(fwfw);
if (??){
clicked.push(i);
}
}
}
You could add onClick event to an image node.
Selecting the image logic is handled by onClick function. In my example selectedImage variable stores the selected url.
See working example:
const images = [
"1.jpg",
"2.jpg",
"3.jpg",
"4.jpg",
];
let selectedImage = null;
const result = document.getElementById('result');
const container = document.getElementById('container');
const onClick = function() {
selectedImage = this['data-url']; // or this.src
// just for showing output in html
result.innerText = selectedImage;
};
// on Init
for (let i = 0; i < images.length; i++) {
const fmg = document.createElement('img');
fmg.setAttribute("src", images[i]);
fmg.setAttribute("class", "fmss");
fmg.setAttribute("alt", images[i]);
fmg.onclick = onClick;
fmg['data-url'] = images[i];
container.appendChild(fmg);
}
.fmss { border: 2px solid black; margin: 10px; }
.result { margin: 20px; }
Click me
<div id="container"></div>
<div id="result"></div>
No array needed. Just set the src of the big picture the to src of the clicked picture.
let main = document.getElementById("main"); // Get reference to main image
// Set up click event handler on thumbnail container
document.addEventListener("click", function(event){
// Check to see if the clicked element is a thumbnail
if(event.target.classList.contains("thumb")){
main.src = event.target.src; // Set main picture to match the thumbnail
}
});
.thumb { width:40px; }
#main { width:125px; }
<div id="picContainer">
<img src="https://spectator.imgix.net/content/uploads/2015/06/Emoji.jpg?auto=compress,enhance,format&crop=faces,entropy,edges&fit=crop&w=620&h=413" class="thumb">
<img src="https://i.pinimg.com/originals/43/7b/9b/437b9bbf3fde6d6a331b52bf6c422850.jpg" class="thumb">
<img src="https://cdn3.volusion.com/ghfyz.wgnwv/v/vspfiles/photos/LOF-A3-3650-2.gif" class="thumb">
<img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQisqxRpIXDaOgpdYoy_4UgSKLjaFXM6qIEa4zAOjFIsh_Plp5R" class="thumb">
</div>
<img id="main" src="">

Change Image Source from Div with onmouseover

Is it possible to change the image source from the containing div? The images are dynamic and pulled from the database.
v = $"<div onmouseover=\"document.navIcon.src='/Images/White/{reader[2]}';\"
onmouseout=\"document.navIcon.src='/Images/{reader[2]}';\">
<img name=\"navIcon\" src=\"Images/{reader[2]}\"><br>{reader[1]}</div>";
That was my thoughts on how to do it but it doesn't appear to work as expected. I was able to get it to work when I put the onmouseover portion in the < img > however, I want it to change anywhere in the div, like over the reader[1] text, not just directly over the image.
Thoughts?
I just grabbed some images off google images. You can use this to refer to the current element.
<img
src='https://osu.ppy.sh/forum/images/smilies/50.gif'
onmouseover='this.src="http://4.bp.blogspot.com/-YrmTHhfMtFU/VJNbpDMHzgI/AAAAAAAAH8c/g3dJ1Q-QTrc/s1600/smile.png"'
onmouseout='this.src="https://osu.ppy.sh/forum/images/smilies/50.gif"'
/>
Edit..
This will change the image when you hover on anything with a "hoverme" class name.
(function() {
var img1 = "https://osu.ppy.sh/forum/images/smilies/50.gif";
var img2 = "http://4.bp.blogspot.com/-YrmTHhfMtFU/VJNbpDMHzgI/AAAAAAAAH8c/g3dJ1Q-QTrc/s1600/smile.png";
var myimg = document.getElementById('myimg');
myimg.src = img1;
var hoverables = document.getElementsByClassName('hoverme');
for (var i = hoverables.length; i--;) {
hoverables[i].addEventListener("mouseover", hoverMe, false);
hoverables[i].addEventListener("mouseout", unhoverMe, false);
}
function hoverMe() {
myimg.src = img2;
}
function unhoverMe() {
myimg.src = img1;
}
})();
<img class='hoverme' id='myimg' />
<p class='hoverme'>poooooooop</p>
<div class='hoverme'>This si a diiiiivvvvv</div>
The best way to accomplish that is to use CSS.
HTML
<img id="NavIcon">
CSS
#Navicon {
background-image: url(image1.jpg);
}
#NavIcon:hover {
background-image: url(image2.jpg);
}

Random image click

So I got a site full of images and they are are all in random order, everytime you refresh the page. You have to search for a image which is always on a different place.
function randomWaldo() {
var randomNummer = Math.floor((Math.random() * 100) + 1);
document.getElementsByTagName('img')[randomNummer].src = "images/waldo.jpg";}
Now I want the first paragraph in my HTML to change when you click on that one image. How can I do this?
You can try to select the image who have the wanted source.
And add a class or id to your paragraph for readability.
document.querySelectorAll("img[src='images/waldo.jpg']")[0].onclick=function()
{
document.getElementById("paragraphid").innerHTML="You win";
};
Example
document.querySelectorAll("img[src='image/waldo.jpg']")[0].onclick=function()
{
document.getElementById("rep").innerHTML="you win !";
}
img{
height:100px;
width:100px;
}
<p id="rep"></p>
<img src="image/nok.jpg" alt="nok">
<img src="image/nok.jpg" alt="nok">
<img src="image/nok.jpg" alt="nok">
<img src="image/waldo.jpg" alt="waldo">
<img src="image/nok.jpg" alt="nok">
<script type="text/javascript" >
var images = document.getElementsByTagName('img');
//find all paragraphs
var paragraphs = document.getElementsByTagName('p');
//define function called on click
function changeParagraph() {
//change first paragraph if exists
if(paragraphs.length) {
paragraphs[0].innerHTML = 'I have been changed!';
}
}
/*
for(var i = 0; i < images.length; i++) {
//set onclick event to every image
images[i].onclick = changeParagraph;
}
*/
// set onclick to the randomImage
images[randomNumber].onclick = changeParagraph;
</script>
Assuming your first paragraph exists before the user clicks the picture, you can add an onClick element to your img tag. Try something like this, changing the URL obviously for your own picture:
<p id = "first">You haven't found Waldo
</p>
<img id = "waldo" src = https://pbs.twimg.com/profile_images/561277979855056896/4yRcS2Zo.png
onclick = "addparagraph()"
/>
JavaScript:
function addparagraph(){
document.getElementById("first").innerHTML = "you found Waldo!";
}

Multiple thumbnails before image upload

I am very unexperienced in Javascript/Jquery therefore I use the JavaScript Load Image plugin to handle the front end of my image upload process.
The Problem: I would like to upload multiple images, not just one, and therefore also would like to display all the images, which are to be uploaded as a thumbnail. At the moment just one image is shown as a thumbnail.
The Fiddle: https://jsfiddle.net/r7s3n64b/1/ (displaying just one thumbnail)
HTML (the relevant parts)
<!-- FILE INPUT -->
<p><input type="file" name="images[]" id="upload-post-images" multiple></p>
<!-- THUMBNAILS -->
<div id="result" class="result">
<p>This only works in browsers with support for the URL or FileReader API.</p>
</div><br>
My attempt to loop through the to be uploaded images:
replaceResults = function (img) {
var content;
var imageFiles = document.getElementById("upload-post-images"),
filesLength = imageFiles.files.length;
// Loop through the FileList and render image files as thumbnails.
for (var i = 0; i < filesLength; i++) {
if (!(img.src || img instanceof HTMLCanvasElement)) {
content = $('<span>Die Bilddatei konnte nicht geladen werden.</span>');
} else {
content = $('<a target="_blank">').append(img)
.attr('download', currentFile.name)
.attr('href', img.src || img.toDataURL());
}
result.children().replaceWith(content);
if (img.getContext) {
actionsNode.show();
}
} // end for loop
},
I would be very thankful for any kind of help!!
=== E D I T ===
In your fiddle the thumbnails are placed after the closing form tag:
</form>
<img src="blob:https%3A//fiddle.jshell.net/001bd1f5-1cce-4618-bc83-9c8bd24f9e90" width="200" height="150">
<img src="blob:https%3A//fiddle.jshell.net/001bd1f5-1cce-4618-bc83-9c8bd24f9e90" width="200" height="150">
In my project (using your code) the thumbnail is placed within the result div:
<div id="result" class="result">
<a target="_blank" download="image.jpg" href="data:image/png;base64,iVBO3sSxiFIz6LUNoB9b27d/p9/HzNSojY7M+FCmPOnGAsrVBWlKSGsSfG4GBNOzbIWtW38xtqwSLsTpzHF7/N4n7PwQgrIo5fh...></a>
<canvas width="265" height="354"></canvas>
</div>
Is there any chance that you would happen to have an idea why this is or how I could change that?!
Thank you so much for your tremendous help!
You need to change your on change function to this:
document.getElementById('upload-post-images').onchange = function (e) {
for(i = 0; i<=e.target.files.length; i++)
{
loadImage(
e.target.files[i],
function (img) {
document.body.appendChild(img);
},
{maxWidth: 200} // Options
);
}
};
Here is updated jsFiddle: https://jsfiddle.net/r7s3n64b/2/
Earlier your event handler looked like this:
document.getElementById('upload-post-images').onchange = function (e) {
loadImage(
e.target.files[0],
function (img) {
document.body.appendChild(img);
},
{maxWidth: 200} // Options
);
};
So beacuse of this line:
e.target.files[0]
You always pass only one image (first) from image array.
Enjoy! :)
UPDATE
Regarding your update - so basically it's all about the second parameter in loadImage function.
Change your upload-post-images change event like following.
document.getElementById('upload-post-images').onchange = function (e) {
$.each(e.target.files, function () {
loadImage(
this,
function (img) {
document.body.appendChild(img);
}, {
maxWidth: 200
} // Options
)
});
};
UPDATED FIDDLE

Javascript replacing image source

I am trying to change the contents of the src tag within a web page (without changing the HTML/naming structure)
My code looks something like this at the moment:
....
<div class="main">
<button>
<img src="image/placeHolder.png"/>
<div>the nothing</div>
</button>
</div>
....
I need to change the src of this img tag
My javascript looks like this at the moment
....
<script type="text/javascript">
function changeSource() {
var image = document.querySelectorAll("img");
var source = image.getAttribute("src").replace("placeHolder.png", "01.png");
image.setAttribute("src", source);
}
changeSource();
</script>
....
I have no idea why it isn't working but I'm hoping someone out there does :D
Change your function to:
function changeSource() {
var image = document.querySelectorAll("img")[0];
var source = image.src = image.src.replace("placeholder.png","01.png");
}
changeSource();
querySelectorAll returns an array. I took the first one by doing [0].
But you should use document.getElementById('id of img here') to target a specific <img>
If you want to target all <img> that has placeholder.png.
function changeSourceAll() {
var images = document.getElementsByTagName('img');
for (var i = 0; i < images.length; i++) {
if (images[i].src.indexOf('placeholder.png') !== -1) {
images[i].src = images[i].src.replace("placeholder.png", "01.png");
}
}
}
changeSourceAll();
function changeSource() {
var img = document.getElementsByTagName('img')[0];
img.setAttribute('src', img.getAttribute('src').replace("placeHolder.png", "image.png"));
}

Categories