Bootstrap Align horizontally data from API - javascript

I have a carousel and within that carousel I have cards in it and each card should have at least horizontally aligned to it but in my case it aligns vertically.
The data are from the API itself.
/*
container.innerText = "It's working!\n\n";
container.innerText += 'Found sample products:\n';
products.forEach(product => (container.innerText += `- ${product.title}\n`));
*/
var products = [
{
"imageUrl": "http://lorempixel.com/g/400/200",
"title": "CANDECOR"
},
{
"imageUrl": "http://lorempixel.com/g/400/200",
"title": "ZOLAREX"
},
{
"imageUrl": "http://lorempixel.com/g/400/200",
"title": "HATOLOGY"
},
{
"imageUrl": "http://lorempixel.com/g/400/200",
"title": "EGYPTO"
},
{
"imageUrl": "http://lorempixel.com/g/400/200",
"title": "BULLZONE"
},
{
"imageUrl": "http://lorempixel.com/g/400/200",
"title": "NIKUDA"
}
];
var countFirstThree = true;
var isCardSet = true;
var setCount = 1;
for (var i = 1; i < products.length; i++) {
if (isCardSet) {
$('.carousel-inner').append(insertCarouselItem(countFirstThree, setCount));
isCardSet = false;
}
if (i % 3 == 0) {
$('#set-' + setCount).append(insertCards(products[i - 1].id, products[i - 1].imageUrl, products[i - 1].title));
$('#set-' + setCount).append('</div>');
countFirstThree = false;
isCardSet = true;
setCount++;
} else {
$('#set-' + setCount).append(insertCards(products[i - 1].id, products[i - 1].imageUrl, products[i - 1].title));
}
}
function getUrlImage(url) {
const host = 'http://localhost:8181';
return "http://lorempixel.com/g/400/200";
}
function insertCarouselItem(isActive, set) {
var active = isActive ? ' active' : '';
var result = `<div id="set-${set}" class="carousel-item${active}">`;
return result;
}
function insertCards(id, imageUrl, title) {
var result = `
<div id="${id}" class="card" style="width: 300px;">
<img class="card-img-top" src="${getUrlImage(imageUrl)}">
<div class="card-body">
<h3 class="card-title">${title}</h3>
<button class="btn btn-primary">Add to cart</button>
</div>
</div>`;
return result;
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<div class="container-fluid">
<div id="productCarousel" class="carousel slide" data-ride="carousel" data-interval="false">
<div class="carousel-inner">
</div>
<a class="carousel-control-prev" href="#productCarousel" role="button" data-slide="prev">
<span class="carousel-control-prev-icon" aria-hidden="true"></span>
<span class="sr-only">Previous</span>
</a>
<a class="carousel-control-next" href="#productCarousel" role="button" data-slide="next">
<span class="carousel-control-next-icon" aria-hidden="true"></span>
<span class="sr-only">Next</span>
</a>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
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://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"
integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM"
crossorigin="anonymous"></script>
but the result that I made is like this:
What I want to achieve is that, I want the cards aligned horizontally.

Try adding d-flex to your carousel-inner div
p {
background: red;
}
.carousel-item {
display: block !important;
float: none !important;
width: auto !important;
margin-right: 0 !important;
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<div class="container-fluid">
<div class="carousel slide">
<div class="carousel-inner d-flex">
<div class="carousel-item">
<div id="123" class="card" style="width: 300px;">
<img class="card-img-top" src="${getUrlImage(imageUrl)}">
<div class="card-body">
<h3 class="card-title">Title</h3>
<button class="btn btn-primary">Add to cart</button>
</div>
</div>
</div>
<div class="carousel-item">
<div id="321" class="card" style="width: 300px;">
<img class="card-img-top" src="${getUrlImage(imageUrl)}">
<div class="card-body">
<h3 class="card-title">Title</h3>
<button class="btn btn-primary">Add to cart</button>
</div>
</div>
</div>
</div>
</div>
</div>
`

Related

How to show specific page views using google analytics api using html and javascript?

Currently i am working in a project in which i require specific page views, users and sessions. I have configured out how to fetch it for the whole website using google analytics data api and now i am curious to know about how to do it for specific page.
Below i am attaching my html and js code.
HTML CODE
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta
name="viewport"
content="width=device-width, initial-scale=1, shrink-to-fit=no"
/>
<meta http-equiv="x-ua-compatible" content="ie=edge" />
<title>Google Analtyics</title>
<!-- Font Awesome -->
<link
rel="stylesheet"
href="https://use.fontawesome.com/releases/v5.11.2/css/all.css"
/>
<!-- Google Fonts Roboto -->
<link
rel="stylesheet"
href="https://fonts.googleapis.com/css2?family=Roboto:wght#300;400;500;700&display=swap"
/>
<!-- MDB UI KIT -->
<link rel="stylesheet" href="css/mdb.min.css" />
<!-- Custom styles -->
<style></style>
</head>
<body style="background-color: hsl(0, 0%, 96%)">
<!--Main Navigation-->
<header class="mb-10">
<!-- Navbar-->
<nav
class="navbar navbar-expand-lg navbar-light bg-white shadow-2 fixed-top"
>
<div
class="
container-fluid
justify-content-center justify-content-md-between
"
>
<!-- Right elements -->
<ul class="navbar-nav flex-row d-none d-md-flex">
<li class="nav-item me-3 me-lg-1">
<button
id="sign-in-btn"
type="button"
class="btn btn-primary btn-rounded"
style="display: none"
onclick="signIn()"
>
Login
</button>
</li>
<li class="nav-item me-3 me-lg-1">
<button
id="sign-out-btn"
type="button"
class="btn btn-primary btn-rounded"
style="display: none"
onclick="signOut()"
>
Logout
</button>
</li>
<li class="nav-item me-3 me-lg-1">
<button
type="button"
class="btn btn-primary btn-rounded"
style="display: none"
onclick="loadData()"
>
Load Data
</button>
</li>
</ul>
<!-- Right elements -->
</div>
</nav>
<!-- Navbar -->
</header>
<!--Main Navigation-->
<!--Main layout-->
<main>
<div class="container">
<!--Section: Design Block-->
<section class="mb-8">
<h3 class="mb-7 text-center fw-bold">Last 7 days</h3>
<div class="row">
<div class="col-md-4 mb-4 mb-md-0">
<!-- Card -->
<div class="card">
<div
class="
card-body
d-flex
justify-content-start
align-items-center
"
>
<div
class="
bg-primary
text-white
rounded-4
d-flex
justify-content-center
align-items-center
"
style="width: 50px; height: 50px"
>
<i class="fas fa-users fa-lg"></i>
</div>
<div class="ms-3">
<p class="text-muted mb-1">Users</p>
<p class="mb-0">
<span id="displayUsers" class="h4 me-2"></span>
</p>
</div>
</div>
</div>
<!-- Card -->
</div>
<div class="col-md-4 mb-4 mb-md-0">
<!-- Card -->
<div class="card">
<div
class="
card-body
d-flex
justify-content-start
align-items-center
"
>
<div
class="
bg-primary
text-white
rounded-4
d-flex
justify-content-center
align-items-center
"
style="width: 50px; height: 50px"
>
<i class="fas fa-file fa-lg"></i>
</div>
<div class="ms-3">
<p class="text-muted mb-1">Page views</p>
<p class="mb-0">
<span id="displayPageViews" class="h4 me-2"></span>
</p>
</div>
</div>
</div>
<!-- Card -->
</div>
<div class="col-md-4">
<!-- Card -->
<div class="card">
<div
class="
card-body
d-flex
justify-content-start
align-items-center
"
>
<div
class="
bg-primary
text-white
rounded-4
d-flex
justify-content-center
align-items-center
"
style="width: 50px; height: 50px"
>
<i class="fas fa-chart-line fa-lg"></i>
</div>
<div class="ms-3">
<p class="text-muted mb-1">Sessions</p>
<p class="mb-0">
<span id="displaySessions" class="h4 me-2"></span>
</p>
</div>
</div>
</div>
<!-- Card -->
</div>
</div>
</section>
<!--Section: Design Block-->
</div>
</main>
<!--Main layout-->
<!--Footer-->
<footer></footer>
<!--Footer-->
</body>
<!-- MDB ESSENTIAL -->
<script type="text/javascript" src="js/mdb.min.js"></script>
<!-- Google API -->
<script src="https://apis.google.com/js/api.js"></script>
<!-- easyData - Google Analtyics -->
<script type="text/javascript" src="js/easyData-google-analtyics.js"></script>
<!--Fetching data-->
<script>
// Your Client ID
const CLIENT_ID = "";
function loadData() {
// Your GA property ID
const propertyId = "";
const startDate = "7daysAgo";
const endDate = "today";
const metrics = [
{ name: "activeUsers" },
{ name: "screenPageViews" },
{ name: "sessions" },
];
const query = {
dateRanges: [{ startDate, endDate }],
metrics: metrics,
};
runReport(propertyId, query, displayResult);
}
function displayResult(response) {
document.getElementById("displayUsers").innerHTML =
response.result.rows[0].metricValues[0].value;
document.getElementById("displayPageViews").innerHTML =
response.result.rows[0].metricValues[1].value;
document.getElementById("displaySessions").innerHTML =
response.result.rows[0].metricValues[2].value;
}
// Login buttons
document.addEventListener("gapi-loaded", (e) => {
if (isSignedIn()) {
document.getElementById("sign-out-btn").style.display = "block";
document.getElementById("sign-in-btn").style.display = "none";
loadData();
} else {
document.getElementById("sign-in-btn").style.display = "block";
document.getElementById("sign-out-btn").style.display = "none";
}
});
</script>
</html>
JAVASCRIPT CODE
// Google Analytics
const GA_SCOPE = "https://www.googleapis.com/auth/analytics.readonly";
const GA_API_URL = "https://analyticsdata.googleapis.com/$discovery/rest?version=v1beta";
gapi.load("client:auth2", function () {
gapi.auth2.init({ client_id: CLIENT_ID }).then(() => document.dispatchEvent(new Event('gapi-loaded')));
});
function signIn(scope = GA_SCOPE) {
return gapi.auth2.getAuthInstance().signIn({ scope }).then(() => {
setCookie('guser-loggedin', 'true', 1);
location.reload();
}, (e) => console.error(e));
}
function signOut() {
return gapi.auth2.getAuthInstance().signOut().then(() => {
setCookie('guser-loggedin', 'true', -1);
location.reload();}, (e) => console.error(e));
}
function loadClient(apiPath = GA_API_URL) {
return gapi.client.load(apiPath);
}
function runReport(propertyId, query, cb = function (res) { console.log(res); }, err = function (err) { console.error(err); }) {
return loadClient().then(() => gapi.client.analyticsdata.properties
.runReport({
property: "properties/" + propertyId,
resource: query
})
.then(cb, err));
}
function isSignedIn() {
if (getCookie('guser-loggedin') === 'true') return true;
return false;
}
function setCookie(cname = 'guser-loggedin', cvalue, exdays) {
const d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
let expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
function getCookie(cname) {
let name = cname + "=";
let ca = document.cookie.split(';');
for(let i = 0; i < ca.length; i++) {
let c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}

Measure image time in a Boostrap carousel

This might be a remarkable stupid question. I use setInterval to measure the total time that a user looks at a specific image in a bootstrap carousel, the total interval time, and the current index of the image.
In addition, I want to measure the time between the event when the picture slides into view and when the picture slides out of view in the bootstrap carousel. Not only the total time but also the time of the single event when the picture is visible.
Until now, I could not figure out a way to achieve my goal without completely changing the whole script. I thought about using setTimeout().
var intervalTime = 10;
var timesMilliseconds = {
0: 0
};
var intervalMilliseconds = 0;
var currentSlideIndex = 0;
var interval;
var currentIndex;
var currentTotalTime;
var currentIntervalTime;
var search_behavior = {};
$('document').ready(function() {
interval = setInterval(function() {
if (timesMilliseconds.hasOwnProperty(currentSlideIndex)) {
timesMilliseconds[currentSlideIndex] += intervalTime;
intervalMilliseconds += intervalTime;
} else {
timesMilliseconds[currentSlideIndex] = intervalTime;
intervalMilliseconds += intervalTime;
}
}, intervalTime);
$('#carouselExampleControls').on('slide.bs.carousel', function(event) {
currentIndex = currentSlideIndex.toString();
currentTotalTime = timesMilliseconds[currentSlideIndex].toString();
currentIntervalTime = intervalMilliseconds;
currentSlideIndex = event.to;
search_behavior = {
current_index: currentIndex,
current_interval: currentIntervalTime,
total_time_index: currentTotalTime,
}
console.log(search_behavior)
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-U1DAWAznBHeqEIlVSCgzq+c9gqGAJn5c/t99JyeKa9xxaYpSvHU5awsuZVVFIhvj" crossorigin="anonymous"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-KyZXEAg3QhqLMpG8r+8fhAXLRk2vvoC2f3B09zVXn8CA5QIVfZOJ3BCsw2P0p/We" crossorigin="anonymous">
<div id="carouselExampleControls" class="carousel slide" data-bs-ride="carousel">
<div class="carousel-inner">
<div class="carousel-item active">
<img src="https://picsum.photos/200/300" class="d-block w-100" alt="...">
</div>
<div class="carousel-item">
<img src="https://picsum.photos/200/300" class="d-block w-100" alt="...">
</div>
<div class="carousel-item">
<img src="https://picsum.photos/200/300" class="d-block w-100" alt="...">
</div>
</div>
<button class="carousel-control-prev" type="button" data-bs-target="#carouselExampleControls" data-bs-slide="prev">
<span class="carousel-control-prev-icon" aria-hidden="true"></span>
<span class="visually-hidden">Previous</span>
</button>
<button class="carousel-control-next" type="button" data-bs-target="#carouselExampleControls" data-bs-slide="next">
<span class="carousel-control-next-icon" aria-hidden="true"></span>
<span class="visually-hidden">Next</span>
</button>
</div>

carousel arrow also changes text in a div react.js

I am making a character select screen and I want the bootstrap carousel arrows to also change the text in the scroll to match each character. Right now the scroll is a separate component but I'm open to putting them on the same page.
I was trying to grab it by the class "active" since that came with the bootstrap carousel and populating from a data.json, but it isn't working. Open to other (hopefully easier) ideas as well!!
state = {
data: characters,
curCharacter: {},
}
componentDidMount() {
var cur = this.state.data[0].description;
this.setState({ curCharacter: this.state.data[0] });
console.log(this.state.curCharacter)
}
characterSelect = (e) => {
e.preventDefault()
var cur = document.getElementsByClassName("active")
console.log("activ1", cur)
var newClass = cur[0].children[0].alt
console.log("activ2", newClass);
var arr = this.state.data;
console.log(arr);
for (let i = 0; i < arr.length; i++) {
console.log(arr[i], arr[i + 2]);
if (newClass == arr[i].class) {
this.setState({ curCharacter: arr[i] });
console.log(this.state.curCharacter)
}
}
}
render() {
return (
<div className="charContain">
<div className="row">
<div className="col-md-6">
<div id="carouselExampleControls" class="sprite carousel slide" data-ride="carousel" data-interval="false" >
<div class="carousel-inner">
<div class="carousel-item active">
<img class="d-block h-100" src="https://i.imgur.com/ODs4zDn.gif" alt="Warrior" />
</div>
<div class="carousel-item">
<img class="d-block h-100" src="https://i.imgur.com/huVIPkL.png" alt="Archer" />
</div>
<div class="carousel-item">
<img class="d-block h-100" src="https://i.imgur.com/bKvuY6T.png" alt="Warrior" />
</div>
<div class="carousel-item">
<img class="d-block h-100" src="https://i.imgur.com/pIHmyE4.png" alt="Mage" />
</div>
</div>
<a class="carousel-control-prev" href="#carouselExampleControls" role="button" data-slide="prev">
<span class="carousel-control-prev-icon" aria-hidden="true"></span>
<span class="sr-only">Previous</span>
</a>
<a class="carousel-control-next" onClick={this.characterSelect} href="#carouselExampleControls" role="button" data-slide="next">
<span class="carousel-control-next-icon" aria-hidden="true"></span>
<span class="sr-only">Next</span>
</a>
</div>
<button onClick={handleButtonChoose} className="choose">Choose Character</button>
</div>
<div className="col-md-6">
<Scroll
text={this.state.description}
/>
</div>
</div>
</div>
)
}
}
export default Character
Thanks in advance!!

Bootstrap carousel not showing images

I'm trying to make a carousel which browses through the images in an image folder. A script automatically adds the items to the carousel based on the images present. The images are labelled 1, 2, 3, and so on.
But no matter what I try, the carousel doesn't show the image. I've tried converting the images to different format. The images are originally JFIF.
Here's my code:
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
<title>Edexcel International GCSE (9-1) Human Biology Student Book | Scotch's Pirated Book Reader (PBR) v3.6</title>
<link rel="stylesheet" href="css/bootstrap.css" />
</head>
<body onLoad="load()" style="margin-top: 10px;">
<div class="container">
<div style="text-align: center; line-height: 2px;">
<h4>Image browser</h4>
<p>Coded by someone</p>
</div><br /><br />
<div id="pageCarousel" class="carousel slide" data-ride="carousel" data-interval="false">
<div class="carousel-inner" role="listbox" id="carousel-inner">
<!-- GONNA BE FILLED BY THE SCRIPT -->
</div>
<a class="carousel-control-prev" href="#pageCarousel" role="button" data-slide="prev">
<span class="carousel-control-prev-icon bg-primary" aria-hidden="true"></span>
<span class="sr-only">Previous</span>
</a>
<a class="carousel-control-next" href="#pageCarousel" role="button" data-slide="next">
<span class="carousel-control-next-icon bg-primary" aria-hidden="true"></span>
<span class="sr-only">Next</span>
</a>
</div>
</div>
<script src="js/jquery-3.3.1.slim.min.js"></script>
<script src="js/popper.min.js"></script>
<script src="js/bootstrap.js"></script>
<script src="js/new.js"></script>
</body>
</html>
The new.js file has the script which loads the images into the carousel. A basic summary of what it does is:
'use strict';
function load()
{
var index = 2; // The first image is named 2.jfif
var carousel_innerHTML = "";
while (index < 278) // There are 277 images
{
carousel_innerHTML = carousel_innerHTML + makeEntry(index);
index++;
}
document.getElementById('carousel-inner').innerHTML = carousel_innerHTML;
}
function makeEntry(index)
{
return '<!-- AUTO GENERATED CODE --> <div class="carousel-item"><img class="d-block mx-auto" src="assets/' + index + '.jfif" alt="' + index + '" /></div>\n';
}
You were missing a couple things:
You need to add an active class to the first div in the carousel-inner div
You should initialize the carousel when finished loading the images. $('#pageCarousel').carousel({interval: 3000});
Here is a working example for you.
'use strict';
// for this example
var images = ["","","https://upload.wikimedia.org/wikipedia/commons/c/c9/10150811_677994762257483_131131840_n_677994762257483.jpg", "https://upload.wikimedia.org/wikipedia/commons/1/1b/10603847_756710051052620_5858255939401577860_o_756710051052620.jpg","https://upload.wikimedia.org/wikipedia/commons/6/6a/1073115_556203904436570_702830415_o_556203904436570.jpg"]
function load() {
var index = 2; // The first image is named 2.jfif
var carousel_innerHTML = "";
while (index < 5) // There are 277 images
{
carousel_innerHTML = carousel_innerHTML + makeEntry(index);
index++;
}
document.getElementById('carousel-inner').innerHTML = carousel_innerHTML;
$('#pageCarousel').carousel({interval: 3000});
}
function makeEntry(index) {
var first = index === 2 ? "active" : "";
return '<!-- AUTO GENERATED CODE --> <div class="carousel-item ' + first + '"><img class="d-block mx-auto" src="' + images[index] + '" alt="' + index + '" /></div>\n';
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<body onLoad="load()" style="margin-top: 10px;">
<div class="container">
<div style="text-align: center; line-height: 2px;">
<h4>Image browser</h4>
<p>Coded by someone</p>
</div><br /><br />
<div id="pageCarousel" class="carousel slide" data-ride="carousel" data-interval="false">
<div class="carousel-inner" role="listbox" id="carousel-inner">
<!-- GONNA BE FILLED BY THE SCRIPT -->
</div>
<a class="carousel-control-prev" href="#pageCarousel" role="button" data-slide="prev">
<span class="carousel-control-prev-icon bg-primary" aria-hidden="true"></span>
<span class="sr-only">Previous</span>
</a>
<a class="carousel-control-next" href="#pageCarousel" role="button" data-slide="next">
<span class="carousel-control-next-icon bg-primary" aria-hidden="true"></span>
<span class="sr-only">Next</span>
</a>
</div>
</div>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
</html>

Wrap a div dynamically using jQuery depending on screen size

I have a bootstrap carousel. Here if window width i more than 400px, I need to show all inner divs in same item. But if the window width is less than 400px, I need to show every 3 inner divs in
one <div class="item">. I have this code:
function item_wrap() {
var width = $(window).width();
console.log(width);
if (width > 400) {
$('.inner').unwrap();
$('.inner').wrapAll('<div class="item active">');
} else {
$('.inner').unwrap();
$('.inner:lt(3)').wrapAll('<div class="item active">');
$('.inner:gt(2)').wrapAll('<div class="item">');
}
}
item_wrap();
$(window).resize(function() {
item_wrap();
});
.item {
background: #ccc;
}
.active {
color: red
}
.inner {
float: left;
width: 20%;
border: 1px solid black;
margin: 2px;
}
#media screen and (max-width: 400px) and (min-width: 300px) {
.inner {
width: 30%;
}
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<div class="container">
<div class="row">
<div id="myCarousel" class="carousel" data-ride="carousel" data-interval="false">
<div class="carousel-inner" role="listbox">
<div>
<div class="inner">1</div>
<div class="inner">2</div>
<div class="inner">3</div>
<div class="inner">4</div>
<div class="inner">5</div>
<div class="inner">6</div>
<div class="inner">7</div>
<div class="inner">8</div>
<div class="inner">9</div>
<div class="inner">10</div>
<div class="inner">11</div>
<div class="inner">12</div>
</div>
</div>
<a class="carousel-control left-carousel" href="#myCarousel" role="button" data-slide="prev">
<span class="glyphicon glyphicon-chevron-left" aria-hidden="true" style="display:block"></span>
<span class="sr-only">Previous</span>
</a>
<a class="right carousel-control right-carousel" href="#myCarousel" role="button" data-slide="next" style="background: inherit !important;display: block;height: auto;opacity: 0.5;right: -4%;">
<span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span>
<span class="sr-only">Next</span>
</a>
</div>
</div>
</div>
If window width is greater than 400px it is working correctly. But if the window width is less than 400px the first 3 inner divs are showing correct
but other inner div are not correctly wrappped in <div class="item">
what i need is if in window width less than 400px then first 3 inner
div is need wrap in <div class="item active"> and all other ecah 3
inner div is need to wrap in <div class="item">.
ie , if window width less than 400px i need to get the following structure
<div class="carousel-inner" role="listbox">
<div>
<div class="item-active">
<div class="inner">1</div>
<div class="inner">2</div>
<div class="inner">3</div>
</div>
<div class="item">
<div class="inner">4</div>
<div class="inner">5</div>
<div class="inner">6</div>
</div>
<div class="item">
<div class="inner">7</div>
<div class="inner">8</div>
<div class="inner">9</div>
</div>
<div class="item">
<div class="inner">10</div>
<div class="inner">11</div>
<div class="inner">12</div>
</div>
</div>
</div>
Please help to solve this .
Try this
<script type="text/javascript">
function item_wrap(){
var width = $(window).width();
console.log(width);
if(width > 400) {
$('.inner').unwrap();
$('.inner').wrapAll('<div class="item active">');
} else {
$('.inner').unwrap();
var divs = $(".inner");
for(var i = 0; i < divs.length; i+=3) {
if(i===0){
$('.inner:lt(3)').wrapAll('<div class="item active">');
}
else{
divs.slice(i, i+3).wrapAll("<div class='item'></div>");
}
}
}
}
item_wrap();
$(window).resize(function(){
item_wrap();
});
</script>
Idea
Here's the code that works. The idea is that you loop through the remaining items after the first three, taking three items at a time, and wrap them into the div. Then take the next three and wrap them again, and so forth.
Main code:
for (var i = 0; i < others.length; i += 3) {
var nextThree = [others[i], others[i+1], others[i+2]]'
$(nextThree).wrapAll('<div class="item">');
}
Full code:
function item_wrap() {
var width = $(window).width();
console.log(width);
if (width > 400) {
$('.inner').unwrap();
$('.inner').wrapAll('<div class="item active">');
} else {
$('.inner').unwrap();
var firstThree = $('.inner:lt(3)');
var others = $('.inner:gt(2)');
$(firstThree).wrapAll('<div class="item active">');
for (var i = 0; i < others.length; i += 3) {
var nextThree = [others[i], others[i+1], others[i+2]]'
$(nextThree).wrapAll('<div class="item">');
}
}
}
item_wrap();
$(window).resize(function() {
item_wrap();
});
.item {
background: #ccc;
}
.active {
color: red
}
.inner {
float: left;
width: 20%;
border: 1px solid black;
margin: 2px;
}
#media screen and (max-width: 400px) and (min-width: 300px) {
.inner {
width: 30%;
}
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<div class="container">
<div class="row">
<div id="myCarousel" class="carousel" data-ride="carousel" data-interval="false">
<div class="carousel-inner" role="listbox">
<div>
<div class="inner">1</div>
<div class="inner">2</div>
<div class="inner">3</div>
<div class="inner">4</div>
<div class="inner">5</div>
<div class="inner">6</div>
<div class="inner">7</div>
<div class="inner">8</div>
<div class="inner">9</div>
<div class="inner">10</div>
<div class="inner">11</div>
<div class="inner">12</div>
</div>
</div>
<a class="carousel-control left-carousel" href="#myCarousel" role="button" data-slide="prev">
<span class="glyphicon glyphicon-chevron-left" aria-hidden="true" style="display:block"></span>
<span class="sr-only">Previous</span>
</a>
<a class="right carousel-control right-carousel" href="#myCarousel" role="button" data-slide="next" style="background: inherit !important;display: block;height: auto;opacity: 0.5;right: -4%;">
<span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span>
<span class="sr-only">Next</span>
</a>
</div>
</div>
</div>

Categories