can't get array of images using JQuery, js, jsp - javascript

I have jsp page where I get products from database and for each product i have several images. i want to create simple image slider in JS for each product, but i can't get an array of images on JS. i try to do it by id in img tag, but have null. i understand that i need to use JQuery and i need to get a link on every product img, but don't know how, maybe somebody can help me.
Jsp
<c:forEach items="${produkt}" var="produkt">
<div class="produkt-container" style=" border: 1px solid #ccc; display: inline-block;text-align:left;">
<a href="produkt${produkt.id}" >${produkt.model}</a>
<%--<img src="${produkt.images[o]}" alt="">--%>
<div id="img-container" style="max-width: 280px">
<button class="btnClass" id="prev" onclick="plusImg(-1)">❮
</button>
<c:forEach items="${produkt.images}" var="image">
<img src="${image}" id="img-list" alt="" style="border: 1px solid black; width: 260px">
</c:forEach>
<button class="btnClass" id="next" onclick="plusImg(1)">❯</button>
</div>
</div>
</c:forEach>
simple slider in js
<script>
var count = 1;
sliderImg(count);
function plusImg(n) {
sliderImg(count += n);
}
function sliderImg (n) {
var i;
// var ar = $('.produkt-container').find('a');
// var x = $(this).attr('href');
var x = document.getElementsByClassName(".img-list");
if(n > x.length){count =1}
if(n < 1){count = x.length}
for (i =0; i<x.length; i++){
x[i].style.display ="none";
}
x[count-1].style.display = "block";
console.log(x);
}

Related

Collapse each div separately in C# MVC Razor foreach loop

