Changing picture frame with toggle button - javascript

Ok so we have a simple user info editing page.I want to create a toggle button which swaps profile picture border-radius from 0 to 25 and backwards.But the 2nd part doesnt work.I created if to check if the boarder radius is 25 already so it will make it 0, but it does not work.Here is my code
<!DOCTYPE html>
<html>
<head>
</head>
<body onload="buildImage();">
<div class="contents" id="content"></div>
<button onclick="changeImage()">NextImage</button>
<button onclick="changeShape()">ChangeShape</button>
<button onclick="uploadImage()">Upload Image</button>
</body>
<script>
var images = [ 'profile1.png', 'profile2.png','profile3.png'];
var index = 0;
var array_length = 3;
function buildImage() {
var img = document.createElement('img')
img.src = images[index];
document.getElementById('content').appendChild(img);
}
function changeImage(){
var img = document.getElementById('content').getElementsByTagName('img')[0]
index++;
index = index % array_length;
img.src = images[index];
}
function changeShape(){
var shape = document.getElementById('content').getElementsByTagName('img')[0].style.borderRadius = "25px";
if(shape.style.borderRadius == 25){
var shape2 = document.getElementById('content').getElementsByTagName('img')[0].style.borderRadius = "0px";
}
}
function uploadImage() {
images.push("profile4.png");
array_length++;
}
</script>
</html>
Any ideas why it doesnt work?

You are uselessly assigning variables in your function by the looks of it.
There is no need to declare shape2. Just declare shape once and then use that to check. Also make sure to check shape.style.borderRadius against a string like "25px" as that will be returned.
Try something like this:
function changeShape(){
var shape = document.getElementById('content').getElementsByTagName('img')[0];
if(shape.style.borderRadius == "25px"){
shape.style.borderRadius = "0px";
}else{
shape.style.borderRadius = "25px";
}
}

Related

Javascript Next and Previous images

Code is supposed to show next image when clicking on next arrow and previous image when clicked on previous arrow. It does not work though. (error occurs while assigning img.src=imgs[this.i]; it says Cannot set property 'src' of null
at collection.next) .
Javascript code :
var arr = new collection(['cake.png', 'image2.png', 'image3.png', 'image1.png']);
function collection(imgs) {
this.imgs = imgs;
this.i = 0;
this.next = function(element) {
var img = document.getElementById('element')
this.i++;
if (this.i == imgs.length) {
this.i = 0;
}
img.src = imgs[this.i].src;
}
this.prev = function(element) {
var img = document.getElementById('element');
this.i--;
if (this.i < 0) {
this.i = imgs.length - 1;
}
img.src = imgs[this.i].src;
}
}
<!DOCTYPE html>
<html>
<head>
<title>photos</title>
<script src="photos.js"></script>
</head>
<body>
<input type='button' value='<' name='next' onclick="arr.next('mainImg')" />
<img id='mainImg' src="cake.png">
<input type='button' value='>' name='prev' onclick="arr.prev('mainImg')" />
</body>
</html>
Not using jquery. I do not have enough experience in js either. Thank you for your time
You had three mistakes:
You referenced the images as img.src = imgs[this.i].src; and you just had an array of strings, not an array of objects with a src property. img.src = imgs[this.i]; is the correct way to get the URL.
You used
var img = document.getElementById('element');
when you should have used
var img = document.getElementById(element);
element is an argument coming from your onclick event. It holds the id of your image that you should be using. "element" is just a string. You try to find an element with id equal to element which doesn't exist.
Edit: You should also use < and > to represent < and >. Otherwise your HTML might get screwed up. More on that here.
var arr = new collection(['http://images.math.cnrs.fr/IMG/png/section8-image.png', 'https://www.w3.org/MarkUp/Test/xhtml-print/20050519/tests/jpeg444.jpg', "http://saturnraw.jpl.nasa.gov/multimedia/images/raw/casJPGFullS72/N00183828.jpg"]);
function collection(imgs) {
this.imgs = imgs;
this.i = 0;
this.next = function(element) {
var img = document.getElementById(element);
this.i++;
if (this.i >= imgs.length) {
this.i = 0;
}
img.src = imgs[this.i];
};
this.prev = function(element) {
var img = document.getElementById(element);
this.i--;
if (this.i < 0) {
this.i = imgs.length - 1;
}
img.src = imgs[this.i];
};
this.next("mainImg"); // to initialize with some image
}
<!DOCTYPE html>
<html>
<head>
<title>photos</title>
<script src="photos.js"></script>
</head>
<body>
<input type='button' value='<' name='next' onclick="arr.next('mainImg')" />
<img id='mainImg' src="cake.png">
<input type='button' value='>' name='prev' onclick="arr.prev('mainImg')" />
</body>
</html>
This is how I'd personally do it:
var myCollection = new Collection([
"http://images.math.cnrs.fr/IMG/png/section8-image.png",
"https://www.w3.org/MarkUp/Test/xhtml-print/20050519/tests/jpeg444.jpg",
"http://saturnraw.jpl.nasa.gov/multimedia/images/raw/casJPGFullS72/N00183828.jpg"
], "mainImg");
document.getElementById("next_btn").onclick = function() {
myCollection.next();
};
document.getElementById("prev_btn").onclick = function() {
myCollection.prev();
}
function Collection(urls, imgID) {
var imgElem = document.getElementById(imgID);
var index = 0;
this.selectImage = function() {
imgElem.src = urls[index];
};
this.next = function() {
if (++index >= urls.length) {
index = 0;
}
this.selectImage();
};
this.prev = function(element) {
if (--index < 0) {
index = urls.length - 1;
}
this.selectImage();
};
// initialize
this.selectImage();
}
<!DOCTYPE html>
<html>
<head>
<title>photos</title>
<script src="photos.js"></script>
</head>
<body>
<input id="next_btn" type='button' value='<' />
<img id='mainImg'>
<input id="prev_btn" type='button' value='>' />
</body>
</html>
Why sending string into arr.next('mainImg') function ?
your img element always have the same id, only change src.
and document.getElementById(element) is also the same img element.
html: <img id='mainImg' src="cake.png">
js: document.getElementById('mainImg')
consider img element as a container, and id is it's identifiler.
var start_pos = 0;
var img_count = document.getElementsByClassName('icons').length - 1;
var changeImg = function(direction){
pos = start_pos = (direction == "next")? (start_pos == img_count)? 0 : start_pos+1 : (start_pos == 0)? img_count : start_pos-1;
console.log(pos)
}
document.getElementById('left').onclick = function(){ changeImg("previous"); }
document.getElementById('right').onclick = function(){ changeImg("next"); }

