This question already has answers here:
How to add a background image on top of a previous background image?
(1 answer)
Can I have multiple background images using CSS?
(8 answers)
Why does z-index not work?
(10 answers)
Closed 3 years ago.
I want to set a z-index to a background img.
I want the .player background to be always displayed, even when in the same box I have another class with another background.
If you click the right button you'll see that at the the .player goes to the blue box another class will be added. The .player background must be always displayed.
Why z-index is not working? is there any alternative?
Thank you
let moveCounter = 0;
let playerOne = {
currentWeapon: "w1"
}
var grid = document.getElementById("grid-box");
for (var i = 0; i <= 8; i++) {
var square = document.createElement("div");
square.className = 'square';
square.id = 'square' + i;
grid.appendChild(square);
}
$("#square" + 0).addClass("player")
$("#square" + 3).addClass("w3")
function getWeapon(ele) {
let classList = $(ele).attr("class").split(' ');
for (let i = 0; i < classList.length; i += 1) {
if (classList[i][0] === "w") {
$(ele).addClass(playerOne.currentWeapon)
playerOne.currentWeapon = classList[i];
$(ele).removeClass(playerOne.currentWeapon)
return classList[i]
}
}
}
$('#right-button').on('click', function() {
$("#square" + moveCounter).removeClass("player")
moveCounter += 1;
$("#square" + moveCounter).addClass("player")
getWeapon("#square" + moveCounter);
});
#grid-box {
width: 420px;
height: 220px;
}
#grid-box>div.square {
font-size: 1rem;
vertical-align: top;
display: inline-block;
width: 10%;
height: 10%;
box-sizing: border-box;
border: 1px solid #000;
}
.player {
background: url(http://placekitten.com/200/300) no-repeat 0 0;
z-index: 1;
}
.w1 {
background: url(https://preview.ibb.co/ntRarR/watermark3.png) no-repeat center center;
z-index: 0;
}
.w3 {
background-color: blue;
}
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<div id="grid-box"></div>
<button class="d-pad-button" id="right-button">Right button</button>
Thank you very much guys.
The problem is the class order in the css file. More info can be found here
Change:
.player {
background: url(http://placekitten.com/200/300) no-repeat 0 0;
z-index: 1;
}
.w1 {
background: url(https://preview.ibb.co/ntRarR/watermark3.png) no-repeat center center;
z-index: 0;
}
To:
.w1 {
background: url(https://preview.ibb.co/ntRarR/watermark3.png) no-repeat center center;
z-index: 0;
}
.player {
background: url(http://placekitten.com/200/300) no-repeat 0 0;
z-index: 1;
}
Demo
let moveCounter = 0;
let playerOne = {
currentWeapon: "w1"
}
var grid = document.getElementById("grid-box");
for (var i = 0; i <= 8; i++) {
var square = document.createElement("div");
square.className = 'square';
square.id = 'square' + i;
grid.appendChild(square);
}
$("#square" + 0).addClass("player")
$("#square" + 3).addClass("w3")
function getWeapon(ele) {
let classList = $(ele).attr("class").split(' ');
for (let i = 0; i < classList.length; i += 1) {
if (classList[i][0] === "w") {
$(ele).addClass(playerOne.currentWeapon)
playerOne.currentWeapon = classList[i];
$(ele).removeClass(playerOne.currentWeapon)
return classList[i]
}
}
}
$('#right-button').on('click', function() {
$("#square" + moveCounter).removeClass("player")
moveCounter += 1;
$("#square" + moveCounter).addClass("player")
getWeapon("#square" + moveCounter);
});
#grid-box {
width: 420px;
height: 220px;
}
#grid-box>div.square {
font-size: 1rem;
vertical-align: top;
display: inline-block;
width: 10%;
height: 10%;
box-sizing: border-box;
border: 1px solid #000;
}
.w1 {
background: url(https://preview.ibb.co/ntRarR/watermark3.png) no-repeat center center;
z-index: 0;
}
.player {
background: url(http://placekitten.com/200/300) no-repeat 0 0;
z-index: 1;
}
.w3 {
background-color: blue;
}
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<div id="grid-box"></div>
<button class="d-pad-button" id="right-button">Right button</button>
Related
Here is a beautiful Number Ticker. the whole day I was wondering and trying to modify the code to make it as I want but no success till now!
if you work with numbers with two or more digits then the code creates separate black squares to hold each digit ( run code snippet to have a look ), but I want only a single square as the container to hold multiple digit numbers. So if we have a two-digit number like 10 the Number Ticker should be something like this:
And the next move should look like :
I don't want those parallel animations that move two digits like this (Only the single animation is required not both):
Here is the code:
let counters = document.getElementsByClassName('number-ticker');
let defaultDigitNode = document.createElement('div');
defaultDigitNode.classList.add('digit');
for (let i = 0; i < 11; i++) {
defaultDigitNode.innerHTML += i + '<br>';
}
[].forEach.call(counters, function(counter) {
let currentValue = 10;
let digits = [];
generateDigits(currentValue.toString().length);
setValue(currentValue);
setTimeout(function() {
setValue(8);
}, 2000);
setTimeout(function() {
setValue(7);
}, 5000);
function setValue(number) {
let s = number.toString().split('').reverse().join('');
let l = s.length;
if (l > digits.length) {
generateDigits(l - digits.length);
}
for (let i = 0; i < digits.length; i++) {
setDigit(i, s[i] || 0);
}
}
function setDigit(digitIndex, number) {
digits[digitIndex].style.marginTop = '-' + number + 'em';
}
function generateDigits(amount) {
for (let i = 0; i < amount; i++) {
let d = defaultDigitNode.cloneNode(true);
counter.appendChild(d);
digits.unshift(d);
}
}
});
:root {
background-color: #555;
color: white;
font-size: 25vh;
font-family: Roboto Light;
}
body,
html {
margin: 0;
height: 100%;
}
.container {
display: flex;
justify-content: center;
align-items: center;
height: 100%;
}
.number-ticker {
overflow: hidden;
height: 1em;
background-color: #333;
box-shadow: 0 0 0.05em black inset;
}
.number-ticker .digit {
float: left;
line-height: 1;
transition: margin-top 1.75s ease;
border-right: 1px solid #555;
padding: 0 0.075em;
}
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Number Ticker</title>
<meta name="viewport" content="width=device-width,initial-scale=1">
<link rel="stylesheet" href="number-ticker.css">
</head>
<body>
<div class="container">
<div class="number-ticker" data-value="0"></div>
</div>
<script src="number-ticker.js"></script>
</body>
</html>
Your css has this
.number-ticker .digit {
float: left;
line-height: 1;
transition: margin-top 1.75s ease;
border-right: 1px solid #555;
padding: 0 0.075em;
}
You need to change it to this
.number-ticker .digit {
float: left;
line-height: 1;
transition: margin-top 1.75s ease;
padding: 0 0.075em;
text-align: center;
}
If you remove border-right: 1px solid #555 you will have it look like 1 box.
Also I added text-align: center to center the numbers.
Hope this solves your problem :)
I think the main issue in your code is the digits variable. It creates an array of HTML elements that holds two blocks.
Also, for this line:
let s = number.toString().split('').reverse().join('');
Why do you need to convert number to a string. You can just pass it as is. Once you add to a string using + it will be converted.
I made few changes to your code and commented out the non-relevant part. Please see below:
let counters = document.getElementsByClassName('number-ticker');
let defaultDigitNode = document.createElement('div');
defaultDigitNode.classList.add('digit');
for (let i = 0; i < 11; i++) {
defaultDigitNode.innerHTML += i + '<br>';
}
[].forEach.call(counters, function(counter) {
// let currentValue = 10;
// let digits = [];
let currentValue = counter.getAttribute("data-value");
let digit = null;
generateDigits(currentValue.toString().length);
setValue(currentValue);
setTimeout(function() {
setValue(8);
}, 2000);
setTimeout(function() {
setValue(7);
}, 5000);
setTimeout(function() {
setValue(10);
}, 8000);
function setValue(number) {
// let s = number.toString().split('').reverse().join('');
// let l = s.length;
/*if (l > digits.length) {
generateDigits(l - digits.length);
}*/
/*for (let i = 0; i < digits.length; i++) {
setDigit(i, s[i] || 0);
}*/
digit.style.marginTop = '-' + number + 'em';
}
/*function setDigit(digitIndex, number) {
console.log(number);
digits[digitIndex].style.marginTop = '-' + number + 'em';
}*/
function generateDigits(amount) {
// console.log("generat", amount);
// for (let i = 0; i < amount; i++) {
let d = defaultDigitNode.cloneNode(true);
digit = counter.appendChild(d);
// digits.unshift(d);
// }
}
});
:root {
background-color: #555;
color: white;
font-size: 25vh;
font-family: Roboto Light;
}
body,
html {
margin: 0;
height: 100%;
}
.container {
display: flex;
justify-content: center;
align-items: center;
height: 100%;
}
.number-ticker {
overflow: hidden;
height: 1em;
background-color: #333;
box-shadow: 0 0 0.05em black inset;
}
.number-ticker .digit {
float: left;
line-height: 1;
transition: margin-top 1.75s ease;
border-right: 1px solid #555;
padding: 0 0.075em;
text-align: center;
}
<div class="container">
<div class="number-ticker" data-value="0"></div>
</div>
Your final JS could be like this:
let counters = document.getElementsByClassName('number-ticker');
let defaultDigitNode = document.createElement('div');
defaultDigitNode.classList.add('digit');
for (let i = 0; i < 11; i++) {
defaultDigitNode.innerHTML += i + '<br>';
}
[].forEach.call(counters, function(counter) {
let currentValue = counter.getAttribute("data-value");
let d = defaultDigitNode.cloneNode(true);
let digit = counter.appendChild(d);
setValue(currentValue);
function setValue(number) {
digit.style.marginTop = '-' + number + 'em';
}
});
The script creates a random number of divs (in range 20-40) and puts some text in every single div. The script calculates the width of divs so that they fit in a single row. The height should be equal to the width - every div must be a square. Here's the code:
var quantity = Math.floor(Math.random() * (40 - 20 + 1)) + 20;
for (var i = 0; i < quantity; i++) {
var elem = document.createElement("div");
elem.className = "part";
elem.id = 'p' + i;
document.getElementById("scale").appendChild(elem);
}
var parts = document.getElementsByClassName("part");
for (var i = 0; i < parts.length; i++) {
parts[i].style.fontSize = (500 / quantity) + 'px';
parts[i].style.lineHeight = (460 / quantity) + 'px';
parts[i].textContent = ("block #" + (i + 1));
}
for (var i = 0; i < parts.length; i++) {
parts[i].style.height = parts[i].style.width;
}
let text = document.getElementById('txt');
text.textContent = 'BLOCKS: ' + quantity;
body {
margin: 0;
}
#scale {
position: absolute;
display: table;
width: 100%;
top: 50%;
transform: translateY(-100%);
table-layout: fixed;
border-spacing: 1px;
}
.part {
display: table-cell;
background-color: #a9cce3;
padding: 3px;
box-sizing: border-box;
border: 1px solid black;
border-radius: 2px;
overflow: hidden;
}
#txt {
position: absolute;
top: 50%;
left: 50%;
margin-top: 20px;
transform: translateX(-50%);
font-size: 18px;
font-family: 'Arial', sans-serif;
}
<div id="scale"> </div>
<div id='txt'> </div>
The first problem is the divs are not always square. The second problem is I can't properly set the font size depending on a div size, so text fits a div. I think that's the worst solution
parts[i].style.fontSize = (500 / quantity) + 'px';
parts[i].style.lineHeight = (460 / quantity) + 'px';
There were two problems with the code:
To get element with use .clientWidth because style.width can be accessed when you have set that but in your code, I couldn't see you are doing so.
Second use font size in per cent, I don't think line-height is required. To make it centre use CSS as in example follows.
Use following:
var quantity = Math.floor(Math.random() * (40 - 20 + 1)) + 20;
for (var i = 0; i < quantity; i++) {
var elem = document.createElement("div");
elem.className = "part";
elem.id = 'p' + i;
document.getElementById("scale").appendChild(elem);
}
var parts = document.getElementsByClassName("part");
for (var i = 0; i < parts.length; i++) {
parts[i].style.fontSize = (500 / quantity) + '%';
parts[i].style.lineHeight = (460 / quantity) + '%';
parts[i].textContent = ("block #" + (i + 1));
}
for (var i = 0; i < parts.length; i++) {
parts[i].style.height = parts[i].clientWidth + "px";
}
let text = document.getElementById('txt');
text.textContent = 'BLOCKS: ' + quantity;
body {
margin: 0;
}
#scale {
position: absolute;
display: table;
width: 100%;
top: 50%;
transform: translateY(-100%);
table-layout: fixed;
border-spacing: 1px;
}
.part {
display: table-cell;
background-color: #a9cce3;
padding: 3px;
box-sizing: border-box;
border: 1px solid black;
border-radius: 2px;
overflow: hidden;
vertical-align: middle;
text-align: center;
}
#txt {
position: absolute;
top: 50%;
left: 50%;
margin-top: 20px;
transform: translateX(-50%);
font-size: 18px;
font-family: 'Arial', sans-serif;
}
<div id="scale"> </div>
<div id='txt'> </div>
Or if you don't want to use your text font to be reduced like this use following:
.part {
display: table-cell;
background-color: #a9cce3;
padding: 3px;
box-sizing: border-box;
border: 1px solid black;
border-radius: 2px;
overflow: hidden;
vertical-align: middle;
text-align: center;
text-overflow: ellipsis;
overflow: hidden;
white-space: nowrap;
}
I am trying to learn by creating a chat bar. I have created a side nav bar with users and once I click the chat pop up box will open at the bottom. I want to add input field to that chatbox.
I tried to add the input field but I just got half success; it just gets added to the body not at the bottom of the chat box.
chat.html
<script>
//this function can remove a array element.
Array.remove = function(array, from, to) {
var rest = array.slice((to || from) + 1 || array.length);
array.length = from < 0 ? array.length + from : from;
return array.push.apply(array, rest);
};
var total_popups = 0;
//arrays of popups ids
var popups = [];
function close_popup(id)
{
for(var iii = 0; iii < popups.length; iii++)
{
if(id == popups[iii])
{
Array.remove(popups, iii);
document.getElementById(id).style.display = "none";
calculate_popups();
return;
}
}
}
function display_popups()
{
var right = 220;
var iii = 0;
for(iii; iii < total_popups; iii++)
{
if(popups[iii] != undefined)
{
var element = document.getElementById(popups[iii]);
element.style.right = right + "px";
right = right + 320;
element.style.display = "block";
}
}
for(var jjj = iii; jjj < popups.length; jjj++)
{
var element = document.getElementById(popups[jjj]);
element.style.display = "none";
}
}
function register_popup(id, name)
{
for(var iii = 0; iii < popups.length; iii++)
{
//already registered. Bring it to front.
if(id == popups[iii])
{
Array.remove(popups, iii);
popups.unshift(id);
calculate_popups();
return;
}
}
var element = '<div class="popup-box chat-popup" id="'+ id +'">';
element = element + '<div class="popup-head">';
element = element + '<div class="popup-head-left">'+ name +'</div>';
element = element + '<div class="popup-head-right">✕</div>';
element = element + '<div style="clear: both"></div></div><div class="popup-messages"></div></div>';
element = element + '<div class="popup-bottom"><div class="popup-bottom"><div id="'+ id +'"></div><input id="field"></div>';
document.getElementsByTagName("body")[0].innerHTML = document.getElementsByTagName("body")[0].innerHTML + element;
popups.unshift(id);
calculate_popups();
}
//calculate the total number of popups suitable and then populate the toatal_popups variable.
function calculate_popups()
{
var width = window.innerWidth;
if(width < 540)
{
total_popups = 0;
}
else
{
width = width - 200;
//320 is width of a single popup box
total_popups = parseInt(width/320);
}
display_popups();
}
//recalculate when window is loaded and also when window is resized.
window.addEventListener("resize", calculate_popups);
window.addEventListener("load", calculate_popups);
</script>
style.css
<style>
#media only screen and (max-width : 540px)
{
.chat-sidebar
{
display: none !important;
}
.chat-popup
{
display: none !important;
}
}
body
{
background-color: #e9eaed;
}
.chat-sidebar
{
width: 200px;
position: fixed;
height: 100%;
right: 0px;
top: 0px;
padding-top: 10px;
padding-bottom: 10px;
border: 1px solid rgba(29, 49, 91, .3);
}
.sidebar-name
{
padding-left: 10px;
padding-right: 10px;
margin-bottom: 4px;
font-size: 12px;
}
.sidebar-name span
{
padding-left: 5px;
}
.sidebar-name a
{
display: block;
height: 100%;
text-decoration: none;
color: inherit;
}
.sidebar-name:hover
{
background-color:#e1e2e5;
}
.sidebar-name img
{
width: 32px;
height: 32px;
vertical-align:middle;
}
.popup-box
{
display: none;
position: absolute;
bottom: 0px;
right: 220px;
height: 285px;
background-color: rgb(237, 239, 244);
width: 300px;
border: 1px solid rgba(29, 49, 91, .3);
}
.popup-box .popup-head
{
background-color: #009688;
padding: 5px;
color: white;
font-weight: bold;
font-size: 14px;
clear: both;
}
.popup-box .popup-head .popup-head-left
{
float: left;
}
.popup-box .popup-head .popup-head-right
{
float: right;
opacity: 0.5;
}
.popup-box .popup-head .popup-head-right a
{
text-decoration: none;
color: inherit;
}
.popup-box .popup-bottom .popup-head-left
{
position:absolute;
left: 0px;
bottom: 0px
text-decoration: none;
color: inherit;
}
.popup-box .popup-messages
{
height: 100%;
overflow-y: scroll;
}
</style>
posting relevant parts hopw you can make sense of it.
HTML
<div class="popup-box chat-popup">
<div class="popup-head">
<div class="popup-head-left">name</div>
<div class="popup-head-right">✕</div>
<div style="clear: both"></div>
</div>
<div class="popup-messages"></div>
<div class="popup-bottom-container">
<div class="popup-bottom">
<div id="'+ id +'"></div>
<input type="text" id="field">
</div>
</div>
</div>
CSS
.popup-bottom
{
position:absolute;
left: 0px;
bottom: 10px;
text-decoration: none;
color: inherit;
}
.popup-box .popup-messages
{
height: 200px;
overflow-y: scroll;
}
It is always better to try out your layout in plain html before testing with js
I have written a program in javascript that matches the images which are randomly shuffled in a 4x4 grid. I have read that for flipping the images, you need to have a front image and a back image. I have declared the "back" images for my program in an Array inside of Javascript and have the common "front" image declared in the div holding those images. Now, I am unable to target the front or back images in my program for applying all the css3 transformation code as they are declared in the Javascript. Hence, I need help in suggesting me a way to achieve flipping in my program. Here is my code:
HTML:
<div class="container">
<div class="page-header">
Match The Flag!
</div>
<div id="clicks"> </div>
<div id="memory_board" onClick="Click()"></div>
<script>newBoard();</script>
<!-- <button onclick=" return newBoard();"> Reset </button> -->
<div class="refresh">
<img src="images/refresh.png" alt="refresh" onclick="return location.reload();">
</div>
</div>
Javscript
<script>
var memory_array = ['A','A','B','B','C','C','D','D','E','E','F','F','G','G','H','H'];
var memory_values = [];
var memory_tile_ids = [];
var tiles_flipped = 0;
Array.prototype.memory_tile_shuffle = function() /* Shuffle Function to Randomly Position the Cards */
{
var i = this.length, j, temp; /* this.length keyword will automatically take the length of the parameter passed to the parent function i.e array of cards */
while(i--){
j = Math.floor(Math.random() * (i+1));
temp = this[j];
this[j] = this[i];
this[i] = temp;
}
}
function newBoard()
{
var i = 0;
tiles_flipped = 0;
var output = '';
memory_array.memory_tile_shuffle();
for(var i = 0; i < memory_array.length; i++){
output += '<div id="tile_'+i+'" onclick="memoryFlipTile(this,\''+memory_array[i]+'\')"></div>';
}
document.getElementById('memory_board').innerHTML = output;
localStorage.setItem("score1", clicks);
}
function memoryFlipTile(tile, val)
{
if(tile.innerHTML == "" && memory_values.length < 2)
{
tile.style.background = '#FFF';
tile.innerHTML = '<img src="' + val + '.png"/>'; /* Adding .png format after our image array */
if(memory_values.length == 0) /* For First Click on the image */
{
memory_values.push(val);
memory_tile_ids.push(tile.id);
}
else if(memory_values.length == 1) /* For Second Click on the other image */
{
memory_values.push(val);
memory_tile_ids.push(tile.id);
console.log(memory_values[0]+" "+memory_values[1]);
if(memory_values[0] == memory_values[1])
{
document.getElementById(memory_tile_ids[0]).style.backgroundColor = "lightgreen";
document.getElementById(memory_tile_ids[1]).style.backgroundColor = "lightgreen";
tiles_flipped += 2;
memory_values = []; /* Clear arrays */
memory_tile_ids = []; /* Clear arrays */
if(tiles_flipped == memory_array.length) /* Check to see if all cards are flipped back */
{
var score = Click();
score--;
/*console.log("Score: "+score);/*
/*alert("All Tiles Flipped. Your Score: "+score);*/
document.getElementById('memory_board').innerHTML = "";
/*newBoard();*/ // Don't Remove
/*var i = 0;
location.reload();*/
}
}
else /* If the images don't match, then flip the two flipped images back */
{
function flipBack()
{
var tile_1 = document.getElementById(memory_tile_ids[0]);
var tile_2 = document.getElementById(memory_tile_ids[1]);
tile_1.style.background = 'url(images/card.png) no-repeat';
tile_1.style.backgroundSize = '100% 100%';
tile_1.innerHTML = "";
tile_2.style.background = 'url(images/card.png) no-repeat';
tile_2.style.backgroundSize = '100% 100%';
tile_2.innerHTML = "";
memory_values = []; /* Clear arrays */
memory_tile_ids = []; /* Clear arrays */
}
setTimeout(flipBack, 700);
}
}
}
}
var clicks = 0;
var previous_scores = localStorage.getItem("old-score");
console.log(previous_scores);
function Click()
{
if(tiles_flipped == memory_array.length)
{
document.getElementById("clicks").innerHTML = "New Score: "+clicks+"<br>"+"Old Score: "+previous_scores;
localStorage.setItem("old-score", clicks);
/*window.location.href = "score.html";*/
}
else
{
clicks += 1;
document.getElementById("clicks").innerHTML = "Clicks: "+clicks;
return clicks;
}
}
</script>
CSS
#memory_board
{
width: 760px;
height: 660px;
padding: 40px;
margin: 0px auto;
}
#memory_board > div
{
background-color: lightblue;
background: url('images/card.png') no-repeat;
background-size: 100% 100%;
width: 130px;
height: 120px;
float: left;
margin: 10px;
padding: 20px;
font-size: 64px;
cursor: pointer;
text-align: center;
border-radius: 5px;
}
#tile_0 img, #tile_1 img, #tile_2 img, #tile_3 img, #tile_4 img, #tile_5 img, #tile_6 img, #tile_7 img, #tile_8 img, #tile_9 img, #tile_10 img, #tile_11 img, #tile_12 img, #tile_13 img, #tile_14 img, #tile_15 img
{
width: 100px;
margin-top: 30px;
}
Here is an example of flipping an image from a front image to a back image.
You should be able to adapt this example so that it works within your setup.
.container {
position: relative;
width: 100px;
height: 130px;
perspective: 800px;
}
.card {
position: absolute;
width: 100%;
height: 100%;
transform-style: preserve-3d;
transition: transform 1s;
}
.card div {
display: block;
position: absolute;
top: 0;
left: 0;
margin: 0;
width: 100%;
height: 100%;
line-height: 130px;
text-align: center;
font-weight: bold;
font-size: 90px;
color: rgb(255, 255, 255);
text-shadow: 4px 4px 4px rgba(0, 0, 0, 0.4);
backface-visibility: hidden;
}
.card .front {
background: url('http://placekitten.com/400/520') 0 0 / 100px 130px no-repeat;
}
.card .back {
background: url('http://placekitten.com/1600/2080') 0 0 / 100px 130px no-repeat;
transform: rotateY( 180deg );
}
.card:hover {
transform: rotateY( 180deg );
}
<section class="container">
<div class="card">
<div class="front"></div>
<div class="back"></div>
</div>
</section>
Credit: The example above is modified from the markup and styling provided in the tutorial at:
https://desandro.github.io/3dtransforms/docs/card-flip.html
I have a simple image slider, with pagination controls.
I have coded it to add and remove an "active" class on the pagination
buttons on click. I would also like them to have the active class when the corresponding slide is showing.
How can I modify my code to achieve this?
<div id="slideshow">
<ul id="slides">
<li class="slide showing">
<div class="slide-description">
<h1 class="slide-title">All-in-one EV charging solution.</h1>
<p> Easy to use. Connected with smart charging capabilities. Our charging stations can be used at home,
work or in public.</p>
</div>
</li>
<li class="slide">
<div class="slide-description">
<h1 class="slide-title">Charging at work- a case study.</h1>
<p>In this new series of charging case studies, we dive into into the reasons why EV-Box partners are taking the green route.</p>
</div>
</li>
<li class="slide"> <div class="slide-description">
<h1 class="slide-title">Finding the best solution for your charging routine.</h1>
<p>
This whitepaper highlights the key answers that will guide you to acharging solution that best serves your needs.
</p>
</div>
</li>
</ul>
<button class="controls" id="previous"></button>
<button class="controls" id="next"></button>
<div id="pagination"></div>
var slides = document.querySelectorAll('#slides .slide'); // get all the slides
var currentSlide = 0;
var slideInterval = setInterval(nextSlide, 6000);
function nextSlide() {
goToSlide(currentSlide + 1);
}
function previousSlide() {
goToSlide(currentSlide - 1);
}
function goToSlide(n) {
slides[currentSlide].className = 'slide';
currentSlide = (n + slides.length) % slides.length;
slides[currentSlide].className = 'slide showing';
}
//Previous and Next controls
var next = document.getElementById('next');
var previous = document.getElementById('previous');
next.onclick = function() {
nextSlide();
};
previous.onclick = function() {
previousSlide();
};
//Pagination controls
var p = document.getElementById('pagination');
var phtml = '';
for(var i = 0; i < slides.length; i++) {
phtml += '<button></button>'; // create the pagination buttons for each slide
}
p.innerHTML = phtml; //insert the html for the buttons
var pbuttons = p.querySelectorAll('button'); // grab all the buttons
var activeButton = null; // reference to active button
for(var i = 0; i < pbuttons.length; i++) {
pbuttons[i].onclick = (function(n) {
return function() {
if(activeButton)
activeButton.classList.remove('active'); // delete class from old active button
activeButton = this;// change ref, this is current button
activeButton.classList.add('active');// add class for new
goToSlide(n);
};
})(i);
}
#slider {
min-height: 400px;
position: relative;
#slides {
min-height: 400px;
padding: 0;
margin: 0;
list-style-type: none;
.slide {
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
opacity: 0;
z-index: 1;
min-height: 400px;
box-sizing: border-box;
background: $black;
color: $white;
display: flex;
align-items: center;
-webkit-justify-content: flex-end;
justify-content: flex-end;
-webkit-transition: opacity 1s;
-moz-transition: opacity 1s;
transition: opacity 1s;
&.showing {
opacity: 1;
z-index: 2;
}
&:nth-of-type(1) {
#include backImage('../images/evbox1.jpg');
}
&:nth-of-type(2){
#include backImage('../images/evbox2.jpg');
}
&:nth-of-type(3) {
#include backImage('../images/evbox3.jpg');
}
}
.slide-description {
width: 500px;
.slide-title {
width: 90%;
font-family: 'Open Sans', sans-serif;
font-size: 44px;
text-shadow: 0 2px 3px rgba($black, .2);
line-height: 1.1em;
margin-bottom: 10px;
}
p {
margin-bottom: 15px;
width: 90%;
font-size: 20px;
font-family: 'Open Sans', sans-serif;
font-weight: 300;
text-shadow: 0 2px 3px rgba($black, .2);
}
.btn {
#include button($blue, $font-color, $shadow-color);
}
}
#include respond-to($mobile) {
#media only screen and (max-width: $mobile) {
.slide:nth-of-type(3) {
background-position: left 0;
}
.slide-description {
height: 100%;
width: 100%;
padding: 8em 5em;
position: static;
text-align: center;
.slide-title {
font-size: 30px;
width: 100%;
}
.btn {
padding: 8px 16px;
}
}
p {
display: none;
}
}
}
}
}
/*Previous and Next Controls*/
.controls {
position: absolute;
top: 42%;
z-index: 10;
background: url('http://www.ev-box.com/Evbox-EN/includes/themes/evbox/assets/images/sprites#2x.png') no-repeat;
height: 50px;
width: 30px;
background-size: 369px 240px;
outline: 0;
border: 0;
cursor: pointer;
}
#previous {
right: 10px;
background-position: -50px -121px;
}
#next {
left: 10px;
background-position: -16px -121px;
}
// Pagination
#pagination {
position: absolute;
bottom: 30px;
right: 50%;
z-index: 10;
button {
border-radius: 50%;
border: 1px solid $white;
background-color: $white;
opacity: .8;
width: 14px;
height: 14px;
min-height: 14px;
border-width: 0;
margin-right: 5px;
&.active {
width: 15px;
height: 15px;
min-height: 15px;
border: 1px solid $white;
background-color: $primary;
opacity: 1;
&:focus {
outline: 0;
}
}
}
}
I updated the javascript as shown below. Use this in your code pen. you can see the diffrence. If you click next and previous button the corresponding pagination will be highlighted by using this javascript
document.addEventListener("DOMContentLoaded", function() {
var slides = document.querySelectorAll('#slides .slide'); // get all the slides
const totalSlides = 2 // Total number of slides count
var currentSlide = 0; // current slide
var previousSlide = totalSlides;
// var slideInterval = setInterval(nextSlide, 1000);
function nextSlide() {
previousSlide = currentSlide
if(totalSlides > currentSlide){
currentSlide += 1
}
else currentSlide = 0
goToSlide();
}
function PreviousSlide() {
if(currentSlide == 0){
previousSlide = currentSlide
currentSlide = totalSlides
}
else{
previousSlide = currentSlide
currentSlide -=1
}
goToSlide();
}
function goToSlide() {
slides[previousSlide].className = 'slide';
slides[currentSlide].className = 'slide showing';
var currentSlideButton = "button"+currentSlide
var previousSlideButton = "button"+previousSlide
document.getElementById(currentSlideButton).classList.add('active');
document.getElementById(previousSlideButton).classList.remove('active');
}
//Previous and Next controls
var next = document.getElementById('next');
var previous = document.getElementById('previous');
next.onclick = function() {
PreviousSlide();
};
previous.onclick = function() {
nextSlide();
};
//Pagination controls
var p = document.getElementById('pagination');
var phtml = '';
for(var i = 0; i < slides.length; i++) {
phtml += '<button id=button'+i+'></button>'; // create the pagination buttons for each slide
}
p.innerHTML = phtml; //insert the html for the buttons
var pbuttons = p.querySelectorAll('button'); // grab all the buttons
var activeButton = null; // reference to active button
for(var i = 0; i < pbuttons.length; i++) {
pbuttons[i].onclick = (function(n) {
return function() {
if(activeButton)
activeButton.classList.remove('active'); // delete class from old active button
activeButton = this;// change ref, this is current button
activeButton.classList.add('active');// add class for new
goToSlide(n);
};
})(i);
}
goToSlide();// Initialising goToSlide method
});