creating html div from json using javascript - javascript

i wanted to create a sliding image gallery in a div. To get the images and the description i make a get request on an api. The returned json is as expected and until that, the code works.
I have found this sliding gallery on W3Ccourses https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_slideshow_auto and i wanted to use it with my data.
I get these 2 errors:
Unable to get property 'style' of undefined or null reference Here is the code
'require' is not defined
i have tried with require.js but it didn't work. I tried to create my div even with document.createElement and then .appendChild but it didn't work. I don't think the issue is in creating the html element. Thanks for replying
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
* {box-sizing: border-box;}
body {font-family: Verdana, sans-serif;}
.mySlides {display: none;}
img {vertical-align: middle;}
/* Slideshow container */
.slideshow-container {
max-width: 1000px;
position: relative;
margin: auto;
}
/* Caption text */
.text {
color: #f2f2f2;
font-size: 15px;
padding: 8px 12px;
position: absolute;
bottom: 8px;
width: 100%;
text-align: center;
}
/* Number text (1/3 etc) */
.numbertext {
color: #f2f2f2;
font-size: 12px;
padding: 8px 12px;
position: absolute;
top: 0;
}
/* The dots/bullets/indicators */
.dot {
height: 15px;
width: 15px;
margin: 0 2px;
background-color: #bbb;
border-radius: 50%;
display: inline-block;
transition: background-color 0.6s ease;
}
.active {
background-color: #717171;
}
/* Fading animation */
.fade {
-webkit-animation-name: fade;
-webkit-animation-duration: 1.5s;
animation-name: fade;
animation-duration: 1.5s;
}
#-webkit-keyframes fade {
from {opacity: .4}
to {opacity: 1}
}
#keyframes fade {
from {opacity: .4}
to {opacity: 1}
}
/* On smaller screens, decrease text size */
#media only screen and (max-width: 300px) {
.text {font-size: 11px}
}
</style>
</head>
<!-- ####################################################### -->
<body>
<div class="slideshow-container">
<!-- ### want to get this kind of div , but with my data ###
<div class="mySlides fade">
<div class="numbertext">1 / 3</div>
<img src="img_nature_wide.jpg" style="width:100%">
<div class="text">Caption Text</div>
</div> -->
<script type="text/javascript">
url = 'http://www.myUrl.com';
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var httpReq = new XMLHttpRequest();
httpReq.open("GET" , url , false);
httpReq.send(null);
var jsonObj = JSON.parse(httpReq.responseText);
var description = jsonObj[i].description
for ( i = 0 ; i < 9 ; i++) {
document.writeln('<div class=\"mySlides fade\">');
document.writeln('<div class = \"numbertext\">' + i + '/9</div>');
document.writeln('<img src=\"' + jsonObj[i].url_image + '\" style="width :100%">');
document.writeln('<div class=\"text\">' + description + '</div>');
}
</script>
</div>
<div style="text-align:center">
<span class="dot"></span>
<span class="dot"></span>
<span class="dot"></span>
<span class="dot"></span>
<span class="dot"></span>
<span class="dot"></span>
<span class="dot"></span>
<span class="dot"></span>
<span class="dot"></span>
</div>
<script>
var slideIndex = 0;
showSlides();
function showSlides() {
var i;
var slides = document.getElementsByClassName("mySlides");
var dots = document.getElementsByClassName("dot");
for (i = 0; i < slides.length; i++) {
slides[i].style.display = "none";
}
slideIndex++;
if (slideIndex > slides.length) {slideIndex = 1}
for (i = 0; i < dots.length; i++) {
dots[i].className = dots[i].className.replace(" active", "");
}
slides[slideIndex-1].style.display = "block";
dots[slideIndex-1].className += " active";
setTimeout(showSlides, 2000); // Change image every 2 seconds
}
</script>
</body>
</html>

I checked you code and I notice three things,
You don't need this line var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest; you don't need to require it here as the XMLHttpRequest is part of the windows object.
Your usage of the xmlhttprequest method is wrong see correct implementation below.
var url = 'http://www.myUrl.com';
var httpReq = new XMLHttpRequest();
httpReq.open("GET" , url);
httpReq.send(null);
var jsonObj, description;
httpReq.onload = function() {
if (httpReq.status == 200) { // analyze HTTP status of the response
var jsonObj = JSON.parse(httpReq.responseText);
var description = jsonObj[i].description // e.g. 404: Not Found
for ( i = 0 ; i < 9 ; i++) {
document.writeln('<div class=\"mySlides fade\">');
document.writeln('<div class = \"numbertext\">' + i + '/9</div>');
document.writeln('<img src=\"' + jsonObj[i].url_image + '\" style="width :100%">');
document.writeln('<div class=\"text\">' + description + '</div>');
}
var slideIndex = 0;
showSlides();
} else { // show the result
alert(`Error: httpReq.status`); // responseText is the server
}
};
You will get a CORS error if you are not running this from the same origin as http://www.myUrl.com
Hope this helps.

You can use ajax request to retrieve your json data, then loop each object while appending a mySlides div
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script>
<script>
$(document).ready(function(){
$.getJSON("https://jsonplaceholder.typicode.com/todos/1", function(result){
$.each(result, function(i, field){
$("div.slideshow-container").append(`<div class="mySlides fade"><div class="numbertext">1 / 3</div><img src="${field.url}" style="width:100%"><div class="text">${field.caption}</div></div>`);
});
});
showSlides();
});
</script>

Related

Javascript interfering with CSS Transition

