JS and JQuery script conflicts - javascript

I am experiencing issues when implementing two sets of code for two functions on a webpage I am designing. I am rather new to JS and JQuery, but none of the similar threads lead to a solution.
On my webpage I have a series of 100vh slideshows (code below) as well as one fullpage "welcome"screen above them. To transition between them, I am using a package that offers block scrolling.
Here is my code:
// Slideshow code, help from w3schools
var slideIndex = 1;
showDivs(slideIndex, show);
function plusDivs(n, show) {
showDivs(slideIndex += n, show);
}
function showDivs(n, show) {
var i;
var x = document.getElementsByClassName("mySlides"+show);
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 = "inline";
}
// blockScroller code from the docs on the linked package.
$(function() {
var blockScroller = $("#main-wrap").blockScroll();
});
I can, depending on which block of code is physically higher up in the script, get one of them to work at a time. However, when the block scrolling works, the slideshow breaks and none of that javascript has any effect on the page. This should tell you that for the sake of each individual scripts, all HTML and CSS requirements are met.
Any help to resolve this conflict would be great, and since this is my first question on stackoverflow if I butchered anything about location or related just tell me. If there is any more information I can provide I will gladly do so.
Here is a sampler of what I am talking about:
<!DOCTYPE html>
<html>
<head>
<!--style>
.slideshow{
z-index: 500;
position: relative;
height: 100vh;
width: 100%;
margin:auto;
overflow: hidden;
}
.slideshow > p{
position: absolute;
color: white;
background-color: black;
padding: 5px;
font-size: 24px;
margin: 0;
}
.mySlides1,.mySlides2{
width: 100%;
height: 100vh;
overflow: hidden;
object-fit: cover;
object-position: center center;
}
.slides_button{
position: absolute;
display: inline-block;
border: none;
padding:8px 16px;
cursor: pointer;
background-color: white;
}
.slides_button:hover{
background-color: black;
color: white;
}
.display_left{
position: absolute;
bottom: 50%;
left: 0%;
}
.display_right{
position: absolute;
bottom: 50%;
right: 0;
}
</style-->
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="SCRIPT HERE"></script> <script>
$(function () {
var blockScroller = $("#main-wrap").blockScroll();
$(function () {
function showDivs(n, show) {
var i;
var x = document.getElementsByClassName("mySlides"+show);
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";
console.log(x[slideIndex-1])
};
var slideIndex = 1;
showDivs(2, 1);
showDivs(2, 2);
$(function () {
function plusDivs(n, show) {
showDivs(slideIndex += n, show);
};
})
});
});
</script>
<div id="main-wrap">
<div style="height:100vh;background-image:url(https://www.planwallpaper.com/static/images/518164-backgrounds.jpg)">
</div>
<div class="slideshow">
<p>slideshow 1</p>
<img class="mySlides1" src="https://cdn.pixabay.com/photo/2015/10/31/00/43/background-texture-1014963_960_720.jpg">
<button class="slides_button display_left" onclick="plusDivs(-1,1)">❮</button>
<button class="slides_button display_right" onclick="plusDivs(1,1)">❯</button>
<img class="mySlides1" src="https://image.freepik.com/free-vector/orange-geometric-background-with-halftone-dots_1035-7243.jpg">
<img class="mySlides1" src="https://cdn.pixabay.com/photo/2015/10/31/00/43/background-texture-1014963_960_720.jpg">
<img class="mySlides1" src="https://image.freepik.com/free-vector/orange-geometric-background-with-halftone-dots_1035-7243.jpg">
</div>
<div class="slideshow">
<p>slideshow 2</p>
<img class="mySlides2" src="https://image.freepik.com/free-psd/abstract-background-design_1297-87.jpg">
<button class="slides_button display_left" onclick="plusDivs(-1,2)">❮</button>
<button class="slides_button display_right" onclick="plusDivs(1,2)">❯</button>
<img class="mySlides2" src="http://images.all-free-download.com/images/graphiclarge/flower_pink_background_vector_art_148632.jpg">
<img class="mySlides2" src="http://images.all-free-download.com/images/graphiclarge/clouds_in_sky_background_192377.jpg">
</div>
</div>
</body>
</html>
blockerScoll js script

