Javascript creating <img> - javascript

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" />';
}

Related

Swap IMG-SRC with another Image dynamically?

Forgive me, it's been a while since figuring out anything with jQuery, I need some guidance/help: I'd love to swap an image 00x-a for 00x-b, but not just for a single image, but for many. Once the BTN below an IMG is clicked, I'd love to swap the IMG above for 00x-b while resetting other IMGs to 00x-a.
<div>
<img id="swap_this" src="img-001-a.jpg">
<a class="button">Change-IMG</a>
</div>
<div>
<img id="swap_this" src="img-002-a.jpg">
<a class="button">Change-IMG</a>
</div>
<div>
<img id="swap_this" src="img-003-a.jpg">
<a class="button">Change-IMG</a>
</div>
<script type="text/javascript">
jQuery(document).ready(function($) {
$(".button").click(function(){
$("#swap_this").attr()({
"src":"img-001-b.jpg";
})
})
});
</script>
This should do it. Only the first picture is set to img-001-a.jpg
var arr = ['img-001-a.jpg', 'img-002-a.jpg', 'img-003-a.jpg']
$.each($('.swap_this'), function(index, value) {
if(index == 0) {
$(this).attr('src', arr[0])
console.log($(this).attr('src'));
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<img class="swap_this" src="img-001-b.jpg">
<a class="button">Change-IMG</a>
</div>
<div>
<img class="swap_this" src="img-002-b.jpg">
<a class="button">Change-IMG</a>
</div>
<div>
<img class="swap_this" src="img-003-b.jpg">
<a class="button">Change-IMG</a>
</div>
Tried to follow up on your answer, but ended up with something else. The below does what I need, but can it be written with "each" or using a for-loop to iterate through? Thx.
// clicking btn_100
$('.btn_100').click(function(e) {
// reset all IMG to version -a.gif..
$(".img_100").attr('src','img-100-a.gif');
$(".img_099").attr('src','img-099-a.gif');
$(".img_098").attr('src','img-098-a.gif');
// set IMG_100 ver -b.gif..
$(".img_100").attr('src','img-100-b.gif');
});
// clicking btn_099
$('.btn_099').click(function(e) {
// reset all IMG to version -a.gif..
$(".img_100").attr('src','img-100-a.gif');
$(".img_099").attr('src','img-099-a.gif');
$(".img_098").attr('src','img-098-a.gif');
// set IMG_100 ver -b.gif..
$(".img_099").attr('src','img-099-b.gif');
});
// and so on..
Maybe this could work…
for(a=1; a<=100; a++) {
// create fns for all btns
$(".btn_" + a).click(function(e) {
// reset all IMG to version -a.gif..
for(i=1; i<=100; i++) {
$(".img_" + i).attr("src","image-" + i + "-a.gif");
}
// set specific IMG to version -b.gif..
$(".img_" + a).attr("src","image-" + a + "-b.gif");
});
}

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

Image is loading as null

I am new to javascript but I am trying to have the default image set with the onload() and I don't think that it is reaching the image that I set up in the array and I cannot figure out why.
I am going to have it rotate images after I click on the button but I can't even get the default image to add.
var images = ['img/profile.jpg', 'img/mountain.jpg', 'img/sanfran.jpg'];
var num=1;
function loadPage()
{
document.getElementById("pictures").src = images[0].src;
}
function nextImage(pictures)
{
var img = document.getElementById("pictures");
document.getElementById("pictures").src = images[1].src;
console.log(num++); // I have this just to make sure that it is catching something
}
<div id="maincontent">
<div id="pictures">
<img src="img/mountain.jpg">
</div>
<div id="paragraph">
<p>
</p>
<button onclick="nextImage()">Switch Images</button>
</div>
</div>
You just need to have your id="pictures" on the image tag, not the div.
Like this:
<img id="pictures" src="img/mountain.jpg">
Also leave off the .src in loadPage() and nextImage()
document.getElementById("pictures").src = images[1];
Here images is an javascript array. So you cannot use .src as it is not an HTML img element
var images = ['img/profile.jpg', 'img/mountain.jpg', 'img/sanfran.jpg'];
var num=1;
//This function will run on body onload
function loadPage()
{
document.getElementById("pictures").src = images[0];
}
//This function will run on button click
function nextImage()
{
var img = document.getElementById("pictures");
document.getElementById("pictures").src = images[1];
console.log(num++); // I have this just to make sure that it is catching something
}
<body onload="loadPage()">
<div id="maincontent">
<img id="pictures" src="img/mountain.jpg">
<div id="paragraph">
<p>
</p>
<button onclick="nextImage()">Switch Images</button>
</div>
</div>
</body>
I have updated your code please check.
var images = ['img/profile.jpg', 'img/mountain.jpg', 'img/sanfran.jpg'];
var num=0;
loadPage();
function loadPage()
{
console.log(num);
document.getElementById("picture").src = images[num];
num++;
}
function nextImage(pictures)
{
if(typeof images[num] === 'undefined') {
// does not exist
num = 0;
}
console.log(num);
document.getElementById("picture").src = images[num];
num++;
}
<div id="maincontent">
<div id="pictures">
<img src="img/mountain.jpg" id="picture">
</div>
<div id="paragraph">
<p>
</p>
<button onclick="nextImage()">Switch Images</button>
</div>
</div>
Try this one:
<script>
var images = ['img/profile.jpg', 'img/mountain.jpg', 'img/sanfran.jpg'];
var num=0;
function loadPage()
{
document.getElementById("pictures").src = images[0].src;
}
function nextImage(pictures)
{
if(num<images.length-1) {
num = num+1;
} else {
num = 0;
}
var img = document.getElementById("pictures");
document.getElementById("pictures").src = images[num];
console.log(num); // I have this just to make sure that it is catching something
}
</script>
<div onload="loadPage()">
<div id="imageholder">
<img id="pictures" src="img/mountain.jpg">
</div>
<div id="paragraph">
<p>
</p>
<button onclick="nextImage()">Switch Images</button>
</div>
</div>

Javascript code for remove image

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);
}
}