I've recently started work on a basic landing-page website. Part of the page is a basic image slider with both the auto-nav and the manual nav being powered by JS. I got everything working but for one thing: I just can't figure out how to get the smooth transition between images - as seen in this example - to work. I figured out the problem after reading some related questions on Stackoverflow: To make the Slideshow work I'm using slides[i].style.display = "none"; and slides[slideIndex-1].style.display = "block"; to update the css code handling the 'display' element - this over rights the 'transition: 2s' css code one would need for the simple slide animation as seen in the video.
As I'm terribly new to Web development I could not wrap my head around possible solutions posted here on Stackoverflow and would really appreciate anyone that could help me out with an answer to my specific problem or an alternative way to solve it.
Cheers,
Jerome
var slideIndex = 1;
showSlides(slideIndex);
// Next/previous controls
function plusSlides(n) {
showSlides(slideIndex += n);
}
// Thumbnail image controls
function currentSlide(n) {
showSlides(slideIndex = n);
}
function showSlides(n) {
var i;
var slides = document.getElementsByClassName("item");
var dots = document.getElementsByClassName("dot");
if (n > slides.length) {
slideIndex = 1
}
if (n < 1) {
slideIndex = slides.length
}
for (i = 0; i < slides.length; i++) {
slides[i].style.display = "none";
}
for (i = 0; i < dots.length; i++) {
dots[i].className = dots[i].className.replace(" active", "");
}
slides[slideIndex - 1].style.display = "block";
dots[slideIndex - 1].className += " active";
}
//automatic
var slideIndexAuto = 0;
showSlidesAuto();
function showSlidesAuto() {
var i;
var slides = document.getElementsByClassName("item");
var dots = document.getElementsByClassName("dot");
for (i = 0; i < slides.length; i++) {
slides[i].style.display = "none";
dots[i].className = dots[i].className.replace(" active", "");
}
slideIndexAuto++;
if (slideIndexAuto > slides.length) {
slideIndexAuto = 1
}
slides[slideIndexAuto - 1].style.display = "block";
dots[slideIndexAuto - 1].className += " active";
setTimeout(showSlidesAuto, 5000);
}
.slider {
width: 65%;
max-width: 940px;
height: 500px;
border-radius: 0.25rem;
position: relative;
overflow: hidden;
}
.slider .left-slide,
.slider .right-slide {
position: absolute;
height: 40px;
width: 40px;
background-color: #444444;
border-radius: 50%;
color: #ffffff;
font-size: 20px;
top: 50%;
cursor: pointer;
margin-top: -20px;
text-align: center;
line-height: 40px;
}
.slider .left-slide:hover,
.slider .right-slide:hover {
box-shadow: 0px 0px 10px black;
background-color: #29a8e2;
}
.slider .left-slide {
left: 30px;
}
.slider .right-slide {
right: 30px;
}
.slider .slider-items .item img {
width: 100%;
height: 500px;
display: block;
}
.slider .slider-items .item {
position: relative;
transition: 4s;
}
.slider .slider-items .item .caption {
position: absolute;
width: 100%;
height: 100%;
bottom: 0px;
left: 0px;
background-color: rgba(0, 0, 0, .5);
}
<div class="slider">
<div class="slider-items">
<div class="item fade">
<img src="/images/cs-slider-high.jpg" />
<div class="caption">
<p class="caption-text">COMING</p>
<p class="caption-text">OKTOBER 10th</p>
</div>
</div>
<div class="item fade">
<img src="/images/building-slider.jpg" />
<div class="caption">
<p class="caption-text-2">Blackstoneroad 109</br>
</p>
</div>
</div>
<div class="item fade">
<img src="/images/kontact-slider.jpg" />
<div class="caption">
<p class="caption-text-3">Coffee<br>Drinks<br>Food<br>& More</p>
</div>
</div>
<div class="item fade">
<img src="/images/seminar-slider.jpg" />
<div class="caption">
<p class="caption-text-3">Seminar Rooms<br>Inspiration<br>Shopping<br>& More</p>
</div>
</div>
</div>
<!-- Next and previous buttons -->
<a class="prev" onclick="plusSlides(-1)">❮</a>
<a class="next" onclick="plusSlides(1)">❯</a>
</div>
<!-- The dots/circles -->
<div class="align-text-center">
<span class="dot" onclick="currentSlide(1)"></span>
<span class="dot" onclick="currentSlide(2)"></span>
<span class="dot" onclick="currentSlide(3)"></span>
<span class="dot" onclick="currentSlide(3)"></span>
</div>
How is this: http://jsfiddle.net/lharby/qox05y96/
For simplification I have stripped out the dot animation (although that code is closer to the effect you want).
Here is the simplified JS:
function showSlides(n) {
var i;
var slides = document.getElementsByClassName("item");
var dots = document.getElementsByClassName("dot");
if (n > slides.length) {
slideIndex = 1
}
if (n < 1) {
slideIndex = slides.length
}
for (i = 0; i < slides.length; i++) {
slides[i].classList.remove('active'); // this is updated
}
slides[slideIndex - 1].className += " active";
}
//automatic
var slideIndexAuto = 0;
showSlidesAuto();
function showSlidesAuto() {
var i;
var slides = document.getElementsByClassName("item");
var dots = document.getElementsByClassName("dot");
for (i = 0; i < slides.length; i++) {
slides[i].classList.remove('active'); // this is updated
}
slideIndexAuto++;
if (slideIndexAuto > slides.length) {
slideIndexAuto = 1
}
slides[slideIndexAuto - 1].classList.add('active'); // this is updated
setTimeout(showSlidesAuto, 4000);
}
This means we also have to change the css. display none/block is harder to animate with css transitions. So I have used opacity: 0/1 and visibility: hidden/visible. However one other trade off is that that the item elements cannot be positioned relatively this would stack them on top of one another (or side by side) usually for an animated slideshow you would use position absolute for each slide, but I realise that causes you another issue.
CSS:
.slider .slider-items .item {
visibility: hidden;
opacity: 0;
transition: 4s;
}
.slider .slider-items .item.active {
visibility: visible;
opacity: 1;
transition: 4s;
}
At least now all of the css is handled within the css and the js purely adds or removes a class name which I feel makes it a bit easier to update.
There are priorities as far as what CSS deems should happen.
Take a look at this and let me know if it changes anything for you. If not I'll try and run the code and fix your errors. I want to let you know in advance, I am a pure JS developer. When I need CSS or HTML I create it in JS. I want you to try first, thus it will make you a better developer.
https://www.thebookdesigner.com/2017/02/styling-priorities-css-for-ebooks-3/