Image Changing Button using JavaScript

I had a look here and here for my answer but found that the code was far too long for such a simple process.
Below, my code shows a basic Image Changer by having the 'image' changed to the different .jpg's in an array, located in the same file.
<!DOCTYPE html>
<html>
<body>
<img id="image" src="blank_light.jpg" style="width:100px">
<p></p>
<button class = "change-image">Change Lights</button>
<script>
var imageSources = ["green_light.jpg", "yellow_light.jpg", "red_and_yellow_light.jpg", "red_light.jpg", "blank_light.jpg"]
var buttons = document.getElementsByClassName("change-image")
for (let i = 0; i < buttons.length; i++) {
buttons[i].onclick = function () {
document.getElementById("image").src = imageSources[i]
}
}
</script>
</body>
</html>
In theory, because I've embedded the script within the HTML it should work like a dream, but the image seems to get stuck on the yellow light. Is there a repeat button click phase I'm missing?
Thanks.
There is no need to use a loop. You can get reference to the button using document.getElementsByClassName("change-image")[0];. Then you can add an event lister to trigger on each button click.
Each time a user clicks you iterate through the array by one.
You could look at doing something like this:
var buttons = document.getElementsByClassName("change-image")[0];
var index = 0;
buttons.addEventListener('click',function() {
if(index === imageSources.length ) {
index = 0;
}
document.getElementById("image").src = imageSources[index];
index++;
});
Here is the complete code, which works. If you inspect the img element you will see that it updates.
<!DOCTYPE html>
<html>
<body>
<img id="image" src="blank_light.jpg" style="width:100px">
<p></p>
<button class="change-image">Change Lights</button>
<script>
var imageSources = ["green_light.jpg", "yellow_light.jpg", "red_and_yellow_light.jpg", "red_light.jpg", "blank_light.jpg"]
var buttons = document.getElementsByClassName("change-image")[0];
var index = 0;
buttons.addEventListener('click', function() {
if (index === imageSources.length) {
index = 0;
}
document.getElementById("image").src = imageSources[index];
index++;
});
</script>
</body>
</html>
Funny implementation -))
document.getElementById("changer").addEventListener("click", function(){
var i = document.getElementById("source");
var images = [
"http://lorempixel.com/400/200/sports",
"http://lorempixel.com/400/200/animals",
"http://lorempixel.com/400/200/nature"
];
var ord = parseInt(i.dataset.order);
nextImage = function(prev) {
return (prev+1 >= images.length ? (prev + 1)%images.length : prev+1);
}
document.getElementById("source").src = images[nextImage(ord)];
i.dataset.order = ord + 1;
})
<img id="source" data-order="0" src="http://lorempixel.com/400/200/sports">
<button id="changer">change</button>