not work because show in showDivs(slideIndex, show); is undefined, it should be like this
showDivs(slideIndex, 1);
showDivs(slideIndex, 2);
demo
//This is only for the block scrolling. If you move this
//ABOVE the previous section, then it will take over.
$(function() {
var blockScroller = $("#main-wrap").blockScroll();
});
//This is the slideshow section. Move this above the block scroll
//and this works.
function showDivs(n, show) {
var i;
var x = document.getElementsByClassName("mySlides" + show);
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 = "inline";
//console.log(x[slideIndex - 1])
}
var slideIndex = 1;
showDivs(slideIndex, 1);
showDivs(slideIndex, 2);
function plusDivs(n, show) {
showDivs(slideIndex += n, show);
}
.slideshow {
z-index: 500;
position: relative;
height: 100vh;
width: 100%;
margin: auto;
overflow: hidden;
}
.slideshow>p {
position: absolute;
color: white;
background-color: black;
padding: 5px;
font-size: 24px;
margin: 0;
}
.mySlides1,
.mySlides2 {
width: 100%;
height: 100vh;
overflow: hidden;
object-fit: cover;
object-position: center center;
}
.slides_button {
position: absolute;
display: inline-block;
border: none;
padding: 8px 16px;
cursor: pointer;
background-color: white;
}
.slides_button:hover {
background-color: black;
color: white;
}
.display_left {
position: absolute;
bottom: 50%;
left: 0%;
}
.display_right {
position: absolute;
bottom: 50%;
right: 0;
}
<link rel="stylesheet" type="text/css" href="//www.dominikgorecki.com/p/block-scroll/blockScroll.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="//www.dominikgorecki.com/p/block-scroll/js/blockScroll.js"></script>
<div id="main-wrap">
<div style="height:100vh;background-image:url(https://www.planwallpaper.com/static/images/518164-backgrounds.jpg)">
</div>
<div class="slideshow">
<p>slideshow 1</p>
<img class="mySlides1" src="https://cdn.pixabay.com/photo/2015/10/31/00/43/background-texture-1014963_960_720.jpg">
<button class="slides_button display_left" onclick="plusDivs(-1,1)">❮</button>
<button class="slides_button display_right" onclick="plusDivs(1,1)">❯</button>
<img class="mySlides1" src="https://image.freepik.com/free-vector/orange-geometric-background-with-halftone-dots_1035-7243.jpg">
<img class="mySlides1" src="https://cdn.pixabay.com/photo/2015/10/31/00/43/background-texture-1014963_960_720.jpg">
<img class="mySlides1" src="https://image.freepik.com/free-vector/orange-geometric-background-with-halftone-dots_1035-7243.jpg">
</div>
<div class="slideshow">
<p>slideshow 2</p>
<img class="mySlides2" src="https://image.freepik.com/free-psd/abstract-background-design_1297-87.jpg">
<button class="slides_button display_left" onclick="plusDivs(-1,2)">❮</button>
<button class="slides_button display_right" onclick="plusDivs(1,2)">❯</button>
<img class="mySlides2" src="http://images.all-free-download.com/images/graphiclarge/flower_pink_background_vector_art_148632.jpg">
<img class="mySlides2" src="http://images.all-free-download.com/images/graphiclarge/clouds_in_sky_background_192377.jpg">
</div>
</div>

Related

Adjust modal size to div shape