RotateY of a group of divs dynamically

I'm working on this script since 9 days, I found the script online, and from there I tried to add some code.
The point of the script is to rotate the Div dynamically based on the distance they have between each other.
In a way it works, if you resize the page at some point the divs turn their Y axes.
I have mainly 2 problems, the first one is that if I add new divs they just are shown in a new line.
The second problem is that those divs position should change, they need to get closer and they should move to the left side of the div.
I hope somebody can help because I spent already 10 days on this and I can't find a solution.
Thank you so much
function myFunction(distance) {
//add browser check currently it set for safari
// Code for Safari
var degree = 0;
if (distance <= -1 && distance >= -5) {
degree = 15;
} else if (distance < -5 && distance >= -10) {
degree = 25;
} else if (distance < -10 && distance >= -15) {
degree = 30;
} else if (distance < -15 && distance >= -20) {
degree = 35;
} else if (distance < -20) {
degree = 45;
}
document.getElementById("panel").style.WebkitTransform = "rotateY(" + degree + "deg)";
document.getElementById("panel2").style.WebkitTransform = "rotateY(" + degree + "deg)";
document.getElementById("panel3").style.WebkitTransform = "rotateY(" + degree + "deg)";
document.getElementById("panel4").style.WebkitTransform = "rotateY(" + degree + "deg)";
// document.getElementById("panel").style.marginRight= "100px";
document.getElementById("panel2").style.marginRight = "300px";
document.getElementById("panel3").style.marginRight = "30px";
document.getElementById("panel4").style.marginRight = "30px";
// document.getElementById("panel5").style.WebkitTransform = "rotateY(45deg)";
// document.getElementById("panel6").style.WebkitTransform = "rotateY(45deg)";
// Code for IE9
// document.getElementById("asd").style.msTransform = "rotateY(20deg)";
// Standard syntax
// document.getElementById("asd").style.transform = "rotateY(20deg)";
}
function myFunctionb() {
document.getElementById("panel").style.WebkitTransform = "rotateY(0deg)";
document.getElementById("panel2").style.WebkitTransform = "rotateY(0deg)";
document.getElementById("panel3").style.WebkitTransform = "rotateY(0deg)";
document.getElementById("panel4").style.WebkitTransform = "rotateY(0deg)";
// document.getElementById("panel5").style.WebkitTransform = "rotateY(0deg)";
// document.getElementById("panel6").style.WebkitTransform = "rotateY(0deg)";
}
// need to find a better solution
var first = document.getElementById("panel");
var second = document.getElementById("panel2");
var lastpanel = document.getElementById("panel4");
var lastbox = document.getElementById("last");
var container = document.getElementById("wrapper");
var notcongainer = container.offsetLeft;
var distance = container.offsetWidth - (lastpanel.offsetWidth + lastbox.offsetLeft + 4) + notcongainer;
console.log(distance);
var myVar;
var minDistance = 10;
function check() {
myVar = setInterval(testcheck, 100);
}
// First I check that the boxes lenght are as much as the container
// Then I check the distance between 2 boxes
function testcheck() {
if (distance < minDistance) {
myFunction(distance);
} else {
myFunctionb();
}
distance = container.offsetWidth - (lastpanel.offsetWidth + lastbox.offsetLeft + 4) + notcongainer;
/*console.log(distance)*/
}
//ADD NEW DIV
function addDiv() {
var div = document.createElement('div');
div.className = "col-box";
div.id = "newId";
div.innerHTML = '<div class="hover panel"><div id= "panel3" class="front"><div class="box1"><p>New Div</p></div></div></div>';
document.getElementById('wrapper').appendChild(div);
}
body {
background-color: #ecf0f1;
margin: 20px;
font-family: Arial, Tahoma;
font-size: 20px;
color: #666666;
text-align: center;
}
p {
color: #ffffff;
}
.col-box {
width: 22%;
position: relative;
display: inline;
display: inline-block;
margin-bottom: 20px;
z-index: 1;
}
.end {
margin-right: 0 !important;
}
/*-=-=-=-=-=-=-=-=-=-=- */
/* Flip Panel */
/*-=-=-=-=-=-=-=-=-=-=- */
.wrapper {
width: 80%;
height: 200px;
margin: 0 auto;
background-color: #bdd3de;
hoverflow: hidden;
border: 1px;
}
.panel {
margin: 0 auto;
height: 130px;
position: relative;
-webkit-perspective: 600px;
-moz-perspective: 600px;
}
.panel .front {
text-align: center;
}
.panel .front {
height: inherit;
position: absolute;
top: 0;
z-index: 900;
text-align: center;
-webkit-transform: rotateX(0deg) rotateY(0deg);
-moz-transform: rotateX(0deg) rotateY(0deg);
-webkit-transform-style: preserve-3d;
-moz-transform-style: preserve-3d;
-webkit-backface-visibility: hidden;
-moz-backface-visibility: hidden;
-webkit-transition: all .4s ease-in-out;
-moz-transition: all .4s ease-in-out;
-ms-transition: all .4s ease-in-out;
-o-transition: all .4s ease-in-out;
transition: all .4s ease-in-out;
}
.panel.flip .front {
-webkit-transform: rotateY(45deg);
-moz-transform: rotateY(180deg);
}
.col-box:hover {
z-index: 1000;
}
.box1 {
background-color: #14bcc8;
width: 160px;
height: 60px;
margin-left: 5px;
padding: 20px;
border-radius: 10px;
-moz-border-radius: 10px;
-webkit-border-radius: 10px;
}
<body onload="check()">
<div id="wrapper" class="wrapper">
<div id="first" class="col-box">
<div class="hover panel">
<div id="panel" class="front">
<div class="box1">
<p>Div 1</p>
</div>
</div>
</div>
</div>
<div id="second" class="col-box">
<div class="hover panel">
<div id="panel2" class="front">
<div class="box1">
<p>Div 2</p>
</div>
</div>
</div>
</div>
<div id="third" class="col-box">
<div class="hover panel">
<div id="panel3" class="front">
<div class="box1">
<p>Div 3</p>
</div>
</div>
</div>
</div>
<div id="last" class="col-box">
<div class="hover panel">
<div id="panel4" class="front">
<div class="box1">
<p>Last Div</p>
</div>
</div>
</div>
</div>
<button onclick="addDiv()">Add New Div</button>
</div>
9 days... that's too long. Time to step back and break this up into smaller things.
This isn't an 'answer' yet... but I need to post an image for you. Your question wasn't that clear, but it's not an easy thing to explain. In your case, I would show an image.
Now that I can see what you're doing - it doesn't sound like an arbitrary and completely silly task.
You have a list of 'things' or 'cards' or whatever... so, first things first... how do you insert new DOM into the page - and / into that list - and have the list all on one line. A few ways - but most likely you can just use flexbox -
https://jsfiddle.net/sheriffderek/8eLggama -> https://jsfiddle.net/sheriffderek/pztvhn3L (this is an example - but it's pretty naive - and the further you take this, the closer you'll get to building what most frameworks - like Vue could do way better... but good for learning! Start with something small - to just do that.
// will take an object with the list name and the card id
// eventuallly - you'd want the card to have more info sent in...
function addCard(infoObject) {
var targetList = document.getElementById(infoObject.list);
var li = document.createElement('li');
li.classList.add('item');
// ug! why aren't I using jQuery...
var component = document.createElement('aside');
component.classList.add('card');
var title = document.createElement('h2');
var uniqueId = idMaker.create();
var id = document.createTextNode(uniqueId);
title.appendChild(id);
component.appendChild(title)
li.appendChild(component);
targetList.appendChild(li);
// woah... this part is really boring...
// this is why templating engines and JSON are so popular
// you could also add 'remove' button etc... right?
var removeButton = document.createElement('button');
var removeText = document.createTextNode('x');
removeButton.appendChild(removeText);
removeButton.classList.add('remove-card');
component.appendChild(removeButton);
//
removeButton.addEventListener('click', function() {
var parent = document.getElementById(infoObject.list);
idMaker.removed.push(uniqueId);
parent.removeChild(li);
idMaker.read();
});
}
// start out with a few?
addCard({list: 'exampleTarget'});
addCard({list: 'exampleTarget'});
addCard({list: 'exampleTarget'});
// start a UI to add cards
var addCardButton = document.querySelector('[data-trigger="add-card"]');
addCardButton.addEventListener('click', function() {
addCard({list: 'exampleTarget'});
});
...and then you maybe absolute position the card inside of that list item? It's certainly a unique thing to do, and wont be easy. Then, you can check the number of items - of the width of each item - and make a calculation for transform based on that? Good luck!

