Hi guys I am trying to create a Carousel using JS. I have succeeded a bit and I able to move one slide to the right side. I figure if I somehow increase the value of widthToMove variable then by clicking on right arrow button will keep pushing the slides. I tried to create a function that returns simply 1, 2, 3, and so on and multiply it with widthToMove on clicking right arrow button but I could not succeed. Any help will highly be appreciated.
Here is the html code;
var productDataWomens = [
{
productUrl:
'https://www.newlook.com/uk/womens/clothing/coats-jackets/dark-grey-faux-fur-longline-coat/p/619712403',
imageSrc: 'https://media2.newlookassets.com/i/newlook/619712403.jpg',
productTitle: 'Dark Grey Faux Fur Longline Coat',
price: '45.99',
},
{
productUrl:
'https://www.newlook.com/uk/womens/clothing/tops/black-ribbed-long-sleeve-roll-neck-top/p/635105501',
imageSrc: 'https://media2.newlookassets.com/i/newlook/635105501.jpg',
productTitle: 'Black Ribbed Long Sleeve Roll Neck Top',
price: '8.99',
},
{
productUrl:
'https://www.newlook.com/uk/womens/clothing/leggings/black-coated-leather-look-leggings/p/634018201',
imageSrc: 'https://media3.newlookassets.com/i/newlook/634018201.jpg',
productTitle: 'Black Coated Leather-Look Leggings',
price: '19.99',
},
{
productUrl:
'https://www.newlook.com/uk/womens/clothing/coats-jackets/black-faux-fur-longline-coat/p/619712401',
imageSrc: 'https://media3.newlookassets.com/i/newlook/619712401.jpg',
productTitle: 'Black Faux Fur Longline Coat',
price: '45.99',
},
{
productUrl:
'https://www.newlook.com/uk/womens/clothing/jeans/black-high-waist-super-skinny-hallie-jeans/p/635654901',
imageSrc: 'https://media2.newlookassets.com/i/newlook/635654901.jpg',
productTitle: 'Black High Waist Super Skinny Hallie Jeans',
price: '25.99',
},
{
productUrl:
'https://www.newlook.com/uk/womens/clothing/coats-jackets/formal-coats/camel-revere-collar-coat/p/619653214',
imageSrc: 'https://media2.newlookassets.com/i/newlook/619653214.jpg',
productTitle: 'Camel Revere Collar Coat',
price: '35.99',
}
]
for (i in productDataWomens) {
var node = document.createElement('LI');
node.setAttribute('class', 'carousel-list-item' + ' ' + 'current-slide');
var carouselImg = document.createElement('img');
carouselImg.setAttribute('class', 'carousel-images');
carouselImg.src = productDataWomens[i].imageSrc;
node.appendChild(carouselImg);
document.getElementById('carousel-list-id').appendChild(node);
}
const track = document.querySelector('.carousel-list-items');
console.log(track);
const slides = Array.from(track.children);
console.log(slides);
const nextButton = document.querySelector('.right-button');
const prevButton = document.querySelector('.left-button');
const slideWidth = slides[0].getBoundingClientRect().width;
nextButton.addEventListener('click', (e) => {
let currentSlide = track.querySelector('.current-slide');
console.log(currentSlide);
let widthToMove = currentSlide.clientWidth;
console.log(slides[0]);
widthToMove = widthToMove + 'px';
console.log(widthToMove);
let nextSlide = currentSlide.nextElementSibling;
console.log(nextSlide);
//const amountToMove = nextSlide.style.widthToMove;
track.style.transform = 'translateX(-' + widthToMove + ')';
currentSlide.classList.remove('current-slide');
//nextSlide.classList.add('current-slide');
});
.carousel {
display: flex;
justify-content: space-between;
/* overflow-x: hidden; */
width: 80%;
margin: 0 auto;
}
.carousel-list-items {
display: flex;
justify-content: space-between;
}
.carousel-container {
overflow-x: hidden;
}
.carousel-list {
list-style: none;
}
.carousel-images {
padding: 15px;
height: 200px;
}
.carousel-button {
position: relative;
background-color: transparent;
border: none;
cursor: pointer;
outline: 0;
}
.right-button {
right: 0;
margin-left: 15px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://kit.fontawesome.com/88ce2b0d97.js" crossorigin="anonymous"></script>
<link rel="stylesheet" href="styles.css">
<title>New Look</title>
</head>
<body>
<div class="carousel">
<button class="left-button carousel-button"><i class="fas fa-chevron-left"></i></button>
<div class="carousel-container" >
<ul class="carousel-list">
<a href="" id="carousel-list-id" class="carousel-list-items">
<!-- <li class="carousel-list-item current-slide" id="carousel-list-id"></li> -->
</a>
</ul>
</div>
<button class="right-button carousel-button"><i class="fas fa-chevron-right"></i></button>
</div>
<script src="script.js"></script>
</script>
</body>
</html>
The problem with your slider is that each time you click on the next button the widthToMove variable is overwritten with currentSlide.clientWidth, what you should've done instead is:
take widthToMove variable outside the scope of the listener
on each click add the values of widthToMove and currentSlide.clientWidth and assign the sum to widthToMove
Also when your slider is "initialized", every slide has the class current-slide therefore you can't determine which slide is the current.
var productDataWomens = [
{
productUrl:
'https://www.newlook.com/uk/womens/clothing/coats-jackets/dark-grey-faux-fur-longline-coat/p/619712403',
imageSrc: 'https://media2.newlookassets.com/i/newlook/619712403.jpg',
productTitle: 'Dark Grey Faux Fur Longline Coat',
price: '45.99',
},
{
productUrl:
'https://www.newlook.com/uk/womens/clothing/tops/black-ribbed-long-sleeve-roll-neck-top/p/635105501',
imageSrc: 'https://media2.newlookassets.com/i/newlook/635105501.jpg',
productTitle: 'Black Ribbed Long Sleeve Roll Neck Top',
price: '8.99',
},
{
productUrl:
'https://www.newlook.com/uk/womens/clothing/leggings/black-coated-leather-look-leggings/p/634018201',
imageSrc: 'https://media3.newlookassets.com/i/newlook/634018201.jpg',
productTitle: 'Black Coated Leather-Look Leggings',
price: '19.99',
},
{
productUrl:
'https://www.newlook.com/uk/womens/clothing/coats-jackets/black-faux-fur-longline-coat/p/619712401',
imageSrc: 'https://media3.newlookassets.com/i/newlook/619712401.jpg',
productTitle: 'Black Faux Fur Longline Coat',
price: '45.99',
},
{
productUrl:
'https://www.newlook.com/uk/womens/clothing/jeans/black-high-waist-super-skinny-hallie-jeans/p/635654901',
imageSrc: 'https://media2.newlookassets.com/i/newlook/635654901.jpg',
productTitle: 'Black High Waist Super Skinny Hallie Jeans',
price: '25.99',
},
{
productUrl:
'https://www.newlook.com/uk/womens/clothing/coats-jackets/formal-coats/camel-revere-collar-coat/p/619653214',
imageSrc: 'https://media2.newlookassets.com/i/newlook/619653214.jpg',
productTitle: 'Camel Revere Collar Coat',
price: '35.99',
}
]
for (i in productDataWomens) {
var node = document.createElement('LI');
// If it's the first slide add .current-slide
// The line below uses a turnary operator which is a short if/else statement
var currentSlide = ( i == 0 ? ' current-slide' : '' );
// Which can be rewritten to this
//var currentSlide;
//if( i == 0 ) {
// currentSlide == ' current-slide';
//} else {
// currentSlide == '';
//}
node.setAttribute('class', 'carousel-list-item' + currentSlide );
var carouselImg = document.createElement('img');
carouselImg.setAttribute('class', 'carousel-images');
carouselImg.src = productDataWomens[i].imageSrc;
node.appendChild(carouselImg);
document.getElementById('carousel-list-id').appendChild(node);
}
const track = document.querySelector('.carousel-list-items');
const nextButton = document.querySelector('.right-button');
const prevButton = document.querySelector('.left-button');
let widthToMove = 0;
nextButton.addEventListener('click', (e) => {
let currentSlide = track.querySelector('.current-slide');
let nextSlide;
if( !currentSlide.nextElementSibling ) {
nextSlide = document.querySelectorAll('.carousel-list-item')[0];
widthToMove = 0;
} else {
nextSlide = currentSlide.nextElementSibling;
widthToMove += currentSlide.clientWidth;
}
// You can use template literals to create a string with several variables/functions/expressions for speed, convenience and readability
track.style.transform = `translateX(-${widthToMove + 30}px)`;
currentSlide.classList.remove('current-slide');
// Add current-slide class to next slide
nextSlide.classList.add('current-slide');
});
.carousel {
display: flex;
justify-content: space-between;
/* overflow-x: hidden; */
width: 80%;
margin: 0 auto;
}
.carousel-list-items {
display: flex;
justify-content: space-between;
transition: all 0.3s ease-in-out 0s;
}
.carousel-container {
overflow-x: hidden;
}
.carousel-list {
list-style: none;
}
.carousel-images {
padding: 15px;
height: 200px;
}
.carousel-button {
position: relative;
background-color: transparent;
border: none;
cursor: pointer;
outline: 0;
}
.right-button {
right: 0;
margin-left: 15px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://kit.fontawesome.com/88ce2b0d97.js" crossorigin="anonymous"></script>
<link rel="stylesheet" href="styles.css">
<title>New Look</title>
</head>
<body>
<div class="carousel">
<button class="left-button carousel-button"><i class="fas fa-chevron-left"></i></button>
<div class="carousel-container" >
<ul class="carousel-list">
<a href="" id="carousel-list-id" class="carousel-list-items">
<!-- <li class="carousel-list-item current-slide" id="carousel-list-id"></li> -->
</a>
</ul>
</div>
<button class="right-button carousel-button"><i class="fas fa-chevron-right"></i></button>
</div>
<script src="script.js"></script>
</script>
</body>
</html>
Related
I am Beginner developer and i try to clone website (using HTML,CSS,JS)
and I stuck in Add products on shopping cart and these my Code:
const listProducts = [
{
id: 1,
name: 'Short Pant',
price: '300.000 VND',
imageUrl: 'img/1.jpg',
button: 'Add to Cart'
},
{
id: 2,
name: 'Long Pant',
price: '500.000 VND',
imageUrl: 'img/2.jpg',
button: 'Add to Cart'
},
{
id: 3,
name: 'Long Shirt',
price: '400.000 VND',
imageUrl: 'img/3.jpg',
button: 'Add to Cart'
},
{
id: 4,
name: 'T-Shirt',
price: '200.000 VND',
imageUrl: 'img/4.jpg',
button: 'Add to Cart'
}
];
const product = document.getElementsByClassName("product");
let item = "";
let listItem = item => {
for (i = 0; i < listProducts.length; i++) {
item += `
<div class="product-item">
<img src="${listProducts[i].imageUrl}" alt="ảnh" />
<h2>${listProducts[i].name}</h2>
<div><span>${listProducts[i].price}</span></div>
<button class="btn">${listProducts[i].button}</button></div>`
}
return item
}
product[0].innerHTML = listItem();
let btnCart = document.getElementsByClassName('btn')
for (j = 0; j < listProducts.length; j++) {
addEventListener('click', function() {
this.document.querySelector('.listCart').append(item)
})
And this is my HTML Code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
img {
max-width: 350px;
height: 350px;
object-fit: contain;
}
.product {
display: flex;
justify-content: space-around;
}
.product-item {
border: 1px solid;
text-align: center;
}
h2 {
border-top: 1px solid black;
text-align: center;
margin-top: 50px;
padding-top: 20px;
}
</style>
</head>
<body>
<div class="product"></div>
<div class="cart">
<div class="listCart">
<h2>Cart</h2>
</div>
</div>
<script src="bai10.js"></script>
</body>
</html>
I am Beginner developer and i try to clone website (using HTML,CSS,JS)
and I stuck in Add products on shopping cart and these my Code:
I am Beginner developer and i try to clone website (using HTML,CSS,JS)
and I stuck in Add products on shopping cart and these my Code:
I am Beginner developer and i try to clone website (using HTML,CSS,JS)
and I stuck in Add products on shopping cart and these my Code:
I have a grid of cards with a button to remove each one of them with an animation. I chose to reduce the width to 0 so that the cards to the right (on the same row) slide to the left and occupy the removed card spot.
What I would like to achieve is to animate the first element of the following row into the last position of the row above (the one that had the card removed).
The best example I can provide is the home page of the Vivaldi browser, where you can remove a speed dial widget and the following ones animate to their new positions.
This example in CodePen is what I have so far.
$(document).ready(function() {
const content = $('#inner-content');
let listCourses = '';
let courses = [
{ title: 'html' },
{ title: 'css' },
{ title: 'javascript' },
{ title: 'python' },
{ title: 'react' },
{ title: 'node' },
{ title: 'angular' },
{ title: 'SEO' },
{ title: 'UX/UI' },
{ title: 'jQuery' },
{ title: 'SQL' },
{ title: 'noSql' }
]
courses.forEach((course) => {
let newCourse = `
<div class="course-container">
<div class="inner-container">
<h2>${course.title}</h2>
<button class="courses-control"> Remove </button>
</div>
</div>
`;
listCourses += newCourse;
});
content.html(listCourses);
$('.courses-control').on('click', function(e){
$(this)
.parents('.course-container').animate({
'width': '0px',
'padding': '12px 0px',
'opacity': '0'}, function() {
$(this).remove();
});
})
});
* {
box-sizing: border-box;
}
body { font-family: 'lato'; }
#inner-content {
display: flex;
flex-wrap: wrap;
}
.centered {
max-width: 960px;
margin: auto;
}
.course-container {
width: 25%;
padding: 12px;
overflow: hidden;
}
.inner-container {
overflow: hidden;
text-align: center;
border: 1px solid gray;
border-radius: 6px;
padding: 12px;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title></title>
<link rel="stylesheet" href="styles.css" />
</head>
<body>
<h1>Courses</h1>
<div id="inner-content" class="centered">
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="scripts.js"></script>
</body>
</html>
change the forEach loop to have an index and give each button an id:
courses.forEach((course, index) => {
let newCourse = `
<div class="course-container">
<div class="inner-container">
<h2>${course.title}</h2>
<button id="${index}" class="courses-control"> Remove </button>
</div>
</div>
`;
listCourses += newCourse;
});
Then in the click function after this:
$(this)
.parents('.course-container').animate({
'width': '0px',
'padding': '12px 0px',
'opacity': '0'
}, function () {
$(this).remove();
});
add this:
$(`#${Number(this.id) + 4}`).parents('.course-container').animate({
'margin-top': '-100px',
'z-index': '1',
'opacity': '0'
}, 500, function () {
$(this).css({ 'margin': '0px', 'opacity': '1' });
});
Try it out and tell me what you think...
I am new here and I am learning programming and I have some doubts about how can I change the style of each function result.
I´m trying to do a poker card that change my elements array for icons depends on the function result and I don´t know how to do it.
Could you help me please?
var cardSuits = ['spades', 'diamonds', 'hearts', 'clubs'];
var cardValue = [
'1','2', '3', '4',
'5', '6', '7', '8',
'9', '10', 'J', 'Q', 'K'];
const GenerateRandomCard = () => {
let cardSuitsRandom = Math.floor(Math.random() * (cardSuits.length));
console.log(cardSuitsRandom);
let cardValueRandom = Math.floor(Math.random() * (cardValue.length));
return '<div>' + cardSuits[cardSuitsRandom] + '</div>' + '<div>' + cardValue [cardValueRandom] + '</div>' + '<div>'+ cardSuits[cardSuitsRandom] + '</div>'
};
window.onload = () => {
document.querySelector('#cardMap').innerHTML = GenerateRandomCard();
}
body {
background-color: green
}
#cardMap {
display: flex;
flex-direction: row;
flex-wrap: wrap;
margin: 80px auto 10px auto;
height: 420px;
width: 360px;
background-color: white;
border-radius: 5px;
}
.allCard {
font-size: 16px;
}
.heartCard {
}
.spadeCard {
}
.diamondCard {
}
.clubCard {
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" type="text/css" href="index.css">
<title>Random Card</title>
</head>
<body>
<div id="cardMap"></div>
<script type="text/javascript" src="index.js"></script>
</body>
</html>
Replace .allCard{} with .card{}
Use the .card{} selector to put all the common styles that should be there regardless of the type of card.
So I guess
.card{
font-size: 16px;
}
And then in your javascript code
var element = document.getElementById("cardMap");
element.classList.add(cardSuitsRandom);
Will add the classes with the card suit, so if you pull a heart, the class will look like class="card hearts"
And then make selectors in your css like
card.spades{}, card.hearts{}, etc
You could do this:
return '<div class="'+cardSuits[cardSuitsRandom]+' value-'+cardValue[cardValueRandom]+'"></div>;
So you add the results of the randomly generated suit and card value to your returned <div>'s classes, and then you style the classes accordingly.
To assign a CSS rule with each suit, create an array of rule names that map to the suit names:
var cardSuits = ['spades', 'diamonds', 'hearts', 'clubs'];
const cardStyles = ['spadeCard', 'diamondCard', 'heartCard', 'clubCard'];
Then simply add the class to the div:
return `<div class="${cardStyles[cardSuitsRandom]}">` + ...
};
A working example with a few additional styling enhancements:
const cardSuits = ['spades', 'diamonds', 'hearts', 'clubs'];
const cardStyles = ['spadeCard', 'diamondCard', 'heartCard', 'clubCard'];
const cardSymbols = ['♠️', '♦️', '♥️', '♣️'];
const cardValue = ['1','2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K'];
const GenerateRandomCard = () => {
let cardSuitsRandom = Math.floor(Math.random() *
(cardSuits.length));
let cardValueRandom = Math.floor(Math.random() *
(cardValue.length));
return `<div class="${cardStyles[cardSuitsRandom]}">` +
'<div>' + cardValue[cardValueRandom] + ' ' +
cardSymbols[cardSuitsRandom] + '</div></div>'
};
window.onload = () => {
document.querySelector('#cardMap').innerHTML =
GenerateRandomCard();
}
body {
background-color: green
}
#cardMap {
display: flex;
flex-direction: row;
flex-wrap: wrap;
margin: 80px auto 10px auto;
height: 420px;
width: 360px;
background-color: white;
border-radius: 5px;
}
#cardMap > div {
width: 100%;
padding: 1rem;
}
.allCard {
font-size: 16px;
}
.heartCard {
background-color: #eee;
}
.spadeCard {
background-color: #ccc;
}
.diamondCard {
background-color: #aaa;
}
.clubCard {
background-color: #888;
}
<div id="cardMap" class="allCard"></div>
I'm trying to create a simple app with HTMl, CSS and vanilla JS.
I've got an array, and ant to display its items in a box, with a button below it that gets the average of the array, which should also appear below the button.
So far, the layout has been very difficult, as I'm familiar with core JS and basic HTML, but never worked with scripts before. I can't make the button to be displayed below the array items and in the centre, no matter what I do. For it to appear after the array, I've applied flex box to the body, because I don't know how to create a wrapping html element, although I've seen some threads, don't know how to implement it.
Is there an easy way (avoiding JQuery) of doing this? Can't I just create a wrapping the script?
This is my code so far:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="style.css">
<title>Test</title>
</head>
<body onload="mapping()">
<script>
const array = [2, 3, 4, 5];
function mapping() {
array.map(arrayItem => {
let elements = document.createElement('p');
elements.innerHTML = arrayItem;
document.body.appendChild(elements);
elements.classList.add("numbers");
});
}
</script>
<div class='container'>
<div class='button'>
<p>
<button onClick="average()">Average</button>
</p>
</div>
<div id='val'></div>
</div>
<script>
function average() {
const array = [2, 3, 4, 5]
let count = 0
let val = array.reduce((x, y) => {
if (+y) {
count++
x += +y
}
return x
}, 0)
val = val / count;
document.getElementById('val').innerHTML += val + '<br/>';
}
</script>
</body>
</html>
body {
display: flex;
flex-direction: row-reverse;
justify-content: space-around;
align-items: center;
/* flex-wrap: wrap; */
}
.numbers {
font-size: 5em;
/* color: blue; */
/* text-orientation: unset; */
margin-top: 2em;
}
.button {
padding: 1em;
border: .2em solid red;
margin-top: 20em;
position: inherit;
}
Sorry I'm very junior and can't figure out how to do it.
I'm struggling to fully understand where the issue is, I've gone and made a jsfiddle that I think does what you're interested in.
I have a feeling the problem is the fact that you use display: flex; on the body of the document. I've surrounded the numbers in a separate div element that now has the flex-display options assigned to it.
HTML
const array = [2, 3, 4, 5];
function mapping() {
array.map(arrayItem => {
let elements = document.createElement('p');
elements.innerHTML = arrayItem;
/*
Adding the numbers to the elNumberArray div element in the HTML
*/
document.getElementById("elNumberArray").appendChild(elements);
elements.classList.add("numbers");
});
document.getElementById("elAverageButton").addEventListener("click", average);
}
function average() {
const array = [2, 3, 4, 5]
let count = 0
let val = array.reduce((x, y) => {
if (+y) {
count++
x += +y
}
return x
}, 0)
val = val / count;
document.getElementById('val').innerHTML += val + '<br/>';
}
document.onload = mapping();
body {}
/* display-flex settings are now no longer on the whole body
but set for elNumberArray div element */
#elNumberArray {
display: flex;
flex-direction: row-reverse;
justify-content: space-around;
align-items: center;
/* flex-wrap: wrap; */
}
.numbers {
font-size: 5em;
/* color: blue; */
/* text-orientation: unset; */
margin-top: 2em;
}
.button {
padding: 1em;
border: .2em solid red;
margin-top: 20em;
position: inherit;
}
<div id="elNumberArray">
<!--Numbers are now inserted here-->
</div>
<div class='container'>
<div class='button'>
<p>
<button id="elAverageButton">Average</button>
</p>
</div>
<div id='val'></div>
</div>
The button and average are now displayed below the numbers.
Is this what you were looking for?
You should place the array contents inside span tags instead of p tags.
body {
display: flex;
align-items: center;
/* flex-wrap: wrap; */
}
.numbers {
font-size: 5em;
}
.button {
padding: 1em;
border: .2em solid red;
margin-top: 20em;
}
.container{
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="style.css">
<title>Test</title>
</head>
<body onload="mapping()">
<script>
const array = [2, 3, 4, 5];
function mapping() {
array.map(arrayItem => {
let elements = document.createElement('span');
elements.innerHTML = arrayItem;
document.getElementById("numbers").appendChild(elements);
elements.classList.add("numbers");
});
}
</script>
<span id="numbers" style="margin: 20px;">
</span>
<div class='container'>
<div class='button'>
<p>
<button onClick="average()">Average</button>
</p>
</div>
<div id='val'></div>
</div>
<script>
function average() {
const array = [2, 3, 4, 5]
let count = 0
let val = array.reduce((x, y) => {
if (+y) {
count++
x += +y
}
return x
}, 0)
val = val / count;
document.getElementById('val').innerHTML += val + '<br/>';
}
</script>
</body>
</html>
JSFiddle: http://jsfiddle.net/kru10xgd/11/
const array = [2, 3, 4, 5];
let arrayContainer = document.getElementById('arrayContainer');
(function mapping() {
array.map(arrayItem => {
let element = document.createElement('p');
element.innerHTML = arrayItem;
element.classList.add("numbers");
arrayContainer.appendChild(element);
});
})();
function average() {
let count = 0
let val = array.reduce((x, y) => {
if (+y) {
count++
x += +y
}
return x
}, 0)
val = val / count;
document.getElementById('val').innerHTML += val + '<br/>';
}
.container {
width: 50%;
margin: 0 auto;
text-align: center;
transform: translate(-50%, -50%);
position: absolute;
top: 50%;
left: 50%;
}
#arrayContainer {
display: flex;
justify-content: space-evenly;
border: 1px solid;
}
.numbers {
min-width: 20px;
}
.button {
margin: 20px 0px;
}
<div class='container'>
<div id="arrayContainer"></div>
<div class='button'>
<button onClick="average()">Average</button>
</div>
<div id='val'></div>
</div>
Something like this maybe , you are trying to achieve?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<!-- // <link rel="stylesheet" href="style.css"> -->
<title>Test</title>
<style>
.container{
width: 50%;
margin: 0 auto;
text-align: center;
transform: translate(-50%,-50%);
position: absolute;
top: 50%;
left: 50%;
}
#arrayContainer{
display: flex;
justify-content: space-evenly;
border: 1px solid;
}
.numbers {
min-width: 20px;
}
.button {
margin: 20px 0px;
}
</style>
</head>
<body>
<div class='container'>
<div id="arrayContainer"></div>
<div class='button'>
<button onClick="average()">Average</button>
</div>
<div id='val'></div>
</div>
<script>
const array = [2, 3, 4, 5];
let arrayContainer = document.getElementById('arrayContainer');
(function mapping() {
array.map(arrayItem => {
let element = document.createElement('p');
element.innerHTML = arrayItem;
element.classList.add("numbers");
arrayContainer.appendChild(element);
});
})();
function average() {
let count = 0
let val = array.reduce((x, y) => {
if (+y) {
count++
x += +y
}
return x
}, 0)
val = val / count;
document.getElementById('val').innerHTML += val + '<br/>';
}
</script>
</body>
</html>
I am a newbie to angular JS and having problem in adding the spliced value back to the list.
How cam i do so or can i use any other Angular JS function in place of splice to do the need full.
Below is the code i have do.
{
<!DOCTYPE html>
<html>
<head>
<title>Drag Drop + Remove Element</title>
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootswatch/2.3.1/spruce/bootstrap.min.css">
<style>
[ng-drag] {
width: 100px;
height: 100px;
background: red;
color: white;
text-align: center;
padding-top: 40px;
display: block;
}
[ng-drop] {
background: silver;
text-align: center;
display: block;
position: relative;
padding: 20px;
width: 140px;
height: 140px;
float: left;
}
.draglist {
display: inline-block;
margin: 0 auto;
}
[ng-drag].dragging {
opacity: 0.5;
}
[ng-drag].drag-over {
border: solid 1px red;
}
[ng-drop].drag-enter {
border: solid 5px red;
}
</style>
</head>
<body ng-app="ExampleApp">
<div class="row text-center">
<h1>Drag Drop + Remove Element</h1>
</div>
<div class="row text-center" ng-controller="MainCtrl">
<ul class="draglist">
<li ng-repeat="obj in draggableObjects | limitTo:quantity" ng-drop="true" ng-drop-success="onDropComplete($index, $data,$event)" >
<button type="button" class="close" ng-click="removeElement($index,draggableObjects.length)"><span aria-hidden="true" ng-mouseover>×</span></button>
<div ng-drag="true" ng-drag-data="obj" ng-class="obj.name">
{{obj.name}}
</div>
</li>
</ul>
</div>
<!--<script src="http://code.angularjs.org/1.3.15/angular.min.js"></script>-->
<script src="Angular.js"></script>
<script src="ngDraggable.js"></script>
<script>
angular.module('ExampleApp', ['ngDraggable']).
controller('MainCtrl', function ($scope, $window) {
$scope.draggableObjects = [
{name: 'one'},
{name: 'two'},
{name: 'three'},
{name: 'four'},
{name: 'five'},
{name: 'six'},
{name: 'seven'},
{name: 'eight'},
{name: 'nine'},
{name: 'ten'}
];
$scope.quantity = 3;
$scope.showDelete = false;
$scope.removeElement = function(index, objLength){
console.log("objLength::"+objLength);
$scope.showDelete = true;
if(objLength < 4){
console.log("In if");
// $window.location.reload();
// $scope.draggableObjects;
console.log($scope.draggableObjects);
$scope.draggableObjects = $scope.draggableObjects.concat($scope.draggableObjects);
// angular.forEach($scope.draggableObjects, function(objects) {
// $scope.draggableObjects.push(objects);
//// console.log($scope.draggableObjects);
// });
}
else{
$scope.draggableObjects.splice(index,1);
}
};
$scope.onDropComplete = function (index, obj, evt) {
var otherObj = $scope.draggableObjects[index];
var otherIndex = $scope.draggableObjects.indexOf(obj);
$scope.draggableObjects[index] = obj;
$scope.draggableObjects[otherIndex] = otherObj;
};
});
</script>
</body>
</html>
}
Now what i want to do is once the value get spliced from the $scope.draggableObjects i want to add the spliced data again at the end of the code so that a cycle is continued of all the values in scope.
Any help will be welcomed.
Thanks in advance.
just javascript
$scope.draggableObjects.push(obj) // obj prev removed