I'm working on my website and I'd like to create a slideshow. Hence, I have created the modal to expand the image after click - it works fine. However, I want to adjust the modal shape to the image size(thus the vertical photos look ugly in standard shape), but after many hours I gave up because I didn't find any satisfactory result.
HTML:
<div id="myModal" class="modal-wraper">
<span class="close cursor" onclick="closeModal()">×</span>
<div class="modal">
<div class="mySlides">
<div class="slide_1"></div>
</div>
<div class="mySlides">
<div class="slide_2"></div>
</div>
<div class="mySlides">
<div class="slide_3"></div>
</div>
</div>
CSS:
.modal-wraper {
position: fixed;
display: none;
top:0;
left: 0;
width: 100vw;
height: 100vh;
background-color: #000;
z-index: 1;
}
.modal {
position: absolute;
display: flex;
flex-direction: column;
height: 85vh;
width: 85vw;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
border: solid 5px red;
}
.mySlides {
display: flex;
background-color: blue;
flex-basis: 100%;
}
.slide_1 {
width: 100%;
height: 100%;
background-image: url('../images/JF_3.jpg');
background-size:contain;
background-repeat: no-repeat;
object-fit: cover;
}
.slide_2 {
width: 100%;
height: 100%;
background-image: url('../images/JF_5.jpg');
background-size:cover;
}
JS
function openModal(n) {
document.getElementById("myModal").style.display = "block";
showSlides(n);
}
function closeModal() {
document.getElementById("myModal").style.display = "none";
}
var slideIndex = 0;
function changeSlides(n) {
showSlides(slideIndex += n);
}
function showSlides(n) {
var i;
var modal = document.getElementsByClassName('modal');
var slides = document.getElementsByClassName("mySlides");
var dots = document.getElementsByClassName("dot");
if (n < 0) {
slideIndex = slides.length-1;
} else if (n >= slides.length) {
slideIndex = 0
} else {
slideIndex = n;
}
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].style.display = "block";
dots[slideIndex].className += " active";
captionText.innerHTML = dots[slideIndex].alt;
}

My function for displayin the images in a carousel has an extra blank image

//get the object
let slideshowContainer = document.getElementById('slideshow-container');
//get the buttons
let next = document.querySelector('.next');
let prev = document.querySelector('.prev');
//create an index
var slideIndex = 0;
function showSlides(n) {
const slides = document.getElementsByClassName('product');
for (var i = 0; i < slides.length; i++) {
slides[i].style.display = 'none';
}
if (n < 0) {
slideIndex = slides.length
}
if (n > slides.length) {
slideIndex = 0
}
slides[slideIndex].style.display = 'block';
slideIndex = n;
}
function incrementSlides(n) {
showSlides(slideIndex += n)
}
//add event listeners
next.addEventListener('click', function () {
incrementSlides(1);
})
prev.addEventListener('click', function () {
incrementSlides(-1);
})
showSlides(slideIndex);
#section-one .categories {
height: 80px;
background: rgba(0, 0, 0, 0.9);
display: -webkit-box;
display: -ms-flexbox;
display: flex;
}
#section-one .categories li {
background: -webkit-gradient(linear, left top, right top, from(#0d0d0d), to(#202020));
background: linear-gradient(to right, #0d0d0d, #202020);
height: inherit;
width: 12.5%;
border-left: 1px solid black;
-webkit-transition: all ease-in 0.3s;
transition: all ease-in 0.3s;
}
#section-one .categories li:hover {
background: green;
}
#section-one .categories li a {
display: inline-block;
font-size: 0.95rem;
height: inherit;
width: 100%;
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
-webkit-box-pack: center;
-ms-flex-pack: center;
justify-content: center;
}
#section-one .slideshow-container {
height: 1000px;
margin: auto;
position: relative;
background: grey;
}
#section-one .slideshow-container .prev,
#section-one .slideshow-container .next {
top: 50%;
background: blue;
font-size: 18px;
border-radius: 0 3px 3px 0;
width: auto;
position: absolute;
padding: 16px;
}
#section-one .slideshow-container .next {
right: 0;
border-radius: 3px 0 0 3px;
}
#section-one .slideshow-container .prev:hover,
#section-one .slideshow-container .next:hover {
background-color: rgba(0, 0, 0, 0.8);
}
<!-- Section-one -->
<section id="section-one">
<ul class="categories">
<li>HEADPHONES</li>
<li>EARPHONES</li>
<li>BLUETOOTH</li>
<li>WATERPROOF</li>
<li>SPORTS</li>
<li>METALLIC</li>
<li>WOODEN/BAMBOO</li>
<li>EARMUFF</li>
</ul>
<div id="slideshow-container">
<div class="product">
<p class="description"></p>
<div class="img">
<img
src="https://i.pinimg.com/originals/5a/e5/8f/5ae58f5036997cfd4636917403c3c951.jpg"
alt="image1"
style="width:100%"
/>
</div>
WIEW MORE
</div>
<div class="product">
<p class="description"></p>
<div class="img">
<img
src="https://images.unsplash.com/photo-1500382017468-9049fed747ef?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&w=1000&q=80"
alt="image2"
style="width:100%"
/>
</div>
WIEW MORE
</div>
<div class="product">
<p class="description"></p>
<div class="img">
<img
src="https://cdn.pixabay.com/photo/2017/02/22/20/02/landscape-2090495_960_720.jpg"
alt="image3"
style="width:100%"
/>
</div>
WIEW MORE
</div>
</div>
</section>
I'm trying to build a page with an image slider.
I watched some youtube videos, I combined the code and tried to make something to work but I came across an error. When I change for next or prev image I get a blank page and I don't know why.
I will create a code snippet to show you. I do not want just the problem to be solved but also the explanation, please!
Cheers!!!
You need to change your 2 " if " statements , since they dont consider the 0-based index on the array :
if (n < 0) {
slideIndex = slides.length - 1
}
if (n > slides.length - 1) {
slideIndex = 0
}
Here's the working jsFiddle with a few fix on your code:
https://jsfiddle.net/0mrpbv6c/
Basically,
I added some text to your a links to be able to click on them
PREV
NEXT
I fixed your 2 if conditions inshowSlides to continue the carousel as expected. Here you forgot the - 1, as your slides start from 0
if (n < 0) {
slideIndex = slides.length - 1;
}
if (n > slides.length - 1) {
slideIndex = 0;
}
I removed the following instruction, as you don't want to update slideIndex from n because it's already being updated when calling showSlides in incrementSlides, and also it overwrites the value you possibly got from the 2 if.
slideIndex = n;
I have tried fix your code.
function showSlides(n) {
console.log(n)
const slides = document.getElementsByClassName('product');
for (var i = 0; i < slides.length; i++) {
slides[i].style.display = 'none';
}
slideIndex = n; // edited
if (n < 0) {
slideIndex = slides.length
}
if (n >= slides.length) { // edited
slideIndex = 0
}
slides[slideIndex].style.display = 'block';
}