Javascript - Trying to Add images to slideshow with JS but it doesn't work?

Hey I'm trying to make a function that fills an empty container of a slideshow with images, with each image being contained in it's own div.
My webpage have an undetermined amount of modal images which , when clicked, open a slideshow album of images. I got this working for 1 image then realized that to have it work for an undetermined amount of slideshows of undetermined size I should make a function that fills the slideshow div. I planned to have each modal image to have a data attribute of "1,2,3...etc" and have a bunch an array with multiple objects each named similarly "1,2,3...etc" then I'd use this information to create and append the correct divs and images to the slideshow container. I will post what I want the slideshow container div to look like, my existing code, and a fiddle of what is supposed to happen. I am new to javascript and appreciate the help. I'm not certain what I've done incorrectly here, and If I haven't explained well enough then I will add more.
Edit:
I have noticed that in my modal image, if in the onClick I put fillSlides first, the other two functions won't work (or won't be called), but if I put it at the end it opens an empty slideshow. I don't get why.
https://jsfiddle.net/nhk3o0m1/26/
Current HTML:
<body >
<h2 id="title" style="text-align:center">hellkkko</h2>
<div class="row">
<div class="column">
<img id="modal-1" src="https://www.yosemitehikes.com/images/wallpaper/yosemitehikes.com-bridalveil-winter-1200x800.jpg" style="max-width:100%" data-modal="1" onclick="openModal();currentSlide(1); fillSlides(this);" class="hover-shadow cursor">
</div>
</div>
<div id="myModal" class="modal">
<span class="close cursor" onclick="closeModal()">×</span>
<div class="modal-content">
<a class="prev" onclick="plusSlides(-1)">❮</a>
<a class="next" onclick="plusSlides(1)">❯</a>
</div>
</div>
What I want my .modal-content div to look like after the function runs:
<div class="modal-content">
<div class="mySlides">
<img src="Images/LS_01.jpg" class="img">
</div>
<div class="mySlides">
<img src="Images/LS_02.jpg" class="img">
</div>
<div class="mySlides">
<img src="Images/LS_03.jpg" class="img">
</div>
<div class="mySlides">
<img src="Images/LS_04.jpg" class="img">
</div>
<a class="prev" onclick="plusSlides(-1)">❮</a>
<a class="next" onclick="plusSlides(1)">❯</a>
</div>
Javascript:
function fillSlides(modalID) {
var container = document.getElementsByClassName("modal-content");
var slides = {
"1": ["Images/LS_01.jpg", "Images/LS_02.jpg", "Images/LS_03.jpg", "Images/LS_04.jpg"],
"2": ["Images/LS_05.jpg", "Images/LS_06.jpg", "Images/LS_07.jpg", "Images/LS_08.jpg"],
"3": ["Images/LS_09.jpg", "Images/LS_10.jpg", "Images/LS_11.jpg", "Images/LS_12.jpg"]
};
var modal_num = modalID.getAttribute('data-modal');
for (var i = slides[modal_num].length; i > 0; i--) {
var the_divs = document.createElement('div');
var s_img = document.createElement('img');
the_divs.className = 'mySlides';
s_img.src = slides[modal_num][i];
the_divs.appendChild(s_img);
container.appendChild(the_divs);
}
}
<h2 id="title" style="text-align:center">hellkkko</h2>
<div class="row">
<div class="column">
<img id="modal-1" src="https://www.yosemitehikes.com/images/wallpaper/yosemitehikes.com-bridalveil-winter-1200x800.jpg" style="max-width:100%" data-modal="1" onclick="openModal();currentSlide(1); fillSlides(this);" class="hover-shadow cursor">
</div>
</div>
<div id="myModal" class="modal">
<span class="close cursor" onclick="closeModal()">×</span>
<div class="modal-content">
<a class="prev" onclick="plusSlides(-1)">❮</a>
<a class="next" onclick="plusSlides(1)">❯</a>
</div>
</div>
Added a function that generates slides on the fly. There are no slides in HTML and arrow controls are in #content. You gave no details on how album exists so I made a thumbnail for 2 extra albums. Also, there's a solution to your problem concerning the removal of everything with the arrows being the exception. The CSS is a little wonky but I'm sure you can rectify it easily enough.
Details commented in demo
Demo
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1, user-scalable=no">
<title></title>
<style>
html,
body {
height: 100%;
width: 100%
}
body {
font-family: Verdana, sans-serif;
margin: 0;
}
* {
box-sizing: border-box;
}
.img {
max-width: 100%;
max-height: 100%;
width: auto;
height: auto;
object-fit: contain;
}
.row {
display:flex;
justify-content:space-between;
}
.column {
width: 25%;
padding: 0 8px;
}
/* The Modal (background) */
.modal {
display: none;
position: fixed;
z-index: 1;
padding-top: 100px;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow-x: hidden;
overflow-y: scroll;
background: rgba(0, 0, 0, 0.9);
}
/* Modal Content */
.modal-content {
position: relative;
background-color: rgba(0, 0, 0, 0.9);
margin: auto;
padding: 0;
width: 100%;
max-width: 1200px;
}
/* The Close Button */
.close {
color: white;
position: absolute;
top: 10px;
right: 25px;
font-size: 35px;
font-weight: bold;
}
.close:hover,
.close:focus {
color: #999;
text-decoration: none;
cursor: pointer;
}
/* Next & previous buttons */
.prev,
.next {
cursor: pointer;
position: absolute;
top: 50%;
width: auto;
padding: 16px;
margin-top: -50px;
color: white;
font-weight: bold;
font-size: 20px;
transition: 0.6s ease;
border-radius: 0 3px 3px 0;
user-select: none;
-webkit-user-select: none;
}
/* Position the "next button" to the right */
.next {
right: 0;
border-radius: 3px 0 0 3px;
}
/* On hover, add a black background color with a little bit see-through */
.prev:hover,
.next:hover {
background-color: rgba(0, 0, 0, 0.8);
text-decoration: none;
}
/* Number text (1/3 etc) */
.nth {
color: #f2f2f2;
font-size: 12px;
padding: 8px 12px;
position: absolute;
right: 0;
}
img {
margin-bottom: -4px;
cursor: pointer
}
img.hover-shadow {
transition: all .2s ease-in-out;
}
.hover-shadow:hover {
transform: scale(1.1);
}
.modal-content {
-webkit-animation-name: zoom;
-webkit-animation-duration: 0.6s;
animation-name: zoom;
animation-duration: 0.6s;
}
#-webkit-keyframes zoom {
from {
-webkit-transform: scale(0)
}
to {
-webkit-transform: scale(1)
}
}
#keyframes zoom {
from {
transform: scale(0)
}
to {
transform: scale(1)
}
}
.slide img {
display: block;
height: 100%;
margin: 0 auto;
margin-bottom: 50px;
}
.slide {
text-align: center;
height: 80vh;
display: none;
}
.cap {
font-size: 1.5em;
background: rgba(0, 0, 0, .4);
position: absolute;
z-index: 2;
left: 0;
top: 0;
right: 0;
text-align: center;
color: #fff
}
.act {
display: block
}
</style>
</head>
<body>
<header>
<div class="row">
<div class="column"> <img src="https://www.yosemitehikes.com/images/wallpaper/yosemitehikes.com-bridalveil-winter-1200x800.jpg"
style="max-width:100%" onclick="album(img0, cap0);openModal();"
class="hover-shadow"> </div>
<div class="column"> <img src="https://www.yosemitehikes.com/images/wallpaper/yosemitehikes.com-bridalveil-winter-1200x800.jpg"
style="max-width:100%" onclick="album(img1, cap1);openModal();"
class="hover-shadow"> </div>
<div class="column"> <img src="https://www.yosemitehikes.com/images/wallpaper/yosemitehikes.com-bridalveil-winter-1200x800.jpg"
style="max-width:100%" onclick="album(img2, cap2);openModal();"
class="hover-shadow"> </div>
</div>
</header>
<section id="box">
<div id="xModal" class="modal"> <span class="close cursor" onclick="closeModal()">×</span>
<div class="modal-content" id='content'> <a class="prev" onclick="plusSlides(-1)">❮</a> <a class="next"
onclick="plusSlides(1)">❯</a> </div>
</div>
</section>
<footer> </footer>
<script>
/* 3 arrays are required:
|= 1. An array of strings.
|| Each represents a src of an image
|= 2. An array of strings. Each represents the
|| text of a figcaption
|= 3. An empty array
|| For each additional album add #1 and #2, #3
|| is emptied and reused at the beginning of
|| a new cycle.
*/
// Album 0
var img0 = [
"http://www.catholicevangelism.org/wp-content/uploads/2013/06/1200x800.gif",
"http://chasingseals.com/wp-content/uploads/2014/02/greenlandBanner2000x800.jpg",
"http://www.a1carpet-to.com/wp-content/uploads/2015/08/600x400.png",
"https://support.kickofflabs.com/wp-content/uploads/2016/06/800x1200.png"
];
var cap0 = ['caption1', 'caption2', 'caption3', 'caption4'];
// Album 1
var img1 = [
'https://d3i6fh83elv35t.cloudfront.net/newshour/app/uploads/2016/05/729665main_A-BlackHoleArt-pia16695_full-1024x576.jpg',
'http://cdn.newsapi.com.au/image/v1/85fb305132eb20ebbb01af386983c8a1',
'http://science.nationalgeographic.com/staticfiles/NGS/Shared/StaticFiles/Science/Images/Content/neptune-pia01492-ga.jpg',
'https://cdn.spacetelescope.org/archives/images/wallpaper1/heic1509a.jpg',
'https://i.giphy.com/media/JCUyexH8Zaf8k/giphy.webp'
];
var cap1 = ['Title I', 'Title II', 'Title III', 'Title IV',
'Title V'
];
// Album 2
var img2 = [
'https://i.ytimg.com/vi/YeQnLnRvZ9Y/maxresdefault.jpg',
'https://www.thesun.co.uk/wp-content/uploads/2017/08/nintchdbpict000319076839.jpg?strip=all&w=960',
'https://i0.wp.com/www.sketchysloth.com/wp-content/uploads/2016/07/Legendary-Hanging-Garden-Of-Babylon.jpg?fit=710%2C495&ssl=1',
'https://i.ytimg.com/vi/YoRvJcgSDE4/maxresdefault.jpg',
'https://www.realmofhistory.com/wp-content/uploads/2017/01/mausoleum-at-halicarnassus-restored_1.jpg',
'http://www.ancient-origins.net/sites/default/files/field/image/statue-of-Zeus-Olympia.jpg',
'https://i.ytimg.com/vi/F2yYkbinGnc/maxresdefault.jpg'
];
var cap2 = ['Colossus of Rhodes', 'Great Pyramid of Giza',
'Hanging Gardens of Babylon', 'Lighthouse of Alexandria',
'Mausoleum at Halicarnassus', 'Statue of Zeus at Olympia',
'Temple of Artemis at Ephesus'
];
// Declare a empty array
var data = [];
// Declare some counters outside of loop (or inside of loop using let)
var i, b, x;
// Reference the node that will contain the slides
var con = document.getElementById('content');
/* On each iteration...
|= Empty the data array
|= Create an object...
|| add a value from img[] to the src property
|| add a value from cap[] to the cap property
|| add the current value of index +1 to pos property
|| push the object into data array
*/
// Get the total length of data array
// Call genSlides()
function album(img, cap) {
data.length = 0;
for (i = 0; i < img.length; i++) {
var ele = new Object;
ele.src = img[i];
ele.cap = cap[i];
ele.pos = i + 1;
data.push(ele);
}
var qty = data.length;
genSlides(qty)
}
console.log(data);
/* Pass qty through...
|= On each iteration...
|= Create a documentFragment
|| it will allow us to append new elements to
|| it while still not in the DOM
|| which is faster because tasks within the DOM
|| are slow for the browser in comparison.
|= Notice that the data array is being used
|| to assign unique values.
*/
function genSlides(qty) {
for (b = 0; b < qty; b++) {
var frag = document.createDocumentFragment();
var slide = document.createElement('figure');
slide.id = 's' + b;
slide.className = 'slide';
var cap = document.createElement('figcaption');
cap.className = 'cap';
cap.textContent = data[b].cap;
var img = document.createElement('img');
img.classsName = 'img';
img.src = data[b].src;
var nth = document.createElement('b');
nth.className = 'nth';
nth.textContent = data[b].pos + '/' + data.length;
slide.appendChild(cap);
cap.appendChild(nth);
slide.appendChild(img);
frag.appendChild(slide);
con.appendChild(frag);
}
return false;
}
/* To avoid redundancy call sub functions within an initiating function
|| currentSlide() should start at 0, remember that all indexes by
|| default start at 0 and that the last index is .length - 1
|| showSlides() has ben corrected.
*/
function openModal() {
document.getElementById('xModal').style.display = "block";
showSlides(slideIndex);
currentSlide(0);
}
/* To remove what's in #content with the exception of the arrows we
|| gather all .slides in a NodeList and use a loop to remove them.
*/
function closeModal() {
document.getElementById('xModal').style.display = "none";
var slides = document.querySelectorAll(".slide");
for (x = 0; x < slides.length; x++) {
con.removeChild(slides[x]);
}
}
var slideIndex = 0;
function plusSlides(n) {
showSlides(slideIndex += n);
}
function currentSlide(n) {
showSlides(slideIndex = n);
}
function showSlides(n) {
var i;
var slides = document.querySelectorAll(".slide");
if (n > slides.length - 1) {
slideIndex = 0
}
if (n < 0) {
slideIndex = slides.length - 1
}
// Flipping a class is much cleaner than relying on style
for (i = 0; i < slides.length; i++) {
slides[i].classList.remove('act');
}
slides[slideIndex].classList.add('act');
}
</script>
</body>
</html>

