Why will my pictures not go through my if statements [closed] - javascript

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I am trying to make it so that every time that I click on the button that I created it cycles through the photos. Right now it won't do anything that I want
I think that a for loop would be the best way to go about this but I don't know what I am doing
var images = ["img/profile.jpg", "img/mountain.jpg", "img/sanfran.jpg"];
function loadPage() {
document.getElementById("pictures").src = images[0];
}
function nextImage() {
if (document.getElementById("pictures").src = images[0]) {
document.getElementById("pictures").src = images[1];
} else if (document.getElementById("pictures").src = images[1]) {
document.getElementById("pictures").src = images[2];
} else(document.getElementById("pictures").src = images[2]) {
document.getElementById("pictures").src = images[0];
}
}
<body onclick="loadPage()">
<div id="maincontent">
<div>
<img id="pictures">
</div>
<div id="paragraph">
<button class="button" onclick="nextImage()">Switch Images</button>
</div>
</div>
</body>

While Jet is on the right track. It will stop working after the last image, as index will be out of bounds.
EDIT Jet has updated their code, and the way of keeping index in bounds is quite elegant.
See the below example:
<body>
<div id="maincontent">
<div>
<img id="pictures">
</div>
<div id="paragraph">
<button class="button" onclick="nextImage()">Switch Images</button>
</div>
</div>
<script>
var images = [
"https://via.placeholder.com/150x150.png?text=1",
"https://via.placeholder.com/150x150.png?text=2",
"https://via.placeholder.com/150x150.png?text=3"
];
let currentImage = -1;
function nextImage() {
currentImage++; // Add 1 to the currentImage variable
if (currentImage === images.length) {
currentImage = 0; // If we've reached the last image, go to the first image
}
document.getElementById("pictures").src = images[currentImage]; // Set the src image to the current image in our images array
}
nextImage();
</script>
</body>

Bascially i cycle through the names of images stored in the array. i used the modulo (%) to ensure that i wont go out of bound of the array
<body>
<div id="maincontent">
<div>
<img src="img/profile.jpg" id="pictures">
</div>
<div id="paragraph">
<button class="button" onclick="nextImage()">Switch Images</button>
</div>
</div>
<script type="text/javascript">
var index = 1;
var images = ["img/profile.jpg", "img/mountain.jpg", "img/sanfran.jpg"];
function nextImage(){
document.getElementById('pictures').src = images[index%3];
index++;
}
</script>
</body>

var images = ["https://via.placeholder.com/150", "https://via.placeholder.com/500",];
var imageElement = document.getElementById("pictures");
function loadPage() {
imageElement.src = images[0];
}
function nextImage() {
if(imageElement.src == images[0])
imageElement.src = images[1];
else if (imageElement.src == images[1])
imageElement.src = images[2];
else if (imageElement.src == images[2])
imageElement.src = images[0];
}
<body onclick="loadPage()">
<div id="maincontent">
<div>
<img id="pictures">
</div>
<div id="paragraph">
<button class="button" onclick="nextImage()">Switch Images</button>
</div>
</div>
</body>
The issue was simple, inside IF conditions use ==
== is for comparison, = is for assignment
P.S instead of calling document.getElementById repeadetly to get the same element, you can also store the element's reference once in a variable and use it, to increase performance

== is used for conditions, and = is used for assignment. However, I would advise using a switch in this case instead of an if statement as below:
<body onclick="loadPage()">
<div id="maincontent">
<div>
<img id="pictures">
</div>
<div id="paragraph">
<button class="button" onclick="nextImage()">Switch Images</button>
</div>
</div>
<script>
let images = ["img/profile.jpg", "img/mountain.jpg", "img/sanfran.jpg"];
let src = document.getElementById("pictures").src
function loadPage() {
src = images[0];
}
function nextImage() {
switch (document.getElementById("pictures").src) {
case images[0]:
src = images[1];
break
case images[1]:
src = images[2];
break
case images[2]:
src = images[0];
break
}
}
</script>
</body>
EDIT: It seems others have come up with an even more efficient way to do this, but I'll leave it here as a reference to an alternative.

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

Image slider requiring 1 extra click to reset. Unable to fix

I've tried to fix this problem for the past 1 hour without success. Basically, once I reach "imageB", I have to click 1 extra time before the image resets back to "imageA". I don't understand why this is happening. Any assistance will be greatly appreciated:
HTML:
<body>
<div class="main-container">
<div class="image-div">
<img width="500px" id="image-holder" src="images/imageA.jpeg" alt="" />
</div>
<button onclick="nextImage()">Next</button>
</div>
<script src="index.js"></script>
</body>
JS:
let imageHolder = document.getElementById("image-holder");
let images = ["images/imageA.jpeg", "images/imageB.jpeg"];
let i = 1;
function nextImage() {
if (i < images.length) {
imageHolder.setAttribute("src", images[i]);
i++;
} else {
i = 0;
}
}
I made a code which can solve your problem, but I think it's a little long, maybe you can find a code more readable on more short than my, anyway here is my solution and it works for me:
everytime when you click in the button, the function give the next item in the array (next source), but if the item is in the end of the array he start again by the first item in the array.
<div class="main-container">
<div class="image-div">
<img width="500px" id="image-holder" src="./img1.png" alt="" />
</div>
<button onclick="nextImage()">Next</button>
</div>
let imageHolder = document.getElementById("image-holder");
let images = ["./img1.png", "./oz.png","./img2.png"];
function nextImage() {
let getSrcAttr = imageHolder.getAttribute("src");
let newSrc =
imageHolder.setAttribute("src",images[(images.indexOf(getSrcAttr))+1]);
if(images.indexOf(getSrcAttr) == (images.length)-1){
newSrc = imageHolder.setAttribute("src",images[0]);
}
}

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>