Basic manual image slideshow JavaScript code is making all images invisible and throwing error

I am trying to implement a simple image slider by drawing on info from several sources. The CSS and HTML seem to be set up fine but when I add in the JavaScript logic all images disappear. The console shows an error of "Uncaught TypeError: Cannot read property 'style' of undefined" which would suggest that the array of elements containing the images is empty. I console log this array in a line before the one throwing the error and get three images as expected.
Also, I am using Web Maker so using "onclick" is not an option. Any suggestions? I know this is basic stuff but I'm just not seeing the issue. (code below)
HTML
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<style>
</style>
</head>
<body>
<div id="myslider">
<img class="slide" src="http://chromethemer.com/wallpapers/chromebook-wallpapers/download/work-space-3840x2160.jpg">
<img class="slide" src="http://lindstrominsuranceagency.com/wp-content/uploads/2015/10/business.jpeg">
<img class="slide" src="http://www.nomisconnections.co.uk/wp-content/uploads/2016/10/image-1377543510.jpg">
<button id="left-button"><i class="fa fa-chevron-left"></i></button>
<button id="right-button"><i class="fa fa-chevron-right"></i></button>
</div>
</body>
</html>
CSS
#myslider {
position: relative;
height: 360px;
width: 700px;
}
.slide {
height: 100%;
width: 100%;
position: absolute;
/* opacity: 0; */
transition: 1s;
}
button {
position: absolute;
z-index: 1;
top: 50%;
background: rgba(0,0,0,0.8);
border: none;
padding: 10px;
color: #fff;
cursor: pointer;
}
button:nth-of-type(2) {
right: 0;
}
JavaScript
document.getElementById("left-button").addEventListener("click", plusDivs(-1));
document.getElementById("right-button").addEventListener("click", plusDivs(1));
var slideIndex = 1;
showDivs(slideIndex);
function plusDivs(n) {
console.log("inside of plusDiv(n)");
showDivs(slideIndex += n);
}
function showDivs(n) {
var i;
var x = document.getElementsByClassName("slide");
console.log(x);
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";
}
You inserted your callback functions in the addEventListener methods in an invalid way. If you want to pass parameters in the function you should invoke the function inside an anonymous function.
You can:
Insert the function-object if you do not need to use function parameters.
function someFunction(){
...
}
elem.addEventListener('click', someFunction);
Insert an anonymous function
elem.addEventListener('click', function(){
...
});
Insert a function with a parameter in an anonymous function
function someFunction(parameter){
...
}
elem.addEventListener('click', function(){
someFunction(parameter);
});
I recommend read up in the MDN docs: https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener
PS: You really do NOT want to call your variables x, n and i. Use something more descriptive.
Your code with updated addEventListener methods
document.getElementById("left-button").addEventListener("click", () => {plusDivs(-1)});
document.getElementById("right-button").addEventListener("click", () => {plusDivs(1)});
var slideIndex = 1;
showDivs(slideIndex);
function plusDivs(n) {
showDivs(slideIndex += n);
}
function showDivs(n) {
var i;
var x = document.getElementsByClassName("slide");
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";
}
#myslider {
position: relative;
height: 360px;
width: 700px;
}
.slide {
height: 100%;
width: 100%;
position: absolute;
/* opacity: 0; */
transition: 1s;
}
button {
position: absolute;
z-index: 1;
top: 50%;
background: rgba(0,0,0,0.8);
border: none;
padding: 10px;
color: #fff;
cursor: pointer;
}
button:nth-of-type(2) {
right: 0;
}
<div id="myslider">
<img class="slide" src="http://chromethemer.com/wallpapers/chromebook-wallpapers/download/work-space-3840x2160.jpg">
<img class="slide" src="http://lindstrominsuranceagency.com/wp-content/uploads/2015/10/business.jpeg">
<img class="slide" src="http://www.nomisconnections.co.uk/wp-content/uploads/2016/10/image-1377543510.jpg">
<button id="left-button"><i class="fa fa-chevron-left"></i></button>
<button id="right-button"><i class="fa fa-chevron-right"></i></button>
</div>