Slideshows(Multiple) for HTML/Webpage

I am attempting to put two slideshows on the same page, both of which would be ran by the same css, and java script. My issue is that I can not seem to figure out why my second slideshow is pushing one of the images down. Notice in the photo provided that the second slideshow is pushing the image of a white circle vertically down and to the left of the page. If anyone can explain what I have done wrong, I would appreciate it and any other advice as well! Thank you
The Image of the result of my slideshows( two of them)
<script>
//1. set ul width
//2. image when click prev/next button
var ul;
var li_items;
var imageNumber;
var imageWidth;
var prev, next;
var currentPostion = 0;
var currentImage = 0;
function init(){
ul = document.getElementById('image_slider');
li_items = ul.children;
imageNumber = li_items.length;
imageWidth = li_items[0].children[0].clientWidth;
ul.style.width = parseInt(imageWidth * imageNumber) + 'px';
prev = document.getElementById("prev");
next = document.getElementById("next");
//.onclike = slide(-1) will be fired when onload;
/*
prev.onclick = function(){slide(-1);};
next.onclick = function(){slide(1);};*/
prev.onclick = function(){ onClickPrev();};
next.onclick = function(){ onClickNext();};
}
function animate(opts){
var start = new Date;
var id = setInterval(function(){
var timePassed = new Date - start;
var progress = timePassed / opts.duration;
if (progress > 1){
progress = 1;
}
var delta = opts.delta(progress);
opts.step(delta);
if (progress == 1){
clearInterval(id);
opts.callback();
}
}, opts.delay || 17);
//return id;
}
function slideTo(imageToGo){
var direction;
var numOfImageToGo = Math.abs(imageToGo - currentImage);
// slide toward left
direction = currentImage > imageToGo ? 1 : -1;
currentPostion = -1 * currentImage * imageWidth;
var opts = {
duration:1000,
delta:function(p){return p;},
step:function(delta){
ul.style.left = parseInt(currentPostion + direction * delta * imageWidth * numOfImageToGo) + 'px';
},
callback:function(){currentImage = imageToGo;}
};
animate(opts);
}
function onClickPrev(){
if (currentImage == 0){
slideTo(imageNumber - 1);
}
else{
slideTo(currentImage - 1);
}
}
function onClickNext(){
if (currentImage == imageNumber - 1){
slideTo(0);
}
else{
slideTo(currentImage + 1);
}
}
window.onload = init;
</script>
/* Silent Auction */
/* SLIDESHOW */
.container2{
width:800px;
height:400px;
padding:5px;
border:1px solid #E6E6FA;
-webkit-box-sizing:border-box;
-moz-box-sizing:border-box;
box-sizing:border-box;
background: #E6E6FA;
}
.slider_wrapper{
overflow: hidden;
position:relative;
height:500px;
top:auto;
}
#image_slider{
position: relative;
height: auto;
list-style: none;
overflow: hidden;
float: left;
/*Chrom default padding for ul is 40px */
padding:0px;
margin:0px;
}
#image_slider li{
position: relative;
float: left;
}
.nvgt{
position:absolute;
top: 120px;
height: 50px;
width: 30px;
opacity: 0.6;
}
.nvgt:hover{
opacity: 0.9;
}
#prev{
background: #000 url('https://dl.dropboxusercontent.com/u/65639888/image/prev.png') no-repeat center;
left: 0px;
}
#next{
background: #000 url('https://dl.dropboxusercontent.com/u/65639888/image/next.png') no-repeat center;
right: 0px;
}
h1.slideshowtitle{
font-style: italic;
font-size: 50px;
font-family: cursive;
color: black;
<h1> Silent Auction </h1>
<!-First Slideshow->
<div class="container2">
<div class="slider_wrapper">
<ul id="image_slider">
<li><img src=""></li>
<li><img src=""></li>
<li><img src=""></li>
</ul>
<span class="nvgt" id="prev"></span>
<span class="nvgt" id="next"></span>
</div>
</div>
<!-Second slide show ->
<div class="container2">
<div class="slider_wrapper">
<ul id="image_slider">
<li><img src=""></li>
<li><img src=""></li>
<li><img src=""></li>
</ul>
<span class="nvgt" id="prev"></span>
<span class="nvgt" id="next"></span>
</div>
</div>
Ids should be unique within the document, but you are styling w/ id selectors and multiple elements with the same id. Switch to classes. E.g. -
Use
class="image_slider"
and
.image_slider { <yourcss> }

Javascript issue inside HTML (popup gallery)

In the code below, when I click on one of the two images it opens a gallery, and if I click on the other one it should open a different gallery. It works, but not as I expected because as you can see on the snippet there are some empty slides in each gallery. Can you help me solve this problem? Thank you!
// Get the image and insert it inside the modal
function imgg(id){
var modal = document.getElementById(id);
var modalImg = document.getElementById('mySlides');
modal.style.display = "block";
modalImg.src = this.src;
}
// When the user clicks on <span> (x), close the modal
function clos(id) {
var modal = document.getElementById(id);
modal.style.display = "none";
}
// Sliseshow
var slideIndex = 1;
showDivs(slideIndex);
function plusDivs(n) {
showDivs(slideIndex += n);
}
function showDivs(n) {
var i;
var x = document.getElementsByClassName("mySlides");
if (n > x.length) {slideIndex = 1}
if (n < 1) {slideIndex = x.length} ;
for (i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
x[slideIndex-1].style.display = "block";
}
#myImg {
border-radius: 5px;
cursor: pointer;
transition: 0.3s;
}
#myImg:hover {opacity: 0.7;}
/* The Modal (background) */
.modal {
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
padding-top: 100px; /* Location of the box */
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
overflow: auto; /* Enable scroll if needed */
background-color: rgb(0,0,0); /* Fallback color */
background-color: rgba(0,0,0,0.9); /* Black w/ opacity */
}
/* Modal Content (image) */
.mySlides {
margin: auto;
display: block;
width: 80%;
max-width: 700px;
box-shadow: 0px 0px 50px -6px #000;
}
#-webkit-keyframes zoom {
from {-webkit-transform:scale(0)}
to {-webkit-transform:scale(1)}
}
#keyframes zoom {
from {transform:scale(0)}
to {transform:scale(1)}
}
/* The Close Button */
.close {
position: absolute;
top: 15px;
right: 100px;
color: #f1f1f1;
font-size: 40px;
font-weight: bold;
transition: 0.3s;
}
.close:hover,
.close:focus {
color: #bbb;
text-decoration: none;
cursor: pointer;
}
/* 100% Image Width on Smaller Screens */
#media only screen and (max-width: 700px){
.mySlides {
width: 100%;
}
}
.w3-btn-floating {
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="test.css" rel="stylesheet" type="text/css">
<link rel="stylesheet" href="http://www.w3schools.com/lib/w3.css">
</head>
<body>
<img id="myImg" onClick="imgg('myModal')" src="http://www.gettyimages.pt/gi-resources/images/Homepage/Hero/PT/PT_hero_42_153645159.jpg" alt="" width="300" height="200">
<img id="myImg" onClick="imgg('myModal1')"src="http://cue.me/kohana/media/frontend/js/full-page-scroll/examples/imgs/bg2.jpg" alt="" width="300" height="200">
<!-- The Modal -->
<div id="myModal" class="modal">
<span onclick="clos('myModal')" class="close">×</span>
<img class="mySlides" id="img_modal" src="http://cue.me/kohana/media/frontend/js/full-page-scroll/examples/imgs/bg2.jpg" >
<img class="mySlides" id="img_modal" src="http://cdn.theatlantic.com/assets/media/img/photo/2015/11/images-from-the-2016-sony-world-pho/s01_130921474920553591/main_900.jpg" >
<a class="w3-btn-floating" style="position:absolute;top:45%;left:280px;" onclick="plusDivs(-1)">❮</a>
<a class="w3-btn-floating" style="position:absolute;top:45%;right:280px;" onclick="plusDivs(1)">❯</a>
</div>
<div id="myModal1" class="modal">
<span onclick="clos('myModal1')" class="close">×</span>
<img class="mySlides" id="img_modal" src="http://www.gettyimages.pt/gi-resources/images/Homepage/Hero/PT/PT_hero_42_153645159.jpg" >
<img class="mySlides" id="img_modal" src="http://i.dailymail.co.uk/i/pix/2016/03/22/13/32738A6E00000578-3504412-image-a-6_1458654517341.jpg" >
<a class="w3-btn-floating" style="position:absolute;top:45%;left:280px;" onclick="plusDivs(-1)">❮</a>
<a class="w3-btn-floating" style="position:absolute;top:45%;right:280px;" onclick="plusDivs(1)">❯</a>
</div>
</body>
</html>
I'm not 100% sure, but this line
var x = document.getElementsByClassName("mySlides");
should return 4 items. That would explain why you are getting 2 empty slides in your slider. Try filtering first by id (e.g. "myModal" or "myModal1") and afterwards get the number of the contained "mySlides"-classes.
so you can do it like this:
var activeModalId = "";
// Get the image and insert it inside the modal
function imgg(id){
activeModalId = id;
var modal = document.getElementById(activeModalId);
var modalImg = modal.getElementsByClassName('mySlides');
modal.style.display = "block";
showDivs(0);
}
// When the user clicks on <span> (x), close the modal
function clos() {
var modal = document.getElementById(activeModalId);
modal.style.display = "none";
activeModalId = "";
}
// Sliseshow
var slideIndex = 1;
showDivs(slideIndex);
function plusDivs(n) {
showDivs(slideIndex += n);
}
function showDivs(n) {
var i;
var x = document.getElementById(activeModalId).getElementsByClassName("mySlides");
if (n > x.length) {slideIndex = 1;}
if (n < 1) {slideIndex = x.length;}
for (i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
x[slideIndex-1].style.display = "block";
}
On top, you declare your active modal. It will be set, reused, and removed by your functions.
From what I can see there are some url typos.
For example: you have ihttp where it should be http.
In the mouse one there's an unnecessary url termination after .jpg: ?1448476701
you need to pass "this" into function like
onClick="imgg('myModal',this)"
now in function get it
function imgg(id,this){
var modal = document.getElementById(id);
var modalImg = document.getElementById('mySlides');
modal.style.display = "block";
modalImg.src = this.src;}

Categories

Resources