I can't remove a child in javascript that is pretty much identical to another child that i can remove

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="box">
<button id="start" type="button" onclick="myStart()" > Start</button>
<script>
function myStart() {
document.getElementById("start").style.display="none";
var rosso = casuale(0,1);
if (rosso==0) {
var imgtest1= document.createElement("input");
imgtest1.src="http://www.w3schools.com/tags/logo_w3s.gif";
imgtest1.type="image";
imgtest1.style.height="50px";
imgtest1.style.width="50px";
imgtest1.style.position="absolute";
imgtest1.style.top="300px";
imgtest1.style.left="0px";
imgtest1.onclick= function() { document.getElementById("box").removeChild(imgtest1)
}
document.getElementById("box").appendChild(imgtest1);
}
else {
var imgtest1= document.createElement("input");
imgtest1.src="https://s3.amazonaws.com/impressivewebs/2014-02/w3schools-logo.jpg";
imgtest1.type="image";
imgtest1.style.height="50px";
imgtest1.style.width="50px";
imgtest1.style.position="absolute";
imgtest1.style.top="300px";
imgtest1.style.left="0px";
imgtest1.onclick= function() { document.getElementById("box").removeChild(imgtest1)}
document.getElementById("box").appendChild(imgtest1);
}
}
function casuale(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
</script>
</div>
</body>
I have a little problem with this code:
var rosso = casuale(0, 3)
if (rosso == 0) {
var imgtest1 = document.createElement("input");
imgtest1.src = "graphic/badtarget.png";
imgtest1.type = "image";
imgtest1.style.height = "50px";
imgtest1.style.width = "50px";
imgtest1.style.position = "absolute";
imgtest1.style.top = "300px";
imgtest1.style.left = "0px";
imgtest1.onclick = function() {
error++;
checkerror();
}
document.getElementById("box").appendChild(imgtest1);
} else {
var imgtest1 = document.createElement("input");
imgtest1.src = "graphic/goodtarget.png";
imgtest1.type = "image";
imgtest1.style.height = "50px";
imgtest1.style.width = "50px";
imgtest1.style.position = "absolute";
imgtest1.style.top = "300px";
imgtest1.style.left = "0px";
imgtest1.onclick = function() {
point++;
document.getElementById("box").removeChild(imgtest1);
if (point == maxp) {
livello2(7);
cleartarget();
}
}
document.getElementById("box").appendChild(imgtest1);
}
wheni try to remove the child "imgtest1" with the goodtarget.png image i have no problems, instead when i want to remove the child with the badtarget.png image the button stay here and there is no way to remove it. Why this happens? there is a way to solve this? if needed i can post other lines of code.
Thanks
Edit: Sorry for wasting your time, in the snippet the code works as intended (both the green and the blue images can disappear) but in my program can not.
the lines of code that i use for the remove child is a function that should be called at the end of a level:
var myNode = document.getElementById("box");
while (myNode.firstChild) {
myNode.removeChild(myNode.firstChild);
}
this function cant remove the objects created with the "imgtest1.src = "graphic/badtarget.png";"
Thanks for your time

JavaScript Image Swap with a Timer and Fade

I have a unique situation where I am trying to take an image and swap it out after a specific time. I have that part working however I also need the pictures to fade in and out of each other and I can not figure that part out. Please help if you can.
JavaScript:
<script type="text/javascript">
var picPaths = ['images/Front1.jpg','images/Front2.jpg','images/Front3.jpg'];
var curPic = -1;
var imgO = new Array();
for(i=0; i < picPaths.length; i++) {
imgO[i] = new Image();
imgO[i].src = picPaths[i];
}
function swapImage() {
curPic = (++curPic > picPaths.length-1)? 0 : curPic;
imgCont.src = imgO[curPic].src;
setTimeout(swapImage,5000);
}
window.onload=function() {
imgCont = document.getElementById('imgBanner');
swapImage();
}
</script>
HTML:
div img id="imgBanner" src="" alt="" / /div
I have the correct <> in places on the HTML however it would not let me post the HTML into the screen.

Different intervals between images

I am studying for GCSE computing and need to be able to change the interval between different images. My code at the moment looks something like this...
<!DOCTYPE html>
<html>
<body>
<h1> Traffic lights can change on their own </h1>
<img src="RED.jpg" id= "traffic" width="155" height="198">
<script>
var myImage = document.getElementById("traffic");
var imageArray = ["RED.jpg", "RED-ORANGE.jpg", "GREEN.jpg", "ORANGE.jpg"];
var imageIndex = 0;
function changeImage()
{
myImage.setAttribute("src",imageArray[imageIndex]);
imageIndex++;
if (imageIndex >= imageArray.length) {
imageIndex = 0;
}
}
setInterval(changeImage,1000);
</script>
</body>
</html>+
If you could include some of this code whilst changing the intervals that would be ideal.
Supposing you want to solve this using Javascript only:
Source documentation
// Save the var timeoutID = window.setTimeout(code, [delay]);
var imageTimers = [500, 1000, 2000, 4000];
var timeTochange = Math.random() * 3000; // or whatever you want to use...
var aTimer = setTimeout(changeImage, timeTochange);
// On the changeImage, alter the timeTochange var.
function changeImage() {
// ...stuffs...
clearTimeout(aTimer);
timeTochange = imageTimers[imageIndex];
aTimer = setTimeout(changeImage, timeTochange);
}

Categories