How to make a slider with jquery using bullets

Hello I want to know how to make a slider with jquery, I'm quite new with this I will try my best to be specific, I want to do this:
I have an slider with 3 images "they are on the same space" and 3 bullets below the images, first I can't see the images because they have opacity: 0 but if I click the first bullet I will see the first image, bullet# 2 img# 2, bullet# 3 img# 3, I want to put an <a> tag for example avanzar that for advance to next image "it will be on the right side" and the left side will be to back to the last image that you saw, my question is how can I do that? I will need to keep the transition of them and how to join that to the bullets? because I need to use the tag <a> <-- the button "for me" or the bullets, it's difficult and I'm trying to do it, any help is welcome
Here is my html:
<!DOCTYPE html>
<html>
<head>
<title>Slider</title>
<meta charset="utf-8" />
<link rel="stylesheet" href="style.css">
<script src="js/jquery-2.1.4.min.js"></script>
<script src="js/slider.js"></script>
</head>
<body>
<div class="sliders">
back
next
<ul >
<li><img src="image_1.jpg"></li>
<li><img src="image_2.jpg"></li>
<li><img src="image_3.jpg"></li>
</ul>
<!-- <ul class="controles">
<li class="activa">&nbsp</li>
<li>&nbsp</li>
<li>&nbsp</li>
</ul> -->
</div>
<div class="sliders">
back
next
<ul>
<li><img src="image_1.jpg"></li>
<li><img src="image_2.jpg"></li>
<li><img src="image_3.jpg"></li>
</ul>
</div>
</body>
</html>
Here is the js:
$.fn.slider = function(config){
var nodos = this;
var delay = (typeof config.delay == "number")?parseInt(config.delay):4000;
for (var i = 0; i < nodos.length; i++) {
Slider(nodos[i]);
}
function Slider(nodo){
var galeria = $(nodo).find('ul');
if(!$(nodo).hasClass('slider'))
$(nodo).addClass('slider');
if(!galeria.hasClass('galeria'))
galeria.addClass("galeria");
//Encontrar cuantas imagenes hay en la galeria
var imagenes = $(galeria).find('li');
//Controles
var html_bullets="<ul class='controles'>";
for (var it = 0; it < imagenes.length; it++) {
html_bullets+="<li data-index='"+it+"'> </li>";
}
html_bullets+="</ul>";
$(nodo).append(html_bullets);
var bullets = $(nodo).find("ul.controles li");
bullets.click(function(){
var index= $(this).data("index");
bullets.removeClass('activa');
$(imagenes[index]).addClass("activa");
$(bullets[index]).addClass("activa");
});
}
};
$(document).ready(function() {
$(".sliders").slider({delay:5000});
});
Here is the css:
.slider{
width: 320px;
overflow: hidden;
}
.slider ul{
list-style: none;
padding: 0;
}
.slider ul.galeria{
height: 200px;
position: relative;
}
.slider ul.galeria li{
position: absolute;
top: 0;
left: 0;
opacity: 0;
transition: all 2s;
}
.slider ul.galeria li.activa{
opacity: 1;
}
.slider ul.galeria img{
max-height: 200px;
}
/*Controles*/
.slider ul.controles {
text-align: center;
}
.slider ul.controles li{
background-color: black ;
display: inline-block;
width: 20px;
height: 20px;
border-radius: 10px;
}
Here is what I wanted I already finished it, I'm glad if it helps someone
html:
<!DOCTYPE html>
<html>
<head>
<title>Practica2Jquery</title>
<meta charset="utf-8" />
<link rel="stylesheet" href="style.css">
<script src="jquery.js"></script>
<script src="slider.js"></script>
</head>
<body>
<div class="sliders">
Atras
<ul >
<li class="activa"><img src="image1.jpg"></li>
<li><img src="image2.jpg"></li>
<li><img src="image3.jpg"></li>
</ul>
Siguiente
</div>
<div class="sliders">
Atras
<ul>
<li class="activa"><img src="image4.jpg"></li>
<li><img src="image5.jpg"></li>
<li><img src="image6.jpg"></li>
</ul>
Siguiente
</div>
</body>
</html>
js:
$.fn.slider = function(config){
var nodos = this;
var delay = (typeof config.delay === "number")?parseInt(config.delay):3000;
for (var i = 0; i < nodos.length; i++) {
Slider(nodos[i]);
}
function Slider(nodo){
var galeria = $(nodo).find('ul');
var tag = "<a class='atras'></a>";
if(!$(nodo).hasClass('slider'))
$(nodo).addClass('slider');
if(!galeria.hasClass('galeria'))
galeria.addClass("galeria");
//Encontrar cuantas imagenes hay en la galeria
var imagenes = $(galeria).find('li');
//Controles
var html_bullets="<ul class='controles'>";
for (var it = 0; it < imagenes.length; it++) {
if(it==0)
html_bullets+="<li data-index='"+it+"' class='activa'> </li>";
else
html_bullets+="<li data-index='"+it+"'> </li>";
}
html_bullets+="</ul><a class='siguiente'></a>";
$(nodo).append(html_bullets);
$(nodo).prepend(tag);
var bullets = $(nodo).find("ul.controles li");
bullets.click(function(){
var index= $(this).data("index");
$(imagenes).add(bullets).removeClass('activa');
$(imagenes[index]).add(bullets[index]).addClass('activa');
});
}
$(".slider").on("click","a.atras",function(){
direcciones({div: this.parentElement});
});
$(".slider").on("click","a.siguiente",function(){
direcciones({div: this.parentElement,direccion:1});
});
function direcciones(lado){
var div = lado.div;
var imagen = $(div).find("ul.galeria li.activa");
var imagenes = $(div).find("ul.galeria li");
var bullet = $(div).find("ul.controles li.activa");
var bullets = $(div).find("ul.controles li");
var index = bullet.data("index");
var max = bullets.length-1;
$(bullets).add(imagenes).removeClass('activa');
if(lado.direccion){
// === ?
if(index == max){
$(imagenes[0]).add(bullets[0]).addClass('activa');
}else {
$(imagenes[index+1]).add(bullets[index+1]).addClass('activa');
}
}
else{
if(index == 0){
$(imagenes[max]).add(bullets[max]).addClass('activa');
}else {
$(imagenes[index-1]).add(bullets[index-1]).addClass('activa');
} } } };
$(document).ready(function() {
$(".sliders").slider({delay:3000});
});
css:
.slider{
width: 420px;
overflow: hidden;
}
.slider ul{
list-style: none;
padding: 0;
}
.slider ul.galeria{
height: 200px;
position: relative;
margin-left: 30px;
}
.slider ul.galeria li{
position: absolute;
top: 0;
left: 0;
opacity: 0;
transition: all 2s;
}
.slider ul.galeria li.activa{
opacity: 1;
}
.slider ul.galeria img{
max-height: 400px;
max-width: 300px;
margin-left: 5px;
}
/*Controles*/
.slider ul.controles {
position: relative;
left: 38%;
bottom: 45px;
}
.slider ul.controles li{
background-color: black ;
display: inline-block;
width: 20px;
height: 20px;
border-radius: 10px;
}
.slider ul.controles li.activa{
background-color: red ;
}
.slider a.atras{
position: relative;
left: 0;
top: 128px;
}
.slider a.siguiente{
position: relative;
left: 80%;
bottom: 120px;
}

