HTML How to change image onClick - javascript

I'm trying to have an image that changes when clicked: when image 1 is clicked, change to image 2, when image 2 is clicked change to image 3 and when image 3 is clicked it changes to image 1.
<p>
<img alt="" src="assets/img1.png"
style="height: 85px; width: 198px" id="imgClickAndChange" onclick="changeImage()" />
<script language="javascript">
function changeImage() {
if (document.getElementById("imgClickAndChange").src == "assets/img1.png")
{
document.getElementById("imgClickAndChange").src = "assets/img2.png";
}
else if (document.getElementById("imgClickAndChange").src == "assets/img2.png")
{
document.getElementById("imgClickAndChange").src = "assets/img3.png";
}
else if(document.getElementById("imgClickAndChange").src == "assets/img3.png"){
document.getElementById("imgClickAndChange").src = "assets/img1.png"
}

Clean and optimal solution in my opinion. As the users before said. It is good to use array to held the images paths.
var images = ["https://images.pexels.com/photos/67636/rose-blue-flower-rose-blooms-67636.jpeg?auto=compress&cs=tinysrgb&h=350", "https://i2.wp.com/beebom.com/wp-content/uploads/2016/01/Reverse-Image-Search-Engines-Apps-And-Its-Uses-2016.jpg?resize=640%2C426", "https://images.pexels.com/photos/248797/pexels-photo-248797.jpeg?auto=compress&cs=tinysrgb&h=350"]
var imgState = 0;
var imgTag = document.getElementById("imgClickAndChange");
imgTag.addEventListener("click", function (event) {
imgState = (++imgState % images.length);
event.target.src = images[imgState];
});
Solution

There were a lot of syntax errors in your code. I cleaned them up in a codepen here where you can see that your basic logic was correct. Though, as other users pointed out, there are more elegant ways to solve this problem.
https://codepen.io/anon/pen/MPYgxM
HTML:
<p>
<img alt="" src="https://r1.ilikewallpaper.net/ipad-wallpapers/download/26516/Natural-Grove-Green-Trees-Path-ipad-wallpaper-ilikewallpaper_com.jpg"
style="height: 85px; width: 198px" id="imgClickAndChange" onclick="changeImage()" />
</p>
JS:
function changeImage() {
if (document.getElementById("imgClickAndChange").src == "https://r1.ilikewallpaper.net/ipad-wallpapers/download/26516/Natural-Grove-Green-Trees-Path-ipad-wallpaper-ilikewallpaper_com.jpg")
{
document.getElementById("imgClickAndChange").src = "https://st2.depositphotos.com/1000438/6182/i/950/depositphotos_61826015-stockafbeelding-cascades-in-nationaal-park-plitvice.jpg";
}
else if (document.getElementById("imgClickAndChange").src == "https://st2.depositphotos.com/1000438/6182/i/950/depositphotos_61826015-stockafbeelding-cascades-in-nationaal-park-plitvice.jpg")
{
document.getElementById("imgClickAndChange").src = "https://orig00.deviantart.net/6787/f/2016/104/5/6/aria_maleki___natural_view_of_waterfall_by_aria_maleki-d9yytu8.jpg";
}
else if(document.getElementById("imgClickAndChange").src == "https://orig00.deviantart.net/6787/f/2016/104/5/6/aria_maleki___natural_view_of_waterfall_by_aria_maleki-d9yytu8.jpg"){
document.getElementById("imgClickAndChange").src = "https://r1.ilikewallpaper.net/ipad-wallpapers/download/26516/Natural-Grove-Green-Trees-Path-ipad-wallpaper-ilikewallpaper_com.jpg"
}
}

you can increment value on each click and update img. on base of incremented value
<img alt="" src="assets/img1.png" style="height: 85px; width: 198px" id="imgClickAndChange" onclick="changeImage()" />
<script language="javascript">
var counter = 1;
function changeImage() {
counter > 3 ? counter = 1 : counter++;
document.getElementById("imgClickAndChange").src = "assets/img"+counter+".png";
}
</script>

Hi this is different approach.
new ClickListener() is the class used to handle your logic & dom logic
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Image click</title>
</head>
<body>
<div id="player">
</div>
<script>
class ClickListener {
constructor() {
this.rootElement = document.querySelector( "#player" );
this.element = document.createElement("img");
this.rootElement.appendChild(this.element);
this.images = ['./1.jpg', './2.jpg', './3.jpg']
this.idx = 0
this.init()
}
init() {
this.element.src = this.images[this.idx]
this.element.style.width = `400px`;
this.element.style.height = `400px`;
this.element.onclick = this.nextImage.bind(this)
}
nextImage() {
this.idx++;
if(this.idx >= this.images.length) {
this.idx = 0;
}
this.element.src = this.images[this.idx]
}
}
new ClickListener()
</script>
</body>
</html>

Related

Call different events when a variable change in JS

I build a small application to switch between random images in an iframe, I would like that after 10 or 20 images the user will get an image or source I want him to get and not a random one, and then return to the loop.
I have a problem with the count and if function, will appreciate any help. Thanks
<body>
<iframe id="img_main" src="https://www.example.com/img_4.jpg" width="600" height="800" frameborder="1" scrolling="no"></iframe>
<br>
<button id="H" type="button" onclick=(newImg(),clickCounter(),changeImg())>images</button>
<div id="result"></div>
<script>
function newImg(){
var myArray = [
"img_1.jpg",
"img_2.jpg",
"img_3.jpg",
"img_4.jpg"
];
var imgNew = "https://example.com/"
var randomItem = myArray[Math.floor(Math.random()*myArray.length)];
document.getElementById("img_main").src = "https://example.com/" + randomItem ;
}
function clickCounter() {
if (typeof(Storage) !== "undefined") {
if (localStorage.clickcount) {
localStorage.clickcount = Number(localStorage.clickcount)+1;
} else {
localStorage.clickcount = 1;
}
function changeImg(){
if (localStorage.clickcount = 10,20) {
document.getElementById("ins_main").src = "https://example.com/pre_defined_img.jpg";
}
}
</script>
</body>
the way I see that...
by simply use of the modulo (finds the remainder after division)
you don't need to use an iframe, img element is enough.
use an IIFE. as closure method
file : "myScript.js"
const imgBox = (function()
{
const refURL = 'https://i.picsum.photos/id/'
, imgName = [ '251/300/500.jpg', '252/300/500.jpg', '253/300/500.jpg', '254/300/500.jpg'
, '255/300/500.jpg', '256/300/500.jpg', '257/300/500.jpg', '258/300/500.jpg'
, '259/300/500.jpg', '260/300/500.jpg', '261/300/500.jpg', '146/300/500.jpg'
, '263/300/500.jpg', '264/300/500.jpg', '265/300/500.jpg', '266/300/500.jpg'
, '267/300/500.jpg', '268/300/500.jpg', '269/300/500.jpg', '270/300/500.jpg'
, '271/300/500.jpg', '272/300/500.jpg', '273/300/500.jpg', '274/300/500.jpg'
]
, imgZero = '250/300/500.jpg'
, imgSiz = imgName.length
, imgMain = document.getElementById('img-main')
;
var imgNum = 0, randomI = 0;
const obj =
{ setNext()
{
if (!(++imgNum % 10)) // each 10 times
{
imgMain.src = refURL + imgZero
}
else
{
randomI = Math.floor(Math.random() * imgSiz)
imgMain.src = refURL + imgName[randomI]
}
return imgNum
}
}
return obj
})()
const btImg = document.getElementById('bt-img')
, imgCount = document.getElementById('img-count')
, banner = document.getElementById('my-banner')
;
btImg.onclick =evt=>
{
let counter = imgBox.setNext()
imgCount.textContent = counter
if (!(counter %50)) // each 50 times..
{
changeBanner()
}
}
// changing banner function...
function changeBanner()
{
//.....
// do what ever you want to change your banner
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>test</title>
<style>
img#img-main {
width: 300px;
height: 500px;
border: 1px solid grey;
padding: 2px;
}
</style>
</head>
<body>
<img id="img-main" src="https://i.picsum.photos/id/250/300/500.jpg" alt="" >
<p id="img-count">0</p>
<button id="bt-img">Image change</button>
<div id="my-banner">the banner</div>
<script src="myScript.js"></script>
</body>
</html>

how to onclick for pairs of images randomly in javascript?

/* egg & broke egg pair1 lite & broke lite pair2 pot & frys pair3 */
I would like to know how to make the images pair up or team up. So when you click the egg image it disappears and the broken egg appears. Then this image should also disappear then and one of the other two teams appear randomly lite click lite broke lite appears and disappears randomly and click pot it turns into frys then frys disappears and turns into a random team.
</head>
<body onLoad="setRandomImage()">
<img id="egg.png" src= "http//"onClick="setRandomImage();"/>
<img id="brokeEgg.png" src= "https://" style="display:none"/>
<img id="lite.png" src= "http://" style="display:none"/>
<img id="brokeLite.png" src= "http://" style="display:none"/>
<img id="pot.jpg" src= "https://style="display:none"/>
<img id="frys.jpg" src= "http://style="display:none"/>
<script type="text/javascript">
var myShapes= ["egg.png","brokeEgg.png","lite.png","brokeLite.png","pot.jpg","frys.jpg" ];
function setRandomImage() {
var imgElem = document.getElementById("egg.png")
imgElem.setAttribute('src',myShapes[Math.floor(Math.random()*6)]);
};
</script>
Here's a very simplified one by making use of HTML data-* attributes, but take in consideration:
The value data-image-seq attribute must be img followed by a number.
These numbers must be sequenced
Updated
jsFiddle
var imgs = document.querySelectorAll('.imgs-wrapper img'),
currentIMG = 1;
// attach click events on odd images only, egg, lite, pot, hi1, hello1
for (var i = 0; i < imgs.length; i += 2) {
addEvent(imgs[i], 'click');
}
function addEvent(element, event) {
element.addEventListener(event, function() {
var imgSeq = element.getAttribute('data-image-seq'),
nextImgSeq, nextImg, shownIMG;
imgSeq = parseInt(imgSeq.replace('img', ''), 10);
nextImgSeq = (imgSeq < imgs.length) ? (imgSeq + 1) : 1;
nextImg = 'img[data-image-seq=img' + nextImgSeq + ']';
element.style.display = 'none';
shownIMG = document.querySelector(nextImg);
shownIMG.style.display = 'block';
setTimeout(function() {
shownIMG.style.display = 'none';
showRandomImg();
}, 1000);
});
}
function showRandomImg() {
var randomIMG = returnRandomOddNum();
randomIMG = (randomIMG !== currentIMG) ? randomIMG : returnRandomOddNum();
currentIMG = randomIMG;
randomIMG = 'img[data-image-seq=img' + randomIMG + ']';
document.querySelector(randomIMG).style.display = 'block';
}
function returnRandomOddNum() {
var randomNum = Math.floor(Math.random() * imgs.length);
randomNum = (randomNum % 2 != 0) ? randomNum : randomNum + 1;
return randomNum;
}
.imgs-wrapper { position: relative; }
.imgs-wrapper { cursor: pointer; }
.hide-me { display: none; }
<div class="imgs-wrapper">
<img data-image-seq="img1" src="//dummyimage.com/150x50?text=egg">
<img data-image-seq="img2" src="//dummyimage.com/150x50?text=broke egg" class="hide-me">
<img data-image-seq="img3" src="//dummyimage.com/150x50?text=lite" class="hide-me">
<img data-image-seq="img4" src="//dummyimage.com/150x50?text=broke light" class="hide-me">
<img data-image-seq="img5" src="//dummyimage.com/150x50?text=pot" class="hide-me">
<img data-image-seq="img6" src="//dummyimage.com/150x50?text=frys" class="hide-me">
<img data-image-seq="img7" src="//dummyimage.com/150x50?text=Hi1" class="hide-me">
<img data-image-seq="img8" src="//dummyimage.com/150x50?text=Hi2" class="hide-me">
<img data-image-seq="img9" src="//dummyimage.com/150x50?text=Hello1" class="hide-me">
<img data-image-seq="img10" src="//dummyimage.com/150x50?text=Hello2" class="hide-me">
</div>
Use this function to toggle the visibility of two elements on click:
function bindToggleVisibilityOnClick(firstElemId, secondElemId) {
var firstElement = document.getElementById(firstElemId);
var secondElement = document.getElementById(secondElemId);
firstElement.onclick = function() { toggleVisibility(firstElement, secondElement); };
secondElement.onclick = function() { toggleVisibility(secondElement, firstElement); };
}
function toggleVisibility(checkElem, otherElem){
// If target is invisible
if (checkElem.style.display == "none"
//|| checkElem.style.visibility == "hidden"
) {
checkElem.style.display = "block";
// checkElem.style.visibility = "visible";
otherElem.style.display = "none"
// otherElem.style.visibility = "hidden";
}
else {
otherElem.style.display = "block";
checkElem.style.display = "none"
// checkElem.style.visibility = "hidden";
}
};
bindToggleVisibilityOnClick("egg", "brokenEgg");
#egg { display: block; }
#brokenEgg { display: none; }
<div id="egg"><p>hi</p></div>
<div id="brokenEgg"><p>hi2</p></div>
Use as such:
// Should now toggle visibility on click
bindToggleVisibilityOnClick("egg", "brokenEgg");
Also note I've left lines to toggle visibility instead of display, which will hide the element but leave the space that it takes up.
EDIT: If you want it to change once and not revert, comment out that second binding in the function as follows:
function bindToggleVisibilityOnClick(firstElemId, secondElemId) {
var firstElement = document.getElementById(firstElemId);
var secondElement = document.getElementById(secondElemId);
firstElement.onclick = function() { toggleVisibility(firstElement, secondElement); };
//secondElement.onclick = function() { toggleVisibility(secondElement, firstElement); };
}
function toggleVisibility(checkElem, otherElem){
// If target is invisible
if (checkElem.style.display == "none"
//|| checkElem.style.visibility == "hidden"
) {
checkElem.style.display = "block";
// checkElem.style.visibility = "visible";
otherElem.style.display = "none"
// otherElem.style.visibility = "hidden";
}
else {
otherElem.style.display = "block";
checkElem.style.display = "none"
// checkElem.style.visibility = "hidden";
}
};
bindToggleVisibilityOnClick("egg", "brokenEgg");
#egg { display: block; }
#brokenEgg { display: none; }
<div id="egg"><p>hi</p></div>
<div id="brokenEgg"><p>hi2</p></div>
If I understood the question correctly you ca use an object instead of an array for myShapes.
var myShapes = {
"egg.png": "brokeEgg.png",
...
}
so when you click an image you can find the paired one.

Add different classes to VERTICAL or HORIZONTAL img

I want to style differently the images if they are vertical or hotizontal.
I'm playing around with this code but it's not working. Any ideas?
JAVASCRIPT
(function() {
var orientation,
img = new Image();
img.onload = function () {
if (img.naturalWidth > img.naturalHeight) {
$(img).addClass('landscape');}
else (img.naturalWidth < img.naturalHeight) {
$(img).addClass('portrait');}
})();
CSS
img {max-width:500px;}
.landscape {max-width: 750px;}
.portrait {max-width: 500px;}
I've just created short codepen here to show you my way of working with images:
codepen link
HTML:
<img src="https://pixabay.com/static/uploads/photo/2014/07/27/20/29/landscape-403165_960_720.jpg" />
<img src="https://s-media-cache-ak0.pinimg.com/736x/f5/a0/62/f5a0626a80fe6026c0ac65cdc2d8ede2.jpg" />
CSS:
.landscape {max-width: 750px;}
.portrait {max-width: 500px;}
JS:
window.onload = function () {
var images = document.getElementsByTagName('img');
for( var i=0; i<images.length;i++){
if (images[i].naturalWidth > images[i].naturalHeight) {
$(images[i]).addClass('landscape');
}
else{
if(images[i].naturalWidth < images[i].naturalHeight) {
$(images[i]).addClass('portrait');
}
}
}
}
You cannot use condition with else part of if-else statement. Use the following code structure:
img.onload = function () {
if (condition) {
// if above condition is true then do this ...
} else {
// otherwise do this ...
}
});
var images = $('.img img');
images.load(function() {
if (this.naturalWidth > this.naturalHeight) {
$(this).addClass('landscape');
} else {
$(this).addClass('portrait');}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="img">
<img src="http://www.w3schools.com/html/pic_mountain.jpg" alt="Image Description">
</div>

Change image src and id when image is clicked (Play / Pause button)

I am trying to make a play / pause button.
This is what I have right now.
Here is the html.
<img alt="play" src="img/play.png" id="imgClickAndChange" onclick="changeImage()" class="hidden-xs hidden-sm" style="position: relative; width: 10%; z-index: 10000; margin: 0 auto; top: 42%;"/>
Here is the javascript:
function changeImage() {
if (document.getElementById("imgClickAndChange").src = "../final_copy/img/play.png")
{
document.getElementById("imgClickAndChange").src = "../final_copy/img/pause.png";
}
else {
if (document.getElementById("imgClickAndChange").src = "../final_copy/img/pause.png")
{
document.getElementById("imgClickAndChange").src = "../final_copy/img/play.png";
}
}
}
I know th second "if" probably isn't needed but neither way works. I can only get the image to change from the play image to the pause image but when I click it again it doesn't change back.
Thanks for the help!
You are comparing those src values wrong. Use == instead of =
if (document.getElementById("imgClickAndChange").src == "../final_copy/img/play.png") {
document.getElementById("imgClickAndChange").src = "../final_copy/img/pause.png";
}
else {
if (document.getElementById("imgClickAndChange").src == "../final_copy/img/pause.png") {
document.getElementById("imgClickAndChange").src = "../final_copy/img/play.png";
}
}
If its a simple toggle function, you'd need just one check:
function changeImage() {
if (document.getElementById("imgClickAndChange").src == "../final_copy/img/play.png") {
document.getElementById("imgClickAndChange").src = "../final_copy/img/pause.png";
}else{
document.getElementById("imgClickAndChange").src = "../final_copy/img/play.png";
}
}
you need var isPasued=false; switch image src!
var isPaused=false;
var imgObj=document.querySelect("img")[0]; //edit this
imgObj.addEventListener("click",function(){
if(!isPaused){
imgObj.src="../final_copy/img/play.png";
isPaused=true;
}
else
{
imgObj.src="../final_copy/img/pause.png";
isPaused=false;
}
});
= is == I agree the one answer in up!
var element = "document.getElementById("imgClickAndChange").src",
play = "../final_copy/img/play.png",
pause = "../final_copy/img/pause.png";
if (element == play) {
element = pause;
} else {
if (element == pause) {
element = play";
}
}
}

Javascript Images Resize

I want to resize images depend on its size in CSS with JS function which get all images in the div but i am facing problems with getelement by tagname which i have to set the images styles into the img HTML tag or its never work , in this test project its easy to do but in my real one there is many images into this div and many pages so here the function and its HTML
<script type="text/javascript">
function x() {
var yourdiv = document.getElementById('test');
var yourImgs = yourdiv.getElementsByTagName('img');
for (var i = 0; i < yourImgs.length; i++) {
if (yourImgs[i].style.height == '1000px' && yourImgs[i].style.width == '1000px')
{
yourImgs[i].style.height = '700px';
yourImgs[i].style.width = '800px';
}
else
{
yourImgs[i].style.height = '400px';
yourImgs[i].style.width = '300px';
}
}
}
window.onload= x;
</script>
</head>
<body>
<div id="test">
<img alt='' class="test_img" style="height:1000px;width: 1000px;" src='imges/book1.jpg' />
<img alt='' class="test_img" style="height:1000px;width: 1000px;" src='imges/book2.jpg' />
</div>
Ignore style and just check for height and width like in this example:
http://jsfiddle.net/5yjfy/2/
function x() {
var yourdiv = document.getElementById('test');
var yourImgs = yourdiv.getElementsByTagName('img');
for (var i = 0; i < yourImgs.length; i++) {
if (yourImgs[i].height == 1000 && yourImgs[i].width == 1000)
{
yourImgs[i].style.height = '700px';
yourImgs[i].style.width = '800px';
}
else
{
yourImgs[i].style.height = '400px';
yourImgs[i].style.width = '300px';
}
} } window.onload= x;

Categories