JavaScript works in Firefox, not in IE8?

This code works when loaded in Firefox, but does not work in IE8. In IE8, clicking the link has no effect.
I would appreciate any pointers on how to make it work in IE.
<html>
<head>
<title>RG</title>
</head>
<script type="text/javascript">
var rightTarget;
var leftTarget;
var index = 516;
var img;
function rightLinkClicked(e) {
rightTarget = e.target;
rightTarget.style.color = "green";
if (index < 547) {
index = index +1;
img=document.getElementById("img");
img.src="pics/IMG_0" + index + ".JPG";
} else {
alert ("This is the last painting");
}
}
function leftLinkClicked(e) {
leftTarget = e.target;
leftTarget.style.color = "red";
rightTarget.style.color = "black";
if (index >516) {
index = index -1;
img=document.getElementById('img');
img.src="pics/IMG_0" + index + ".JPG";
} else {
alert ("This is the first painting");
}
}
function addListeners() {
var rightLink = document.getElementById("rightlinkid");
rightLink.addEventListener('click', rightLinkClicked, false);
var leftLink = document.getElementById("leftlinkid");
leftLink.addEventListener('click', leftLinkClicked, false);
}
window.addEventListener('load', addListeners, false);
</script>
</head>
<body>
<h2>RG</h2>
<div>
<a id="leftlinkid">Previous
<img src="icons/left.gif" ;="" alt="left arrow" title="">
</a>
</div>
<div id="myimg">
<img id="img" src="pics/IMG_0516.JPG" ;="" alt="start arrow" title=""width="640"height="480">
</div>
<div>
<a id="rightlinkid">Next
<img src="icons/right.gif" ;="" alt="right arrow" title="">
</a>
</div>
<p>© 2011 RG</p>
</body>
</html>
IE uses attachEvent instead of addEventListener.
You may want to use a cross-browser Javascript library such as jQuery to handle these issues (and many more) for you.

Categories