onClick javascript function shows only first child of wrapper

I am learning javascript these days and I have a little problem with my code.
I have three elements on page wrapper1, wrapper2 and wrapper3 and every of these has its triggerand redbox element.
My goal is when the trigger is hit, it will show the redbox element corresponding to number.
Examples:
clicking trigger1 inside wrapper1 element shows up redbox1 element,
trigger2 inside wrapper2 element shows up redbox2 element etc.
The problem is, when I click on trigger3 for example it always shows redbox1 element. (as example shows).
What I am doing wrong? I am just a begginer.
function showTheRedBox() {
var theRedBox = document.getElementsByClassName('redbox');
theRedBox[0].style.display = 'block';
}
body {background: #222;}
.wrapper {
background: yellow;
width: 100px;
height: 100px;
}
.trigger {
background: blue;
width: 50px;
height: 50px;
position: absolute;
margin-top: 50px;
margin-left: 50px;
}
.redbox {
background: red;
width: 200px;
height: 100px;
margin-left: 100px;
position: absolute;
display: none;
}
<div class="wrapper">
<div class="trigger" onclick="showTheRedBox();">trigger1</div>
<div class="redbox">hurrah1</div>
wrapper1</div>
<div class="wrapper">
<div class="trigger" onclick="showTheRedBox();">trigger2</div>
<div class="redbox">hurrah2</div>
wrapper2</div>
<div class="wrapper">
<div class="trigger" onclick="showTheRedBox();">trigger3</div>
<div class="redbox">hurrah3</div>
wrapper3</div>
You can use a for loop and a closure to access the .wrapper information for each onclick event. This method will work whether there are the same amount of children or not, and will always show the correct child.
Also, it is best to not use inline JavaScript attributes (e.g. onclick="showTheRedBox();") you should always assign your event handlers in your script for readability and maintainability.
var wrappers = document.querySelectorAll('.wrapper'), i;
var redboxes = document.querySelectorAll('.redbox');
for(i = wrappers.length - 1; i >= 0; --i) {
(function(wrapper){
wrapper.querySelector('.trigger').onclick = function() {
hideAll();
wrapper.querySelector('.redbox').style.display = 'block';
}
})(wrappers[i]);
}
function hideAll() {
for(i = redboxes.length - 1; i >= 0; --i) {
redboxes[i].style.display = 'none';
}
}
var wrappers = document.querySelectorAll('.wrapper'), i;
var redboxes = document.querySelectorAll('.redbox');
for(i = wrappers.length - 1; i >= 0; --i) {
(function(wrapper){
wrapper.querySelector('.trigger').onclick = function() {
hideAll();
wrapper.querySelector('.redbox').style.display = 'block';
}
})(wrappers[i]);
}
function hideAll() {
for(i = redboxes.length - 1; i >= 0; --i) {
redboxes[i].style.display = 'none';
}
}
body {background: #222;}
.wrapper {
background: yellow;
width: 100px;
height: 100px;
}
.trigger {
background: blue;
width: 50px;
height: 50px;
position: absolute;
margin-top: 50px;
margin-left: 50px;
}
.redbox {
background: red;
width: 200px;
height: 100px;
margin-left: 100px;
position: absolute;
display: none;
}
<div class="wrapper">
<div class="trigger">trigger1</div>
<div class="redbox">hurrah1</div>
wrapper1</div>
<div class="wrapper">
<div class="trigger">trigger2</div>
<div class="redbox">hurrah2</div>
wrapper2</div>
<div class="wrapper">
<div class="trigger">trigger3</div>
<div class="redbox">hurrah3</div>
wrapper3</div>
This method will also work, but it will use more memory as it queries the DOM once more than the above solution.
var wrappers = document.querySelectorAll('.wrapper'), i;
var redboxes = document.querySelectorAll('.redbox');
for(i = wrappers.length - 1; i >= 0; --i) {
wrappers[i].querySelector('.trigger').onclick = function() {
hideAll();
this.parentNode.querySelector('.redbox').style.display = 'block';
}
}
function hideAll() {
for(i = redboxes.length - 1; i >= 0; --i) {
redboxes[i].style.display = 'none';
}
}
var wrappers = document.querySelectorAll('.wrapper'), i;
var redboxes = document.querySelectorAll('.redbox');
for(i = wrappers.length - 1; i >= 0; --i) {
wrappers[i].querySelector('.trigger').onclick = function() {
hideAll();
this.parentNode.querySelector('.redbox').style.display = 'block';
}
}
function hideAll() {
for(i = redboxes.length - 1; i >= 0; --i) {
redboxes[i].style.display = 'none';
}
}
body {background: #222;}
.wrapper {
background: yellow;
width: 100px;
height: 100px;
}
.trigger {
background: blue;
width: 50px;
height: 50px;
position: absolute;
margin-top: 50px;
margin-left: 50px;
}
.redbox {
background: red;
width: 200px;
height: 100px;
margin-left: 100px;
position: absolute;
display: none;
}
<div class="wrapper">
<div class="trigger">trigger1</div>
<div class="redbox">hurrah1</div>
wrapper1</div>
<div class="wrapper">
<div class="trigger">trigger2</div>
<div class="redbox">hurrah2</div>
wrapper2</div>
<div class="wrapper">
<div class="trigger">trigger3</div>
<div class="redbox">hurrah3</div>
wrapper3</div>
The problem you have was that the method "getElementsByClassName", returns you an Array that contains all the elements of that class. So, when you where doing this:
theRedBox[0].style.display = 'block'
You were changing the display style of the First element of the Array, in this case "wrapper1".
Here's a modify version that functions whit the others wrappers:
<!DOCTYPE html>
<html lang = 'es'>
<head>
<title> MY TEST </title>
<style>
body {
background: #222;
}
.wrapper {
background: yellow;
width: 100px;
height: 100px;
}
.trigger {
background: blue;
width: 50px;
height: 50px;
position: absolute;
margin-top: 50px;
margin-left: 50px;
}
.redbox {
background: red;
width: 200px;
height: 100px;
margin-left: 100px;
position: absolute;
display: none;
}
</style>
</head>
<body>
<div class="wrapper">
<div class="trigger" onclick="showTheRedBox(0)">trigger1</div> <!-- When the onClick event is trigered the function "showTheRedBox receives a parameter , that parameter is the position of the element in the Array "theRedBox"-->
<div class="redbox">hurrah1</div>
wrapper1
</div>
<div class="wrapper">
<div class="trigger" onclick="showTheRedBox(1)">trigger2</div>
<div class="redbox">hurrah2</div>
wrapper2
</div>
<div class="wrapper">
<div class="trigger" onclick="showTheRedBox(2)">trigger3</div>
<div class="redbox">hurrah3</div>
wrapper3</div>
<script>
function showTheRedBox(wrapperNumber) {
var theRedBox = document.getElementsByClassName('redbox');
theRedBox[wrapperNumber].style.display = 'block';
}
</script>
</body>
</html>

Categories