I'm working on C# mvc project, and I'm trying to load product cart partial view, where I want in each row to have a button Read More for product specification. When users click on Read more it should collapse in div where specification for product are loaded.
I manage to accomplish this by creating css style for div Id - product-intro, but It functioning just on first row.
I'm now trying to dynamically create div Id's and also style inline product-intro"+"-"+i and I cant manage working.
Thanks in advance for any suggestions.
Here is my html:
#{int i = 0;}
#foreach (var line in Model.Lines)
{
var validQuantityClass = line.Quantity <= line.InStock ? "" : "danger";
<tr class="article #validQuantityClass" id="article-#line.Product.ProductId">
<td>
<div class="media">
<h4 class="group inner list-group-item-heading">#line.Product.Name</h4>
#{i++;}
<script>articleSpec()</script>
<div class="media-body">
<div id="#("product-intro"+"-"+i)" class="collapse" style="margin-bottom: 10px; border-bottom:1px solid #dee2e6; padding:10px 0; font-size: 12px;">
<div class="row justify-content-between">
<div class="col">
<span id='#string.Format("article-{0}-spec", line.Product.tecId)'></span>
</div>
</div>
</div>
<button type="button" class="btn btn-default" data-toggle="collapse" data-target="#product-intro-#i">Read More +</button>
</div>
</div>
</td>
</tr>
}
Javascript:
<script>
function articleSpec() {
$("#product-intro").each(function (index) {
var articleId = document.getElementById('tecId').value;
if (!articleId)
return;
var labelSelector = "#article-" + articleId + "-spec";
var url = "/Search/ArticleSpecification";
var postdata = "articleid=" + articleId;
$.post(url,
postdata,
function (data) {
$(labelSelector).html(data);
});
});
}
</script>
And this is my css for product-intro:
.cart-content #product-intro {
margin-bottom: 10px;
border-top: 1px solid #dee2e6;
border-bottom: 1px solid #dee2e6;
padding: 10px 0;
font-size: 12px;
}
I also tried to pass #i in javascript and dynamically load data in div:
function articleSpec(number) {
$("#product-intro" + '-' + number).each(function (index) {

How to shift pictures on click using jQuery

I am trying to shift my pictures to the left using jQuery. I am using a while statement to change all pictures. Here is my code:
<script language="javascript">
$(function() {
$("#leftButton").click(function() {
var imglength = $("#content").children("img").length;
var iterations = imglength;
var lastimg = imglength-1;
var nextimg = lastimg-1;
var start = 1;
var text = "";
document.getElementById("Number").innerHTML="The number of pictures is " + imglength;
document.getElementById("Number1").innerHTML="The index of the last image is " + lastimg;
while (start < iterations)
{
var last = $("img:eq('lastimg')").attr("src");
var next = $("img:eq('nextimg')").attr("src");
text += "<br>Iteration: " + imgindex + " and nextimg is:" +nextimg;
$("img:eq('lastimg')").attr('src', next);
start++;
nextimg--;
}
document.getElementById("Number2").innerHTML = text;
})
})
</script>
HTML is here:
Imgae Shift
Left Shift
Pictures
<p id="Number">Number</p>
<p id="Number1">Number</p>
<p id="Number2">Number</p>
<div id="result"></div>
</section>
</section>
<footer>
© Matthew King: 2015, Birmingham, AL 35211
</footer>
</body>
</html>
It might be easier to simply append the first image back to its parent. This should remove it and add it back as the last child. In the demo, each image has a border so you can see what is happening. I am guessing this is what you are after, but if not let me know.
function slideKittens(){
var first = document.querySelector("#kittens > img");
first.parentNode.appendChild(first);
}
setInterval(slideKittens, 1 * 1000);
#kittens img {
border: solid 2px black;
margin: 2px;
padding: 0px;
display: inline-block;
float: left;
}
<div id="kittens" style="overflow: hidden; width:333px; height: 108px">
<img src="http://placekitten.com/100/100" style="border-color: black;" />
<img src="http://placekitten.com/100/100" style="border-color: red;" />
<img src="http://placekitten.com/100/100" style="border-color: green;" />
<img src="http://placekitten.com/100/100" style="border-color: blue;" />
</div>
The problem is that you do not use the variables correctly.
The lines
var last = $("img:eq('lastimg')").attr("src");
var next = $("img:eq('nextimg')").attr("src");
$("img:eq('lastimg')").attr('src', next);
should be
var last = $("img:eq('" + lastimg + "')").attr("src");
var next = $("img:eq('" + nextimg+ "')").attr("src");
$("img:eq('" + lastimg +"')").attr('src', next);

How to make images a simple slider in js

i only know html, js and css. i'm trying to make the images change every couple of seconds., as in a slideshow.
<script type="text/javascript">
var temp=1;
function slider(){
document.getElementById("pic1").style.display = 'none';
document.getElementById("pic2").style.display = 'none';
document.getElementById("pic3").style.display = 'none';
if(temp==1){
document.getElementById("pic1").style.display = 'block';
}
else if(temp==2){
document.getElementById("pic2").style.display = 'block';
}
else if (temp==3){
document.getElementById("pic3").style.display = 'block';
temp=1;
}
temp++;
setTimeout(slider(),25000);
}
</script>
the head is above, body below.
<div id="rightside" onload="slider()">
<a id="pic1"><img src="photos/hamilton/candyshop.jpg" style="display:block"></a>
<a id="pic2"><img src="photos/hamilton/hamiltonboat.jpg" style="display:none"></a>
<a id="pic3"><img src="photos/hamilton/waterduel.jpg" style="display:none"></a>
</div>
There are multiple errors in this that must all be fixed for it to work.
In the line setTimeout(slider(), 25000), you should pass slider, the function itself, not slider(), the return value of the function. Then you need to call slider() once after defining it to start the whole thing. You can do this in the JavaScript with document.addEventListener instead of the HTML with onload, making the HTML self-contained.
You set the img to display:none in the HTML, and then you set the element with ID pic1 to display: block. But this element isn’t the img, it’s the a. So you end up with a display: block <a> containing a display: none <img>, so nothing shows after all.
When you set temp = 1, immediately after that you run temp++, so picture #1 is never seen again. temp = 0 on that line would fix this, but it is better to make temp loop through “0, 1, 2” and use the modulo operator % that makes numbers loop if they are too high.
I also added alt attributes describing each of the images so the demo will work without the images loading. This would help your users too if they can’t see the images for whatever reason.
A working version:
document.addEventListener("DOMContentLoaded", function(event) {
var temp = 0;
function slider() {
document.getElementById("pic1").style.display = 'none';
document.getElementById("pic2").style.display = 'none';
document.getElementById("pic3").style.display = 'none';
if (temp == 0) {
document.getElementById("pic1").style.display = 'block';
} else if (temp == 1) {
document.getElementById("pic2").style.display = 'block';
} else if (temp == 2) {
document.getElementById("pic3").style.display = 'block';
}
temp = (temp + 1) % 3;
setTimeout(slider, 1500); // decreased delay for demo purposes
}
slider();
});
<div id="rightside">
<a id="pic1" style="display:block">
<img alt="candy shop" src="photos/hamilton/candyshop.jpg">
</a>
<a id="pic2" style="display:none">
<img alt="Hamilton boat" src="photos/hamilton/hamiltonboat.jpg">
</a>
<a id="pic3" style="display:none">
<img alt="water duel" src="photos/hamilton/waterduel.jpg">
</a>
</div>
After getting the code working like the above, you can also reduce the repetition by using loops and functions. With the following version, if you add more pictures, you will only need to change one line of code instead of copying and pasting multiple parts of your code. Splitting your code up into functions that are each simple has the additional benefit that the code is easier to understand and to check for errors in.
document.addEventListener("DOMContentLoaded", function(event) {
var currentIndex = 0;
var numPictures = 3;
function slideshow() {
hideAllPictures();
showPicture(currentIndex);
currentIndex = (currentIndex + 1) % numPictures;
setTimeout(slideshow, 1500);
}
function hideAllPictures() {
for (var i = 0; i < numPictures; i++) {
hidePicture(i);
}
}
function hidePicture(index) {
getPictureElement(index).style.display = 'none';
}
function showPicture(index) {
getPictureElement(index).style.display = 'block';
}
function getPictureElement(index) {
var id = "pic" + (index + 1);
return document.getElementById(id);
}
slideshow();
});
<div id="rightside">
<a id="pic1" style="display:block">
<img alt="candy shop" src="photos/hamilton/candyshop.jpg">
</a>
<a id="pic2" style="display:none">
<img alt="Hamilton boat" src="photos/hamilton/hamiltonboat.jpg">
</a>
<a id="pic3" style="display:none">
<img alt="water duel" src="photos/hamilton/waterduel.jpg">
</a>
</div>
Try this with Pure Javascript and CSS, change only myimage*.jpg to your image name.
<!DOCTYPE html>
<html>
<title>My Simple Slider</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
.fading{
-webkit-animation:fading 10s infinite;
animation:fading 10s infinite
}
#-webkit-keyframes fading {
0%{opacity:0}
50%{opacity:1}
100%{opacity:0
}
}
#keyframes fading {
0%{opacity:0}
50%{opacity:1}
100%{opacity:0
}
}
</style>
<body>
<div>
<p>Simple Image Carousel</p>
<img class="mySlides fading" src="myimage1.jpg" style="width:100%">
<img class="mySlides fading" src="myimage2.jpg" style="width:100%">
<img class="mySlides fading" src="myimage3.jpg" style="width:100%">
<img class="mySlides fading" src="myimage4.jpg" style="width:100%">
</div>
<script>
var myIndex = 0;
carousel();
function carousel() {
var i;
var x = document.getElementsByClassName("mySlides");
for (i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
myIndex++;
if (myIndex > x.length) {
myIndex = 1
}
x[myIndex - 1].style.display = "block";
setTimeout(carousel, 9000);
}
</script>
</body>
</html>

managing several show/hide divs

I have some scripts here that show and hide divs when click. Now what I need is to just only display one div at a time. I have a code that controls them all but its not working I don't know about much of javascript.
This is the first example of show/hide function that can be done simultaneously without hiding the other divs.
FIDDLE HERE
HTML:
<a href="javascript:ReverseDisplay('uniquename')">
Click to show/hide.
</a>
<div id="uniquename" style="display:none;">
<p>Content goes here.</p>
</div>
<a href="javascript:ReverseDisplay('uniquename1')">
Click to show/hide.
</a>
<div id="uniquename1" style="display:none;">
<p>Content goes here.</p>
</div>
SCRIPT:
function HideContent(d) {
document.getElementById(d).style.display = "none";
}
function ShowContent(d) {
document.getElementById(d).style.display = "block";
}
function ReverseDisplay(d) {
if (document.getElementById(d).style.display == "none") {
document.getElementById(d).style.display = "block";
} else {
document.getElementById(d).style.display = "none";
}
}
function HideAllShowOne(d) {
// Between the quotation marks, list the id values of each div.
var IDvaluesOfEachDiv = "idone idtwo uniquename1 uniquename";
//-------------------------------------------------------------
IDvaluesOfEachDiv = IDvaluesOfEachDiv.replace(/[,\s"']/g," ");
IDvaluesOfEachDiv = IDvaluesOfEachDiv.replace(/^\s*/,"");
IDvaluesOfEachDiv = IDvaluesOfEachDiv.replace(/\s*$/,"");
IDvaluesOfEachDiv = IDvaluesOfEachDiv.replace(/ +/g," ");
var IDlist = IDvaluesOfEachDiv.split(" ");
for(var i=0; i<IDlist.length; i++) { HideContent(IDlist[i]); }
ShowContent(d);
}
The other fiddle I created would do what I need but the script seems not to be working. Fiddle here
Found the solution on my code thanks to #Abhas Tandon
Fiddle here the extra id's inside the IDvaluesOfEachDiv seems to be making some error with the codes.
If you are happy with IE10+ support then
function ReverseDisplay(d) {
var els = document.querySelectorAll('.toggle.active:not(#' + d + ')');
for (var i = 0; i < els.length; i++) {
els[i].classList.remove('active');
}
document.getElementById(d).classList.toggle('active')
}
.toggle {
display: none;
}
.toggle.active {
display: block;
}
<a href="javascript:ReverseDisplay('uniquename')">
Click to show/hide.
</a>
<div id="uniquename" class="toggle">
<p>Content goes here.</p>
</div>
<a href="javascript:ReverseDisplay('uniquename1')">
Click to show/hide.
</a>
<div id="uniquename1" class="toggle">
<p>Content goes here.</p>
</div>
I would suggest to use jQuery which is far easier.
Include thiswithin
<head>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
</head>
HTML
<div id="id_one">Item 1</div>
<div id="content_one">
content goes here
</div>
<div id="id_two">Item 1</div>
<div id="content_two">
content goes here
</div>
Script:
$(function()
{
$("#content_one").hide();
$("#content_two").hide();
});
$("#id_one").on("click",function()
{
$("#content_one").slideDown("fast");
});
$("#id_two").on("click",function()
{
$("#content_two").slideDown("fast");
});
If you have a "Button" for every DIV inside your HTML - you can go by element index
var btn = document.querySelectorAll(".btn");
var div = document.querySelectorAll(".ele");
function toggleDivs() {
for(var i=0; i<btn.length; i++) {
var us = i===[].slice.call(btn).indexOf(this);
btn[i].tog = us ? this.tog^=1 : 0;
div[i].style.display = ["none","block"][us?[this.tog]:0];
}
}
for(var i=0; i<btn.length; i++) btn[i].addEventListener("click", toggleDivs);
.btn{/* Anchors Buttons */ display:block; cursor:pointer; color:#00f;}
.ele{/* Hidden Divs */ display:none;}
<a class="btn"> 1Click to show/hide.</a>
<div class="ele"><p>1Content goes here.</p></div>
<hr>
<a class="btn">2Click to show/hide.</a>
<div class="ele"><p>2Content goes here.</p></div>
<hr>

How to not insert duplicate images?

So what I have done is that, I have created a function that retrives data(images) from the database using XMLHttpRequest and appends it to td every 5000 milliseconds. Now as they are appended every 5000 milliseconds, if the data retrieved is not changed then it keeps appending the same data again and again. To stop it I attached custom attributes to the images with their IDs but I am not sure how would I stop it from appending duplicated items. This is my JS:
function getAlbumImages() {
var xhr2 = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
xhr2.open('GET', 'admin/images_data.php');
xhr2.onreadystatechange = function(e) {
if(xhr2.readyState == 4 && xhr2.status == 200) {
var album_photos = JSON.parse(xhr2.responseText);
for(var i = 0; i < album_photos.length; i++) {
var td = document.createElement('td');
var imagewrap = document.createElement('div');
imagewrap.className = "image-wrap";
var imagemenu = document.createElement('div');
imagemenu.className = "image-menu";
var imagemenuimg1 = document.createElement('img');
imagemenuimg1.src = "img/edit_img.png";
var imagemenuimg2 = document.createElement('img');
imagemenuimg2.src = "img/close.png";
var imagewrapimg = document.createElement('img');
imagewrapimg.className = "thumbnail";
imagewrapimg.src = "admin/album_photos/" + album_photos[i].Image_Path;
imagewrapimg.setAttribute("data-image-id", album_photos[i].Image_ID);
document.getElementById("tiare").appendChild(td);
td.appendChild(imagewrap);
imagewrap.appendChild(imagemenu);
imagemenu.appendChild(imagemenuimg1);
imagemenu.appendChild(imagemenuimg2);
imagewrap.appendChild(imagewrapimg);
}
}
}
xhr2.send(null);
}
setInterval(function(){
getAlbumImages();
}, 5000);
And the markup:
<html>
<head>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<!-- <div class="big_image" id="drop_zone">
<img src="" id="big_img" />
</div -->
<div class="images_holder">
<div class="header">
Album Name - Photo Album
<span class="close"><img src="img/close.png" /></span>
</div>
<div class="body">
<table width="80%">
<tr id="tiare">
</tr>
</table>
</div>
</div>
<div id="drop_zone">
Drag/Drop images to upload.
</div>
<div style="height: 30px; width: 80%; color: white; text-align: center; margin: 0 auto;">
<p id="progress_bar" style="width: 0%; background-color: red;"></p>
</div>
<script src="js/script.js"></script>
</body>
</html>
This is what happens the first time:
And this is what happens afterwards:
See the duplicated images
How can I stop it from appending the duplicated? Thanks in advance. :)
P.S: NO JQUERY ALLOWED. :)
Just check if instance with same ID or URL is at page before insert
if(document.querySector('div.thumbnail[data-image-id="' + album_photos[i].Image_ID + '"]')){
continue;
}
Or save list of all inserted id's in memory ( as array or object { id: url } ) and check if this item already loaded

Categories

Resources