Swiper.js: cannot get textarea value in loop mode - javascript

I cannot get the value of an textarea in a looped swiper of Swiper.js.
Here's what I did.
I defined a swiper with a single slide and put a textarea in it. (id="aaa", one and only textarea)
I defined a function "getValue()" that shows the value of the textarea. (using getElementById(), console.log())
function getValue(id){
var element = document.getElementById(id);
var value = element.value;
console.log(value);
}
I enabled the loop mode of the swiper.
// Swiper Setting
var swiper = new Swiper('.swiper-container', {
allowTouchMove: false,
loop: true,
I executed the function with a button, and it returns "" (empty string)
Here's the results of my experiments
When the loop is disabled, the function returns the proper text in the textarea.
When the swiper has multiple slides, the function returns "" only for textareas in the last slide.
Here's the full code that replicates the problem.
https://jsfiddle.net/mjn7d385/
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>test</title>
<!-- Link Swiper's CSS -->
<link rel="stylesheet" href="https://unpkg.com/swiper/swiper-bundle.css">
<link rel="stylesheet" href="https://unpkg.com/swiper/swiper-bundle.min.css">
<!-- Demo styles -->
<style>
html,
body {
position: relative;
height: 100%;
}
body {
background: #eee;
font-size: 14px;
color: #000;
margin: 0;
padding: 0;
}
.swiper-container {
width: 100%;
height: 100%;
}
.swiper-slide {
text-align: center;
font-size: 18px;
background: #fff;
/* Center slide text vertically */
display: -webkit-box;
display: -ms-flexbox;
display: -webkit-flex;
display: flex;
-webkit-box-pack: center;
-ms-flex-pack: center;
-webkit-justify-content: center;
justify-content: center;
-webkit-box-align: center;
-ms-flex-align: center;
-webkit-align-items: center;
align-items: center;
}
.swiper-pagination-bullet {
width: 20px;
height: 20px;
text-align: center;
line-height: 20px;
font-size: 12px;
color: #000;
opacity: 1;
background: rgba(0, 0, 0, 0.2);
}
.swiper-pagination-bullet-active {
color: #fff;
background: #007aff;
}
</style>
</head>
<body>
<!-- Swiper -->
<div class="swiper-container">
<div class="swiper-wrapper">
<div class="swiper-slide" id="page1">
<textarea name="aaa" id="aaa" cols="40" rows="5"></textarea>
<button onclick="getValue('aaa');">Check Values</button>
</div>
</div>
<!-- Add Pagination -->
<div class="swiper-pagination"></div>
<!-- Add Arrows -->
<div class="swiper-button-next"></div>
<div class="swiper-button-prev"></div>
</div>
<!-- Swiper JS -->
<script src="https://unpkg.com/swiper/swiper-bundle.js"></script>
<script src="https://unpkg.com/swiper/swiper-bundle.min.js"></script>
<script>
// Swiper Setting
var swiper = new Swiper('.swiper-container', {
allowTouchMove: false,
loop: true,
pagination: {
el: '.swiper-pagination',
renderBullet: function (index, className) {
return '<span class="' + className + '">' + (index + 1) + '</span>';
},
},
navigation: {
nextEl: '.swiper-button-next',
prevEl: '.swiper-button-prev',
},
});
function getValue(id){
var element = document.getElementById(id);
var value = element.value;
console.log(value);
}
</script>
</body>
</html>
How can I get the value of the textarea in a looped swiper? Please let me know if you have any solutions for this.
Thank you in advance.

The problem here is that Id's can't be duplicated in the same document, and this control duplicates the Template Slide and its contents, so "aaa" is declared multiple times. One solution could be this one:
Modify Slide Template to be like this:
<div class="swiper-slide" id="page1">
<textarea cols="40" rows="5"></textarea>
<button onclick="getValue(this);">Check Values</button>
</div>
Here, getValue() is called using the Caller object (Button) as argument.
Now, getValue function is modified to this:
function getValue(obj){
var element = obj.parentElement.getElementsByTagName("textarea")[0];
var value = element.value;
console.log(value);
}
In this function, we locate the parent object of the button, which is the DIV, and then we get the first textarea object that contains. That's it!
Have a look to the proposed solution in JSFiddle:
https://jsfiddle.net/s0Lw2yeg/1/
I hope this will be useful.

Related

Fetch and display API information using Javascript

fetch("https://wptavern.com/wp-json/wp/v2/posts")
.then((response) => {
if (response.ok) {
return response.json();
} else {
throw new Error("NETWORK RESPONSE ERROR");
}
})
.then((data) => {
console.log(data);
displayDetails(data);
})
.catch((error) => console.error("FETCH ERROR:", error));
//*function displayDetails(data) {
const informations = data[0]; //create a variable and store the array you need to access
const informationsDiv = document.getElementById("informations"); //create a vaiable with a div to display the data
const informationsTitle = informations.title.rendered; //create a variable and access the specific data, title in this case
const heading = document.createElement("h1"); //create a heading variable h1
heading.innerHTML = informationsTitle;
informationsDiv.appendChild(heading);
const informationsImage = document.createElement("img"); //create a variable for the image
informationsImage.src = informations.episode_featured_image; //specify the image source inside the array
informationsDiv.appendChild(informationsImage);
const informationsDate = informations.date; //create a variable and access the date
const heading1 = document.createElement("p"); //create a variable to use in the DOM
heading1.innerHTML = informationsDate;
informationsDiv.appendChild(heading1); //append the data
//}
function displayDetails(data) {
let informationsDiv = document.getElementById("informations");
for(var i = 0; i < data.length; i++) {
let informations = data[i];
let informationsTitle = informations.title.rendered;
let heading = document.createElement("h1");
heading.innerHTML = informationsTitle;
informationsDiv.appendChild(heading);
let informationsImage = document.createElement("img");
informationsImage.src = informations.episode_featured_image;
informationsDiv.appendChild(informationsImage);
let informationsDate = informations.date;
let heading1 = document.createElement("p");
heading1.innerHTML = informationsDate;
informationsDiv.appendChild(heading1);
}
}
.swiper {
margin: auto;
padding: auto;
width:100%;
height: 100%;
}
.swiper-slide {
text-align: center;
font-size-adjust: 15px;
background: #fff;
/* Center slide text vertically */
display: -webkit-box;
display: -ms-flexbox;
display: -webkit-flex;
display: flex;
-webkit-box-pack: center;
-ms-flex-pack: center;
-webkit-justify-content: center;
justify-content: center;
-webkit-box-align: center;
-ms-flex-align: center;
-webkit-align-items: center;
align-items: center;
background-color: #c2bdd1;
}
.swiper-slide img {
display: block;
width: 100%;
height: 100%;
object-fit: cover;
}
html,body {
height:100%;
background: #eee;
font-family: Helvetica Neue, Helvetica, Arial, sans-serif;
font-size: 14px;
color: #000;
margin: auto;
padding: 0;
}
#informations{
max-width: 700px;
text-align: center;
padding: 30px 30px 12px 30px;
color: rgb(252, 252, 252);
background-color: #7766d7;
border: 4px solid #9387f2;
border-radius: 5px;
}
<!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>
</head>
<body>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/swiper#8/swiper-bundle.min.css" />
<link rel="stylesheet" href="style.css" />
<!--Script-->
<script src="script/script.js"></script>
<!-- Swiper -->
<div class="swiper mySwiper">
<div class="swiper-wrapper ">
<div class="swiper-slide">
<div id="informations"></div>
</div>
<div class="swiper-slide">Slide 2</div>
<div class="swiper-slide">Slide 3</div>
<div class="swiper-slide">Slide 4</div>
<div class="swiper-slide">Slide 5</div>
<div class="swiper-slide">Slide 6</div>
<div class="swiper-slide">Slide 7</div>
<div class="swiper-slide">Slide 8</div>
<div class="swiper-slide">Slide 9</div>
</div>
<div class="swiper-button-next"></div>
<div class="swiper-button-prev"></div>
</div>
<!-- Swiper JS -->
<script src="https://cdn.jsdelivr.net/npm/swiper/swiper-bundle.min.js"></script>
<!-- Initialize Swiper -->
<script>
var swiper = new Swiper(".mySwiper", {
allowTouchMove: true,
navigation: {
nextEl: ".swiper-button-next",
prevEl: ".swiper-button-prev",
},
keyboard: {
enabled: true,
}
});
</script>
</body>
</html>
I am building a carousel where on every page I want to display information (title, image, date) taken from this API: https://wptavern.com/wp-json/wp/v2/posts
So far I managed to write this script:
fetch("https://wptavern.com/wp-json/wp/v2/posts")
.then((response) => {
if (response.ok) {
return response.json();
} else {
throw new Error("NETWORK RESPONSE ERROR");
}
}).then((data) => {
console.log(data);
displayDetails(data);
}).catch((error) => console.error("FETCH ERROR:", error));
function displayDetails(data) {
const informations = data[0];
const informationsDiv = document.getElementById("informations");
const informationsTitle = informations.title.rendered;
const heading = document.createElement("h1");
heading.innerHTML = informationsTitle;
informationsDiv.appendChild(heading);
const informationsImage = document.createElement("img");
informationsImage.src = informations.episode_featured_image;
informationsDiv.appendChild(informationsImage);
const informationsDate = informations.date;
const heading1 = document.createElement("p");
heading1.innerHTML = informationsDate;
informationsDiv.appendChild(heading1);
}
The problem is, this works only on the first slide. If I try to call the same function for slide n2 and change all the variables and the start of the array, from data[0] to data[1], then slide n1 doesn't showcase info anymore, but slide n2 does!
I also added a picture of HTM because I don't know how to format code properly and stack overflow is not allowing me to post the question.
The end result should display all the recent articles provided by the API.
Thank you for your time.
I've updated your code, this should work:
fetch("https://wptavern.com/wp-json/wp/v2/posts")
.then((response) => {
if (response.ok) {
return response.json();
} else {
throw new Error("NETWORK RESPONSE ERROR");
}
})
.then((data) => {
console.log(data);
displayDetails(data);
})
.catch((error) => console.error("FETCH ERROR:", error));
function displayDetails(data) {
let informationsDiv = document.getElementById("slider");
for(var i = 0; i < data.length; i++) {
var slide = document.createElement("div");
slide.className = "swiper-slide";
var slideContent = document.createElement("div");
slideContent.className = "informations";
let informations = data[i];
let informationsTitle = informations.title.rendered;
let heading = document.createElement("h1");
heading.innerHTML = informationsTitle;
slideContent.appendChild(heading);
let informationsImage = document.createElement("img");
informationsImage.src = informations.episode_featured_image;
slideContent.appendChild(informationsImage);
let informationsDate = informations.date;
let heading1 = document.createElement("p");
heading1.innerHTML = informationsDate;
slideContent.appendChild(heading1);
slide.appendChild(slideContent);
informationsDiv.appendChild(slide);
}
}
.swiper {
margin: auto;
padding: auto;
width:100%;
height: 100%;
}
.swiper-slide {
text-align: center;
font-size-adjust: 15px;
background: #fff;
/* Center slide text vertically */
display: -webkit-box;
display: -ms-flexbox;
display: -webkit-flex;
display: flex;
-webkit-box-pack: center;
-ms-flex-pack: center;
-webkit-justify-content: center;
justify-content: center;
-webkit-box-align: center;
-ms-flex-align: center;
-webkit-align-items: center;
align-items: center;
background-color: #c2bdd1;
}
.swiper-slide img {
display: block;
width: 100%;
height: 100%;
object-fit: cover;
}
html,body {
height:100%;
background: #eee;
font-family: Helvetica Neue, Helvetica, Arial, sans-serif;
font-size: 14px;
color: #000;
margin: auto;
padding: 0;
}
.informations{
max-width: 700px;
text-align: center;
padding: 30px 30px 12px 30px;
color: rgb(252, 252, 252);
background-color: #7766d7;
border: 4px solid #9387f2;
border-radius: 5px;
}
<!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>
</head>
<body>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/swiper#8/swiper-bundle.min.css" />
<link rel="stylesheet" href="style.css" />
<!--Script-->
<script src="script/script.js"></script>
<!-- Swiper -->
<div class="swiper mySwiper">
<div class="swiper-wrapper" id="slider">
</div>
<div class="swiper-button-next"></div>
<div class="swiper-button-prev"></div>
</div>
<!-- Swiper JS -->
<script src="https://cdn.jsdelivr.net/npm/swiper/swiper-bundle.min.js"></script>
<!-- Initialize Swiper -->
<script>
var swiper = new Swiper(".mySwiper", {
allowTouchMove: true,
navigation: {
nextEl: ".swiper-button-next",
prevEl: ".swiper-button-prev",
},
keyboard: {
enabled: true,
}
});
</script>
</body>
</html>
It basically creates a new swiper-slide for each result of the API, and appends it to your slider.

Adding Images Dynamically into Swiper JS not working

I have a page where images need to showed in slider.
// Initializing the Swiper
var swiper = new Swiper(".mySwiper", {
loop: true,
spaceBetween: 10,
slidesPerView: 4,
freeMode: true,
autoplay: {
delay: 1000,
disableOnInteraction: false,
},
watchSlidesProgress: true,
});
var swiper2 = new Swiper(".mySwiper2", {
loop: true,
spaceBetween: 10,
autoplay: {
delay: 1000,
disableOnInteraction: false,
},
navigation: {
nextEl: ".swiper-button-next",
prevEl: ".swiper-button-prev",
},
thumbs: {
swiper: swiper,
},
});
$("body").keydown(function (e) {
if (e.keyCode == 37) { // top
swiper.slidePrev();
}
else if (e.keyCode == 39) { // bottom
swiper.slideNext();
}
});
let image_list = ["https://swiperjs.com/demos/images/nature-1.jpg", "https://swiperjs.com/demos/images/nature-2.jpg", "https://swiperjs.com/demos/images/nature-3.jpg", "https://swiperjs.com/demos/images/nature-4.jpg", "https://swiperjs.com/demos/images/nature-5.jpg", "https://swiperjs.com/demos/images/nature-6.jpg", "https://swiperjs.com/demos/images/nature-7.jpg",
"https://swiperjs.com/demos/images/nature-8.jpg",
"https://swiperjs.com/demos/images/nature-9.jpg",
"https://swiperjs.com/demos/images/nature-10.jpg"]
// Adding Images
for (i = 0; i < image_list.length; i++) {
let div = '<div class="swiper-slide"><img src="' + image_list[i] + '" alt=""/></div>';
$("#large-img").append(div);
$("#small-img").append(div);
}
/* SWIPER JS */
.swiper {
width: 100%;
height: 100%;
}
.swiper-slide {
text-align: center;
font-size: 18px;
background: #fff;
/* Center slide text vertically */
display: -webkit-box;
display: -ms-flexbox;
display: -webkit-flex;
display: flex;
-webkit-box-pack: center;
-ms-flex-pack: center;
-webkit-justify-content: center;
justify-content: center;
-webkit-box-align: center;
-ms-flex-align: center;
-webkit-align-items: center;
align-items: center;
}
.swiper-slide img {
display: block;
width: 100%;
height: 100%;
object-fit: cover;
}
.swiper {
width: 100%;
height: 10rem;
margin-left: auto;
margin-right: auto;
}
.swiper-slide {
background-size: cover;
background-position: center;
}
.mySwiper2 {
height: 27rem;
width: 100%;
}
.mySwiper {
height: 20%;
box-sizing: border-box;
padding: 10px 0;
}
.mySwiper .swiper-slide {
width: 25%;
height: 100%;
opacity: 0.4;
}
.mySwiper .swiper-slide-thumb-active {
opacity: 1;
}
.swiper-slide img {
display: block;
width: 100%;
height: 100%;
object-fit: cover;
}
<link rel="stylesheet" href="//code.jquery.com/ui/1.13.0/themes/base/jquery-ui.css">
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<link rel="stylesheet" href="https://unpkg.com/swiper/swiper-bundle.css" />
<div class="container-fluid" style="padding: 0;">
<div class="row g-0 justify-content-center mt-5">
<div class="col-md-12">
<div style="--swiper-navigation-color: #fff; --swiper-pagination-color: #fff" class="swiper mySwiper2">
<div class="swiper-wrapper" id="large-img">
<!-- Images coming from the backend through javascript -->
</div>
<div class="swiper-button-next"></div>
<div class="swiper-button-prev"></div>
</div>
<div thumbsSlider="" class="swiper mySwiper">
<div class="swiper-wrapper" id="small-img">
<!-- Images coming from the backend through javascript -->
</div>
</div>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.6.0.js"
integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"
integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1"
crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/js/bootstrap.bundle.min.js"
integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p"
crossorigin="anonymous"></script>
<script src="https://unpkg.com/swiper/swiper-bundle.min.js"></script>
When I am adding the Images Dynamically through the javascript into the HTML template, the SWIPER doesnt work. I am actually passing the media url of the image in the img.src attribute as I am using Django as the backend. No matter from where you pass the image url, it doesnt work.
**UPDATE** : In running this code, it works on the full screen mode (Only the autoplay and next and previous button. Clicking on the thumbnail isnt working) and in the small window which opens when pressing the Run Snippet, the Swiper.js doesnt work. The problem in the small window is similar to what I am seeing in my website.
You should load the Swiper after loading the images, this way it can use the images when initializing. Maybe it would be a good way to check the Swipper documentation, I saw it has some lazy loading parameters which could possibly help solve this differently.
doc:
https://swiperjs.com/swiper-api#lazy-loading

swiper slider - swiping as one slide, but CSS is included

How come swiper slider is sliding all my divs as one? Did the library change?
Below is my example:
var swiper = new Swiper('.swiper-container', {
autoplay:false,
direction: "horizontal",
loop:false,
pagination: {
el: '.product-image-thumbs .swiper-pagination',
clickable: true,
bulletActiveClass: 'active'
}
});
.swiper-slide {
background-color: green;
width: 300px;
height: 100px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Swiper/5.4.5/js/swiper.min.js"></script>
<link href="https://unpkg.com/swiper/css/swiper.min.css" rel="stylesheet"/>
<div class="swiper-container">
<div class="swiper-wrapper">
<div class="swiper-slide"></div>
<div class="swiper-slide"></div>
<div class="swiper-slide"></div>
<div class="swiper-slide"></div>
</div>
<div class="swiper-pagination"></div>
</div>
you can see that all the slides are in one slide?
as per these answers
Swiper Slider puts all slides in one slide
Swiper slider does not swipe slides on mobile devices
They all say to include the CSS file, but you can see that my CSS file is included, and the linked answers are now exhibiting the same behavior as mine.
Did swiper change?
Yes might be links are outdated, refer swiperjs for latest version and try this links:
// CSS
<link rel="stylesheet" href="https://unpkg.com/swiper/swiper-bundle.min.css">
// JS
<script src="https://unpkg.com/swiper/swiper-bundle.min.js"></script>
There are few quick fixes:
Pagination: Property el will allow comma separated classes, that you have separated with spaces
BulletActiveClass: Currently there are no style on active class that you have specified, so commented for now
Script Location: Always try to use scripts at the end of body tag, as i have add in below example
CSS: I have added css from swiper example, because here without css slider was corrupted
Your working example with above fixes:
var swiper = new Swiper('.swiper-container', {
autoplay:false,
direction: "horizontal",
loop:false,
pagination: {
el: '.product-image-thumbs, .swiper-pagination',
clickable: true,
// bulletActiveClass: 'active'
}
});
html,
body {
position: relative;
height: 100%;
}
body {
background: #eee;
font-family: Helvetica Neue, Helvetica, Arial, sans-serif;
font-size: 14px;
color: #000;
margin: 0;
padding: 0;
}
.swiper-container {
width: 100%;
height: 100%;
}
.swiper-slide {
text-align: center;
font-size: 18px;
background: #fff;
/* Center slide text vertically */
display: -webkit-box;
display: -ms-flexbox;
display: -webkit-flex;
display: flex;
-webkit-box-pack: center;
-ms-flex-pack: center;
-webkit-justify-content: center;
justify-content: center;
-webkit-box-align: center;
-ms-flex-align: center;
-webkit-align-items: center;
align-items: center;
}
<link rel="stylesheet" href="https://unpkg.com/swiper/swiper-bundle.min.css">
<div class="swiper-container">
<div class="product-image-thumbs"></div>
<div class="swiper-wrapper">
<div class="swiper-slide">Slide 1</div>
<div class="swiper-slide">Slide 2</div>
<div class="swiper-slide">Slide 3</div>
<div class="swiper-slide">Slide 4</div>
</div>
<div class="swiper-pagination"></div>
</div>
<script src="https://unpkg.com/swiper/swiper-bundle.min.js"></script>

Change page sections on scroll

I want to change sections on scroll, to kill the overflow of a single page website and change the sections that have 100% height on scroll. I tried using the:
https://github.com/hellsan631/angular-fullpage.js
but cannot make it work. When I follow all the instructions I get the following errors:
Error: [$compile:nonassign] http://errors.angularjs.org/1.6.6/$compile/nonassign?p0=undefined&p1=options&p2=fullPage
angular.js:14700 TypeError: Cannot set property 'afterRender' of undefined
angular.js:14700 TypeError: Cannot set property 'afterRender' of undefined
I also tried using https://github.com/alvarotrigo/fullPage.js, no errors but nothing happens.
Anyone has a different solution, or a way to fix this one? Thanks.
Here is a Swiper content sliding plugin, similar to fullpage.js:
http://idangero.us/swiper/demos/20-mousewheel-control.html
You can scroll it with mousewheel, mouse (desktop touch emulation), keypad (on desktop) and finger (on touch devices). Plus there is a non-JQuery version available.
Additionally, you can even configure it to change page background colors, like:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Swiper demo</title>
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/Swiper/3.3.1/css/swiper.min.css">
<style>
html, body {
position: relative;
height: 100%;
}
body {
background: #eee;
font-family: Helvetica Neue, Helvetica, Arial, sans-serif;
font-size: 14px;
color:#000;
margin: 0;
padding: 0;
}
.swiper-container {
width: 100%;
height: 100%;
margin-left: auto;
margin-right: auto;
}
.swiper-slide {
text-align: center;
font-size: 18px;
background: transparent;
/* Center slide text vertically */
display: -webkit-box;
display: -ms-flexbox;
display: -webkit-flex;
display: flex;
-webkit-box-pack: center;
-ms-flex-pack: center;
-webkit-justify-content: center;
justify-content: center;
-webkit-box-align: center;
-ms-flex-align: center;
-webkit-align-items: center;
align-items: center;
}
body {
transition: background-color .5s ease-in-out;
}
body.red {
background-color: #f40;
}
body.orange {
background-color: #f90;
}
body.yellow {
background-color: #fe0;
}
</style>
</head>
<body>
<!-- Slider main container -->
<div class="swiper-container">
<div class="swiper-wrapper">
<div class="swiper-slide" data-bg="red">Slide 1</div>
<div class="swiper-slide" data-bg="orange">Slide 2</div>
<div class="swiper-slide" data-bg="yellow">Slide 3</div>
</div>
<div class="swiper-pagination"></div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Swiper/3.3.1/js/swiper.min.js"></script>
<script>
var body = document.body;
body.className = 'red';
var slider = new Swiper ('.swiper-container', {
pagination: '.swiper-pagination',
direction: 'vertical',
slidesPerView: 1,
paginationClickable: true,
spaceBetween: 30,
mousewheelControl: true,
onSlideChangeStart: function (swiper) {
var currentSlide = swiper.slides[ swiper.activeIndex ];
body.className = currentSlide.getAttribute( 'data-bg' );
console.log( currentSlide.getAttribute( 'data-bg' ) );
},
});
</script>
</body>
</html>
DEMO

How to give button a default input value

I've put together a Codepen by mashing together a couple different examples by other people in order to get something pretty close to what I'm actually looking for. The only problem I have now is that I'd like to give the button in my example a default value of 3, rather than have somebody input a value of their choice, so that when the button is clicked, three images are selected at random.
I've tried
$(shuffle($all).slice(0, $("input").val(3))).addClass("selected");
whilst commenting out the input type, but that didn't work.
Thanks in advance for any tips!
http://codepen.io/asyi/pen/XMVwVg
<head>
<link rel="stylesheet" type="text/css" href="styles/style.css"> <title>This Webpage</title>
</head>
<body>
<div id="container">
<div class="square">
</div>
<div class="square">
</div>
<div class="square">
</div>
<div class="square">
</div>
</div>
<button>Click to win!:</button>
<input type="text" size="3" value="3" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="scripts/script.js"></script>
</body>
CSS
* {
box-sizing: border-box;
}
#container {
width: 100%;
display: flex;
flex-direction: row;
flex-wrap: wrap;
}
#container > div {
width: 50%;
height: 20vw;
border: white 10px solid;
}
.selected {
background: tan;
border: red 2px solid;
}
.square {
background-image: url('https://placebear.com/300/200');
background-repeat: no-repeat;
background-size: 85%;
background-position: center;
}
jQuery
$(document).ready(function(){
function shuffle(array) {
var m = array.length, t, i;
// While there remain elements to shuffle…
while (m) {
// Pick a remaining element…
i = Math.floor(Math.random() * m--);
// And swap it with the current element.
t = array[m];
array[m] = array[i];
array[i] = t;
}
return array;
}
$(function() {
$("button").click(function() {
var $all = $(".square").removeClass("selected");
$(shuffle($all).slice(0, $("input").val())).addClass("selected");
});
});
});

Categories