Div Traversing with jquery [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I want to know that, when I click on next button than id="upper1" become id="upper2" and id="upper2" become id="upper3" and id="upper3" become id="upper1" and so on.
Jquery
$('#next').click(function() {
var $dives = $('div');
var total_div = $sel.length;
for (var i = 1; i <= total_div; i++) {
$dives.eq(i).attr('id', $dives.eq(i + 1).attr('id'));
}
});
CSS
#upper1{
background-color:red;
}
#upper2{
background-color:yellow;
}
#upper3{
background-color:orange;
}
HTML
<div id="upper1">9</div>
<div id="upper2">8</div>
<div id="upper3">7</div>
<button id="next">Next</button>
You may do something like this that may work with any number of element with any IDs:
$('#next').click(function() {
let $sel = $('.container > div')
let l = $sel.length;
let last = $sel.eq(l - 1).attr('id');
for (let i = l - 1; i >= 1; i--) {
$sel.eq(i).attr('id', $sel.eq(i - 1).attr('id'));
}
$sel.eq(0).attr('id', last);
})
#upper1 {
background-color: red;
}
#upper2 {
background-color: yellow;
}
#upper3 {
background-color: orange;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div id="upper1">9</div>
<div id="upper2">8</div>
<div id="upper3">7</div>
</div>
<button id="next">Next</button>
With jQuery, you may use:
$("#next").click(function() {
var i1 = $("#upper1");
var i2 = $("#upper2");
var i3 = $("#upper3");
i1.attr("id", "upper2");
i2.attr("id", "upper3");
i3.attr("id", "upper1");
});
You will need to put the code inside a block that waits for the page to load like:
$(document).ready(function() {
<code here>
});
The use of attr allows to set a new id to each of the former id´s. Check the jsFiddle.
Also, as noted by other people, this would be better done by having fixed id´s and changing classes that defined the attributes to rotate.
Is changing the ids themselves really the goal or rather swapping the elements? (with contents)
$('#next').click(function(){
$("#container").children().last().prependTo("#container");
})
#upper1{
background-color:red;
}
#upper2{
background-color:yellow;
}
#upper3{
background-color:orange;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
<div id="upper1">9</div>
<div id="upper2">8</div>
<div id="upper3">7</div>
</div>
<button id="next">Next</button>
Or if the goal is switching the colours and not the elements themselves, it can be done with classes instead of swapping the ids:
$('#next').click(function(){
$("[class^=upper]").each(function(){
this.className = "upper" + (((this.className.substring(5) + 1) % 3)+1);
});
})
.upper1{
background-color:red;
}
.upper2{
background-color:yellow;
}
.upper3{
background-color:orange;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="upper1">9</div>
<div class="upper2">8</div>
<div class="upper3">7</div>
<button id="next">Next</button>
I guess you actually want to shuffle the divs not replace ids.
let divs = $(yourDivSelector);
divs.first().prepend(divs.last());
This code would move the last to the top and thereby move the rest down one step.

Make a book reader using images [jquery]

I've been trying for the past hours to create a Comic Book online reader to allow my images to load up.
Everything works fine but I use a counter using a increment method basically and it just doesn't work because bringing down the increments breaks the function.
Maybe there is a simpler way? Also jQuery is the most obscure language to learn unlike HTML or PHP, jQuery has a documentation that pretty much has no organization. Its like here's all the stuff now read each one and maybe you'll find yours. My code is below
<script>
$(function manga () {
var count = 0;
var images = ["source_images/01.jpg", "source_images/02.jpg", "source_images/03.jpg", "source_images/04.jpg", "source_images/05.jpg", "source_images/06.jpg", "source_images/07.jpg"];
$("#left").click(function () {
var img = images[count % images.length];
++count;
$("#manga").attr("src", img);
//alert("clicked");
manga();
});
$("#right").click(function () {
var img = images[count % images.length];
--count;
$("#manga").attr("src", img);
//alert("clicked");
manga();
});
manga();
});
</script>
<title></title>
<center>
<img id="left" style="width:10%; float:left; padding:1.3%" src="files/left_arrow.png" />
<div >
<img id="manga" style="width:75%; float:left" src="source_images/00.jpg" />
</div>
<img id="right" style="width:10%; float:left; padding:1.2%" src="files/right_arrow.png" />
</center>
Basically your calling your function manga 3 times
first when it loads
second when your do left click
and third when you do right click
In this your initializing counter to keep track of the images and everytime
your calling function again your initializing it to 0
so your count again starting from 0.
So to avoid it make your count variable global declare it outside the manga() function.
checkout this code
<script>
var count = 0;
$(function manga () {
var images = ["source_images/01.jpg", "source_images/02.jpg", "source_images/03.jpg", "source_images/04.jpg", "source_images/05.jpg", "source_images/06.jpg", "source_images/07.jpg"];
$("#left").click(function () {
++count;
var img = images[count % images.length];
alert(img);
$("#manga").attr("src", img);
//alert("clicked");
manga();
});
$("#right").click(function () {
if(count == 0)
{
count = images.length-1;
}
else {
--count;
}
var img = images[count % images.length];
alert(img);
$("#manga").attr("src", img);
//alert("clicked");
manga();
});
manga();
});
</head>
<body>
<center>
<center>
<img id="left" style="width:10%; float:left; padding:1.3%" src="files/left_arrow.png" />
<div >
<img id="manga" style="width:75%; float:left" src="source_images/00.jpg" />
</div>
<img id="right" style="width:10%; float:left; padding:1.2%" src="files/right_arrow.png" />
</center>
</center>
I changed the position of count variable in both left and right click. And added one if condition in left click so that when the page loads first time and if user click left arrow first it will show last image.
so image src will move from first to last.It will work.

Categories