Javascript code for remove image - javascript

I want to make this Javascript code to when I click "remove image" link , it remove the image. Please help me.
<script>
function previewFile(){
var preview = document.querySelector('img');
var file = document.querySelector('input[type=file]').files[0];
var reader = new FileReader();
reader.onloadend = function () {
preview.src = reader.result;
}
if (file) {
reader.readAsDataURL(file);
} else {
preview.src = "";
}
}
previewFile();
</script>
<input type="file" onchange="previewFile()"><br>
<img src="" height="200" alt="Image preview...">
remove image
</body>
</html>

<img id='image' src="" height="200" alt="Image preview...">
<a id='remove' href="#">remove image </a>
<script>
$(function rmv() {
$('#remove').click(function() {
$('#image').remove();
}
});
</script>

If you cannot add id attribute to that img, you can remove it like this with raw javascript - it assumes the image is preceding the anchor tag directly, allowing for only one text node between them:
function removeImage(el){
if(!el.previousSibling.tagName){//if it is textnode like newline etc. we go one back
var el = el.previousSibling;
}
if(el.previousSibling.tagName && el.previousSibling.tagName=='IMG'){
el.previousSibling.remove();
}
}
<img src="" height="200" alt="Image preview...">
remove image

Keep img element in div and assign id to both this element
<input type="file" onchange="previewFile()"><br>
<div id="imgDiv"> <img id="image1" src="" height="200" alt="Image preview..."></div>
remove image
</body>
</html>
<script>
function previewFile() {
var d = document.getElementById('imgDiv');
var olddiv = document.getElementById("image1");
d.removeChild(olddiv);
}
</script>

<img src="" id="image" height="200" alt="Image preview...">
remove image
JS:
function foo(){
var image = document.getElementById("image");
if (image != null)
{
image.parentNode.removeChild(image);
}
}

Related

Random image from html on button click

I am trying to make a script that will take the images from one div element and put it to div rndmImage randomly on button click, I should see images when document is loaded, but the new div where images should go after click must be empty until click heapends. And I need only JavaScript, no jQuery, alse i can not change the html, and it has to work for any number of images. So if you have some ideas that would be great. Here's my code.
window.addEventListener('load', start, false);
function start() {
var butt = document.getElementsByTagName('button')[0];
var rnImg = document.getElementsByClassName('ekran');
var pictures = document.getElementsByTagName('img');
var choose = Math.floor(Math.random()*pictures.length);
butt.addEventListener('click', menjaj, false);
function menjaj(e) {
var new = e.button;
var img = [];
for(var i = 0; i< pictures.length; i++) {
var dodaj = img[i];
img.push(dodaj);
}
//ekran.src = 'slike/' + slike[izbor] + '.jpg';
}
}
<body>
<div class="wrapper">
<div>
<img src="slike/leto1.jpg" alt="leto1">
<img src="slike/leto2.jpg" alt="leto2">
<img src="slike/leto3.jpg" alt="leto3">
<img src="slike/leto4.jpg" alt="leto4">
<img src="slike/leto5.jpg" alt="leto5">
<img src="slike/leto6.jpg" alt="leto6">
<img src="slike/leto7.jpg" alt="leto7">
<img src="slike/leto8.jpg" alt="leto8">
<img src="slike/leto9.jpg" alt="leto9">
</div>
<div>
<button type="button">choose</button>
</div>
<div class="rndmImage"></div>
</div>
</body>
This is a working snippet of your code:
window.addEventListener('load', start, false);
function start () {
var butt = document.getElementsByTagName('button')[0];
var rnImg = document.getElementsByClassName('rndmImage')[0]; //Change selector to existing class and select the first (the only) one
var pictures = document.getElementsByTagName('img');
butt.addEventListener('click', menjaj, false);
function menjaj (e) {
// var new = e.button;// 'new' is reserved word in JS, you can't use it as variable name
// var btn = e.button;// but this line is useless
var choose = Math.floor(Math.random() * pictures.length); //better move this line inside this function to get rundom image every button clicks
var img = document.createElement('img'); //creates new img tag
img.src = pictures[choose].src;
rnImg.innerHTML = ''; //to delete previous image
rnImg.appendChild(img);
// var img = []; //useless lines of code
// for(var i = 0; i< pictures.length; i++) {
// var dodaj = img[i];
// img.push(dodaj);
// }
//ekran.src = 'slike/' + slike[izbor] + '.jpg';
}
}
welcome to StackOverflow!
I would first hide the .wrapper > div img as that will prevent the images to show, then, append a data-pos to help select the position and simply randomize them and pick the src to show on the placeholder
and remember that you have a <div> as placeholder, so you can't assign src, only if you change it to <img>
so, something like this 😊
function chooseImg() {
// get total images available
var totalImages = document.querySelectorAll('.wrapper > div img').length
log('totalImages', totalImages)
// get a random position
var rndPosition = Math.floor(Math.random() * totalImages)
log('rndPosition', rndPosition)
// get hold of the image for such position
var rndImage = document.querySelector('.wrapper > div img[data-pos="' + rndPosition + '"]')
log('rndImage', rndImage)
// assign the source to the DIV
document.querySelector('.rndmImage').style = 'background-image: url("' + rndImage.src + '")'
}
function log(txt, obj) {
console.log(txt, obj)
}
.wrapper > div img {
display: none;
}
.rndmImage {
background-size: contain;
background-repeat: no-repeat;
width: 100px;
height: 100px;
}
<div class="wrapper">
<div>
<img data-pos="0" src="https://randomwordgenerator.com/img/picture-generator/54e5d2434953a514f1dc8460962e33791c3ad6e04e507440742f7cd09645cc_640.jpg" alt="leto1">
<img data-pos="1" src="https://randomwordgenerator.com/img/picture-generator/54e2d1404a57a814f1dc8460962e33791c3ad6e04e5074417c2d78d19f44c4_640.jpg" alt="leto2">
<img data-pos="2" src="https://randomwordgenerator.com/img/picture-generator/57e2d5444851a414f1dc8460962e33791c3ad6e04e50744172287ad2914fc4_640.jpg" alt="leto3">
<img data-pos="3" src="https://randomwordgenerator.com/img/picture-generator/51e8d0444f56b10ff3d8992cc12c30771037dbf85254794e722c73d19245_640.jpg" alt="leto4">
<img data-pos="4" src="https://randomwordgenerator.com/img/picture-generator/53e4d2464a56a914f1dc8460962e33791c3ad6e04e507440722d7cd39345c1_640.jpg" alt="leto5">
<img data-pos="5" src="https://randomwordgenerator.com/img/picture-generator/57e9dc434b5ba414f1dc8460962e33791c3ad6e04e50744172297bd5934cc4_640.jpg" alt="leto6">
<img data-pos="6" src="https://randomwordgenerator.com/img/picture-generator/55e1dc4b4254ad14f1dc8460962e33791c3ad6e04e507440722d72d09249c7_640.jpg" alt="leto7">
<img data-pos="7" src="https://randomwordgenerator.com/img/picture-generator/57e9d4474e54a814f1dc8460962e33791c3ad6e04e50744172297cdd974cc0_640.jpg" alt="leto8">
<img data-pos="8" src="https://randomwordgenerator.com/img/picture-generator/53e6dc404951b10ff3d8992cc12c30771037dbf852547848702e7ed19348_640.jpg" alt="leto9">
</div>
<div>
<button type="button" onclick="chooseImg()">choose</button>
</div>
<div class="rndmImage"></div>
</div>
<div class="wrapper">
<img src="../Assets1/Image/1.svg" alt="" />
<img src="../Assets1/Image/2.svg" alt="" />
<img src="../Assets1/Image/3.svg" alt="" />
</div>
<button>Click</button>
<div class="randomImageContainer"></div>
const button = document.querySelector('button');
button.addEventListener('click', randomImage);
function randomImage() {
const image = document.querySelectorAll('.wrapper > img');
const randomImageContainer = document.querySelector('.randomImageContainer');
let randomNumber = Math.floor(Math.random() * image.length);
const img = document.createElement('img');
img.src = image[randomNumber].src;
randomImageContainer.appendChild(img);
}
You can do this with plain javascript like this:
document.querySelector("button").addEventListener("click", () => {
var imgElements = document.querySelectorAll(".wrapper img");
document.querySelector(".rndmImage").innerHTML = imgElements[Math.floor(Math.random() * imgElements.length)].outerHTML;
});
<div class="wrapper">
<div>
<img src="slike/leto1.jpg" alt="leto1">
<img src="slike/leto2.jpg" alt="leto2">
<img src="slike/leto3.jpg" alt="leto3">
<img src="slike/leto4.jpg" alt="leto4">
<img src="slike/leto5.jpg" alt="leto5">
<img src="slike/leto6.jpg" alt="leto6">
<img src="slike/leto7.jpg" alt="leto7">
<img src="slike/leto8.jpg" alt="leto8">
<img src="slike/leto9.jpg" alt="leto9">
</div>
<div>
<button type="button">choose</button>
</div>
<div class="rndmImage"></div>
</div>
If you're able to use randojs, you can even simplify the randomness and make it all cryptographically secure like this:
document.querySelector("button").addEventListener("click", () => document.querySelector(".rndmImage").innerHTML = rando(document.querySelectorAll(".wrapper img")).value.outerHTML);
<script src="https://randojs.com/2.0.0.js"></script>
<div class="wrapper">
<div>
<img src="slike/leto1.jpg" alt="leto1">
<img src="slike/leto2.jpg" alt="leto2">
<img src="slike/leto3.jpg" alt="leto3">
<img src="slike/leto4.jpg" alt="leto4">
<img src="slike/leto5.jpg" alt="leto5">
<img src="slike/leto6.jpg" alt="leto6">
<img src="slike/leto7.jpg" alt="leto7">
<img src="slike/leto8.jpg" alt="leto8">
<img src="slike/leto9.jpg" alt="leto9">
</div>
<div>
<button type="button">choose</button>
</div>
<div class="rndmImage"></div>
</div>
Try this:
this is my image in HTML file
<snap id="image" class="btn btn-warning" onclick="changeImage()">Image</snap>
<image id="imagechange" src="https://picsum.photos/200/300" ></image>
my javascript file
imgcount = 0;
function changeImage() {
document.getElementById("imagechange").src =
"https://picsum.photos/200/" + (300 + imgcount);
imgcount++;
}
everytime you click button you get a new image

onclick get index of image in for loop javascript

onclick get image index in for loop in javascript not jquery, the main problem here is that i can't access any global variable in function
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/styles.css">
<title></title>
</head>
<body>
<img src="images/2.jpg" width="350" height="250">
<img src="images/3.jpg" width="350" height="250">
<img src="images/4.jpg" width="350" height="250">
<img src="images/5.jpg" width="350" height="250">
<img src="images/6.jpg" width="350" height="250">
<img src="images/7.jpg" width="350" height="250">
<script type="text/javascript" src="scripts/script.js"></script>
</body>
</html>
/*external javascript file code */
var img = document.images;
var i;
for(i=0;i<img.length;i++){
img[i].src = "images/1.jpg";
//after changing image src i just want to show index of clicked image
img[i].onclick = function(){
alert("i m img "+ i);
console.log(i);
}
console.log(i);
}
You can store the index in your own html attribute like index-data using setAttribute and getAttribute:
var img = document.images;
var i;
for (i = 0; i < img.length; i++) {
img[i].src = "images/1.jpg";
img[i].setAttribute("index-data", i);
//after changing image src i just want to show index of clicked image
img[i].onclick = function() {
var index = this.getAttribute("index-data");
console.log(index);
}
}
<img src="images/2.jpg" width="350" height="250">
<img src="images/3.jpg" width="350" height="250">
<img src="images/4.jpg" width="350" height="250">
<img src="images/5.jpg" width="350" height="250">
<img src="images/6.jpg" width="350" height="250">
<img src="images/7.jpg" width="350" height="250">
You can use the attribute dataset to store the current index.
var img = document.images;
var i;
var images = ['https://www.hrexaminer.com/wp-content/uploads/2016/10/2016-10-11-hrexaminer-stackoverflow-6-xxl-sq-250px.png', 'https://i.stack.imgur.com/G2FO1.jpg?s=48&g=1']
for (i = 0; i < img.length; i++) {
img[i].src = images[i];
img[i].dataset.index = i;
img[i].onclick = function() {
var index = this.dataset.index;
console.log(index);
}
}
<img src="" width="100" height="100">
<img src="" width="100" height="100">
This is a classical closure problem inside a loop.
The simple solution to this problem is to wrap the code block which has
indefinite execution, inside a IIFE block.
read about it here : Javascript closures
for(i=0;i<img.length;i++){
img[i].src = "images/1.jpg";
(function(index){
img[index].onclick = function(){
alert("i m img "+ index);
console.log(index);
}
})(i)
}

Javascript creating <img>

I have this code that is creating to div after clicking on button. But its not working... here is the html with script in it
<img id="boxm" style="position: fixed;left: 90%;padding-top:2%"
src="images/box1.png" id="image1" onclick="diffImage(this);myFunction();" />
<script>
function myFunction()
{
document.getElementById("surprise").createElement="<img
style="width:304px;height:228px"
src='images/mese.png' />";
}
</script>
<div id="surprise">
</div>
<img src='images/box1.png' onclick="showSurpriseImage()" />
<div id="surprise">
Surprise Image will be displayed here
</div>
<script>
function showSurpriseImage() {
var x = document.createElement("IMG");
x.setAttribute("src", "images/mese.png");
x.setAttribute("width", "304");
x.setAttribute("height", "228");
x.setAttribute("alt", "surprise image");
document.getElementById("surprise").appendChild(x);
}
</script>
Best Practice to set attributes checkout here
Hope this helps
<img id="boxm"
src="http://wfarm1.dataknet.com/static/resources/icons/set28/7f8535d7.png" id="image1" onclick="myFunction();" />
<script>
function myFunction() {
var s = document.getElementById("surprise")
var x = document.createElement("IMG");
x.setAttribute("src", "http://wfarm1.dataknet.com/static/resources/icons/set28/7f8535d7.png");
s.appendChild(x);
}
</script>
<div id="surprise">
</div>
Try this :
function myFunction()
{
document.getElementById("surprise").innerHTML='<img style="width:304px;height:228px" src="images/mese.png" />';
}

Javascript: Target image Id to display message

I've attached an onclick event on two images. I would like to display a different message for each image. How do I create an if/else statement to display one message "You Liked this Cat!" if one image is clicked and the other "You Didn't Like this Cat!"
<img src="black_cat.jpg" alt="Profile Pic" height="300" width="300" id="profile_pic"></img>
<img src="white_cat.jpg" alt="Profile Pic" height="300" width="300" id="next_profile"></img>
<img src="" alt="Swipe Left" height="150" width="150" id="swipe_left" onclick="hide_profile(); show_profile();"></img>
<img src="" alt="Swipe Right" height="150" width="150" id="swipe_right" onclick="hide_profile(); show_profile();"></img>
<p id="display_message"></p>
function hide_profile() {
document.getElementById("profile_pic").style.visibility = "hidden";
}
function show_profile() {
document.getElementById("next_profile").style.display = "block";
document.getElementById("next_profile").style.visibility = "visible";
document.getElementById("profile_pic").style.display = "none";
document.getElementById("display_message").innerHTML = "You Liked this Cat!";
}
In the HTML element you can pass its ID
<img onclick="functionName(this.id)">
And in Javascript:
function functionName(clicked_id){
if(clicked_id == "cat"){
...
}
}
You may need to add some attribute (e.g. id or rel) to your image tags and assign some unique value to them so you can identify it onclick event handler and show message accordingly.
Or rather pass some param with onclick function.
I am providing code pressuming used with jQuery.
<IMG SRC='IMG1.jpg' id='1' onclick='updatepic(1)'>
Javascript function
function updatepic(id) {
if(id==1) {
//change the innerhtml for pic 1
}
else {
//change the innerhtml for pic 2
}
}
Pass the text to the show_profile function.
Try this code:
function hide_profile() {
document.getElementById("profile_pic").style.visibility = "hidden";
}
function show_profile(message) {
document.getElementById("next_profile").style.display = "block";
document.getElementById("next_profile").style.visibility = "visible";
document.getElementById("profile_pic").style.display = "none";
document.getElementById("display_message").innerHTML = message;
}
<img src="black_cat.jpg" alt="Profile Pic" height="300" width="300" id="profile_pic"></img>
<img src="white_cat.jpg" alt="Profile Pic" height="300" width="300" id="next_profile"></img>
<img src="" alt="Swipe Left" height="150" width="150" id="swipe_left" onclick="hide_profile(); show_profile('You Liked this Cat!');"></img>
<img src="" alt="Swipe Right" height="150" width="150" id="swipe_right" onclick="hide_profile(); show_profile('You Didn\'t Like this Cat!');"></img>
<p id="display_message"></p>

Clicking on thumbnail changes an unintended main image

When I click on a thumbnail meant to change (img), it changes the main image of (img1) as well.
I would want only AGM thumbnails to change (img), and BLACSBF to change (img1)
Would appreciate any assistance. (:
My Javascript
function changeImage(img) {
document.getElementById("img").src = img.src.replace("_t", "_b");
document.getElementById("img1").src = img.src.replace("_t", "_b");
My HTML
<img src="images/AGM/events_t.jpg"
onclick='changeImage(this);'
onmouseout="this.style.opacity=1;this.filters.alpha.opacity=100"
onmouseover="this.style.opacity=0.5;this.filters.alpha.opacity=0.5">
<img src="images/AGM/events1_t.jpg"
onclick='changeImage(this);'
onmouseout="this.style.opacity=1;this.filters.alpha.opacity=100"
onmouseover="this.style.opacity=0.5;this.filters.alpha.opacity=0.5">
<img id="img" src="images/AGM/events_b.jpg" width="650">
<img src="images/BLACSBF/events_t.jpg"
onclick='changeImage(this);'
onmouseout="this.style.opacity=1;this.filters.alpha.opacity=100"
onmouseover="this.style.opacity=0.5;this.filters.alpha.opacity=0.5">
<img src="images/BLACSBF/events1_t.jpg"
onclick='changeImage(this);'
onmouseout="this.style.opacity=1;this.filters.alpha.opacity=100"
onmouseover="this.style.opacity=0.5;this.filters.alpha.opacity=0.5">
<img id="img1" src="images/BLACSBF/events_b.jpg" width="650">
Thank you very much!
You need to pass the targeted image element as a parameter to the changeImage function
function changeImage(img, target) {
document.getElementById(target).src = img.src.replace("_t", "_b");
}
then
<img src="images/AGM/events_t.jpg"
onclick="changeImage(this, 'img');"
onmouseout="this.style.opacity=1;this.filters.alpha.opacity=100"
onmouseover="this.style.opacity=0.5;this.filters.alpha.opacity=0.5">
<img src="images/AGM/events1_t.jpg"
onclick="changeImage(this, 'img');"
onmouseout="this.style.opacity=1;this.filters.alpha.opacity=100"
onmouseover="this.style.opacity=0.5;this.filters.alpha.opacity=0.5">
<img id="img" src="images/AGM/events_b.jpg" width="650">
<img src="images/BLACSBF/events_t.jpg"
onclick="changeImage(this, 'img1');"
onmouseout="this.style.opacity=1;this.filters.alpha.opacity=100"
onmouseover="this.style.opacity=0.5;this.filters.alpha.opacity=0.5">
<img src="images/BLACSBF/events1_t.jpg"
onclick="changeImage(this, 'img1');"
onmouseout="this.style.opacity=1;this.filters.alpha.opacity=100"
onmouseover="this.style.opacity=0.5;this.filters.alpha.opacity=0.5">
<img id="img1" src="images/BLACSBF/events_b.jpg" width="650">
You might be able to simplify your markup a little more if you attached event handlers directly in JavaScript. This isn't a cross browser method, but it certainly does work. Firstly you could slim down your markup and turn the bigger img elements into classes, instead of having a bunch of unique IDs to worry about:
<img src="images/AGM/events_t.jpg">
<img src="images/AGM/events1_t.jpg">
<img class="img" src="images/AGM/events_b.jpg" width="650">
<img src="images/BLACSBF/events_t.jpg">
<img src="images/BLACSBF/events1_t.jpg">
<img class="img" src="images/BLACSBF/events_b.jpg" width="650">
Then, in your JavaScript, you could cycle through all the img tags that don't have a class attribute, and add your event handlers with addEventListener() ( this is the part that will not work on IE8, but can be easily fixed with a cross browser implementation).
var imgs = document.getElementsByTagName('img');
for (var i = 0; i < imgs.length; i++) {
if (!imgs[i].getAttribute('class')) {
//mouseout handler
imgs[i].addEventListener("mouseout", function () {
this.style.opacity = 1;
this.filters.alpha.opacity = 100;
});
//mouseover handler
imgs[i].addEventListener("mouseover", function () {
this.style.opacity = 0.5;
this.filters.alpha.opacity = 0.5;
});
//click handler
imgs[i].addEventListener("click", function () {
var src = this.src.replace("_t", "_b");
var fullImg = siblingByClass(this);
fullImg.src = src;
//traverse siblings till 'img' class is found
function siblingByClass(node) {
var sibling = node.nextSibling;
if (sibling.nodeType === 3 || sibling.getAttribute('class') !== 'img') {
return siblingByClass(sibling);
} else {
return sibling;
}
}
});
}
}
jsFiddle

Categories