How to load JSP page on next/prev click of Bootstrap carousel - javascript

Earlier I had scrollbar, where different icons were displayed. on click of particular icon, jsp page was displayed. but i need to replaced it with carousel.
on next/prev click following function should be called:
function testing(index) {
var tableLength = tableAddArray.length;
for (var i = 0; i < tableLength; i++) {
if (i == index) {
selectedElement= tableAddArray[i].id;
}
console.log("selectedElement:: "+selectedElement);
}
createElement();
}
function createElement() {
var request ="/xyzz/abcdd?objectName=";
var attributesToSend = "&action=add" ;
attributesToSend += "&ref="+document.getElementsByName("ref")[0].value ;
document.getElementsByName("action")[0].value = "add";
if (selectedElement != null) { request += selectedElement;
if (selectedElement == "1") {equest += "&condOp=5"; }
else if (selectedElement == "2") {request += "&dest=2";}
request += attributesToSend; location.href=request;
//from here other processing is done to get corresponding data from DB
}
}
then in carousel,:
<div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel" data-interval="false">
<div class="carousel-inner">
<div class="carousel-item">
<c:choose>
<c:when test="${requestScope.objectName == '2'}">
<jsp:include page="2nd_Slide.jsp"></jsp:include> </c:when>
<c:when test="${requestScope.objectName == '3'}">
<jsp:include page="3rd_slide.jsp"></jsp:include> </c:when>
</c:choose>
</div>
<a class="carousel-control-prev" ..>
<a class="carousel-control-next" ..>
</div>
Hence i need to set objectname at 0th index as well. I dont know how to call js before 0th slide of carousel is shown.

You might wanna register an event handler on slide action of the carousel. Something like this
$('#carousel_id').on('slide.bs.carousel', function ()
//load jsp like before with click on icons
)
Set some id on the element that needs to trigger jsp load
NOTE: check out slid.bs.carousel for post slide event handling
EDIT:
Try:
<div id="carouselExampleControls" class="carousel slide" data- ride="carousel">
<div class="carousel-inner">
<div class="carousel-item active">
<p class="d-block w-100">
Slide 1
<div id="jspdiv1"></div>
</p>
</div>
<div class="carousel-item">
<p class="d-block w-100">
Slide 2
<div id="jspdiv2"></div>
</p>
</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" 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>
<script>
var ind = 0;
$('#carouselExampleControls').bind('slid.bs.carousel', function (e) {
if(e.direction =='right'){
ind++;
console.log("right "+ind);
$("#jspdiv1").text("Slided right "+ind);
}
else if(e.direction == 'left'){
ind--;
console.log("left "+ind);
$("#jspdiv2").text("Slided left "+ind);
}
console.log(e);
});
</script>

Related

Javascript array used in bootstrap carousel

I want to use my javascript array in my bootstrap carousel in order to make a carousel which uses all of the elements within the array with which it decides what picture should be there. It should also write out what would be my , and alt of the picture on the carousel items but don't know how to connect the two, any suggestions? The array I have is
const data = [
{
src: 'italian.jpg',
title: 'Italian cuisine',
subtitle: 'Great italian cuisine',
alt: 'Image of italian cuisine'
},
{
src: 'mexican.jpg',
title: 'Mexican cuisine',
subtitle: 'Amazing mexican cuisine',
alt: 'Image of mexican cuisine'
},
{
src: 'japanese.jpg',
title: 'Japanese cuisine',
subtitle: 'Traditional japanese cuisine',
alt: 'Image of japanese cuisine'
}
];
document.getElementById("carousel-item").innerHTML = data;
The carousel is the basic bootstrap one.
<div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel">
<ol class="carousel-indicators">
<li data-target="#carouselExampleIndicators" data-slide-to="0" class="active"></li>
<li data-target="#carouselExampleIndicators" data-slide-to="1"></li>
<li data-target="#carouselExampleIndicators" data-slide-to="2"></li>
</ol>
<div class="carousel-item">
<img src="..." alt="...">
<div class="carousel-caption d-none d-md-block">
<h5>...</h5>
<p>...</p>
</div>
</div>
<div class="carousel-item">
<img src="..." alt="...">
<div class="carousel-caption d-none d-md-block">
<h5>...</h5>
<p>...</p>
</div>
</div>
<div class="carousel-item">
<img src="..." alt="...">
<div class="carousel-caption d-none d-md-block">
<h5>...</h5>
<p>...</p>
</div>
</div>
<a class="carousel-control-prev" href="#carouselExampleIndicators" 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="#carouselExampleIndicators" role="button" data-slide="next">
<span class="carousel-control-next-icon" aria-hidden="true"></span>
<span class="sr-only">Next</span>
</a>
To create the carousel using javascript, you'd create/get an array of data (like you have) -> then create the slide/indicator elements in javascript looping through your array -> then write the HTML you created in that loop to the page. When you do write it to the page, you'll want it to go into the carousel structure, which is why we set up the skeleton of the carousel first, then inserted the slides HTML to it. Below, I create an array for slides and indicators and for each picture in your array, I create the HTML and add it to the relevant array. When the arrays are complete, I add them to the page using join(''). Join('') just takes all the array elements and joins them together to make a string, which is what we're writing to the page.
Remove this line document.getElementById("carousel-item").innerHTML = data; - you're not writing an array into an HTML element. Rather, you need to loop through your array and create the slides and the indicators with it.
Start off with the basic skeleton - and I added a div for us to place the slides into. Also, I removed data-ride="carousel" since we'll actually activate the carousel after our loop, rather than on page load.
<div id="carouselExampleIndicators" class="carousel slide" >
<ol class="carousel-indicators" id='carousel-indicators'>
<!-- here is where we'll add the indicators -->
</ol>
<div class='carousel-inner' id='carousel-items'>
<!-- here is where we'll add the slides -->
</div>
<a class="carousel-control-prev" href="#carouselExampleIndicators" 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="#carouselExampleIndicators" role="button" data-slide="next">
<span class="carousel-control-next-icon" aria-hidden="true"></span>
<span class="sr-only">Next</span>
</a>
Then at the top we'll get the data ready after the page loads:
window.onload = (event) => {
// const data = [ ... ]
var slides=[], indicators=[], html='', activeClass
data.forEach(item => {
// set up the slide
activeClass = slides.length == 0 ? ' active ' : '' ; // the carousel has to have 1 active slide when it starts or else nothing will show. We set the first one as 'active' based on the length of the array we're making (when it's 0, that means we on the first one)
html = '<div class="carousel-item ' + activeClass + '">'
html += '<img src="' + item.src + '" alt="' + item.alt + '">'
html += '<div class="carousel-caption d-none d-md-block">'
html += '<h5>' + item.title + '</h5>'
html += '<p>' + item.subtitle + '</p>'
html += '</div></div>'
slides.push(html);
// set up the indicator
activeClass = indicators.length == 0 ? ' class="active" ' : '' ; // see note about the active slide above- same goes for the indicators
html = '<li data-target="#carouselExampleIndicators" data-slide-to="' + indicators.length + '" ' + activeClass + '></li>';
indicators.push(html);
})
// now add it to your carousel and fire it up!
document.getElementById('carousel-indicators').innerHTML = indicators.join('');
document.getElementById('carousel-slides').innerHTML = slides.join('');
$('#carouselExampleIndicators').carousel(); // This line assumes you have jQuery loaded with Bootstrap
};

How to add different image slideshow in html on the same page?

From API I’m getting array of images and when requesting the API second time I’m getting another array of different images. When press the button I want to add an images array to the bootstrap gallery and when press again I want to add second array into another gallery. I don’t understand how reuse the same bootstrap html template and create different image galleries in the same html page.
API object:
{
"title": "rodeo",
"author": "consectetur",
"images": [
"http://example/photo.jpg",
"http://example/photostwo.jpg",
"http://example/photosone.jpg"
],
"year": "1998"
}
<div>
<div id="container"></div>
<button id="dataBtn"></button>
</div>
<div id="carouselExampleControls" class="carousel slide" data-ride="carousel">
<div class="carousel-inner">
<div class="carousel-item active">
<img class="d-block w-100" src="...">
</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" 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>
function test(){
const carouselItem = document.querySelector('.carousel-item');
function create(element) {
return document.createElement(element);
}
function append(parent, el) {
return parent.appendChild(el);
}
for (image of data.images) {
let img = create('img');
img.classList.add(‘d - block’, ‘w - 100’);
img.src = image;
append(carouselItem, img);
}
}
test();
document.getElementById("dataBtn").addEventListener("click", test);
With bootstrap, those tasks would be much more easier using jQuery Framework! As you are mentioning only Javascript in your Question' tags, This is a method showing how we could do it is in pure Javascript that you could easily include in your project.
We clone the Carousel container, then we fill the dynamically added clones with new pictures.
//An initial status we could check later
var initial = true;
//A global counter that could be used to distinguish between non-DOM duplicates
let i = 0;
function test() {
//Here A random array of pics would be used
//Just to simulate an API call
var rand = Math.floor(Math.random() * Math.floor(2));
var pix = JSON.parse('{"data":[{"title":"rodeo","author":"consectetur","images":["https://images.unsplash.com/photo-1533522688752-ef641aa0607b?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=125&q=60","https://images.unsplash.com/photo-1550543941-281cef85c281?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=125&q=60","https://images.unsplash.com/photo-1565291707930-351bfd98e772?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=125&q=60"],"year":"1998"},{"title":"Flasher","author":"Photo Addict","images":["https://images.unsplash.com/photo-1516724562728-afc824a36e84?ixlib=rb-1.2.1&auto=format&fit=crop&w=125&q=60","https://images.unsplash.com/photo-1505739998589-00fc191ce01d?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=125&q=60","https://images.unsplash.com/photo-1516962126636-27ad087061cc?ixlib=rb-1.2.1&auto=format&fit=crop&w=125&q=80","https://images.unsplash.com/photo-1518890414976-bb41382be43e?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=125&q=80"],"year":"2020"},{"title":"Domotics","author":"iOting","images":["https://images.unsplash.com/photo-1528255671579-01b9e182ed1d?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=125&q=60","https://images.unsplash.com/photo-1505739998589-00fc191ce01d?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=125&q=60","https://images.unsplash.com/photo-1494351416886-f6b4ed2a1d68?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=125&q=60","https://images.unsplash.com/photo-1547938094-b000547cbeb9?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=125&q=60"],"year":"2020"}]}');
const carouselItem = document.querySelector('.carousel-item');
function create(element) {
return document.createElement(element);
}
function append(parent, el) {
return parent.appendChild(el);
}
var model = document.getElementById('carouselExampleControls');
function duplicate() {
i++;
//We clone the default laoded Gallery container
var clone = model.cloneNode(true);
clone.id = "cloneGallery" + i;
model.parentNode.appendChild(clone);
//We identify the dynamically newly added picture container
var clItem = document.getElementsByClassName('carousel-item')[i];
//We empty it... so we could replace by new pics
clItem.innerHTML = '';
for (image of pix.data[rand].images) {
var img = create('img');
img.classList.add('d-block', 'w-100');
img.src = image;
append(clItem, img);
}
}
if (initial) {
for (image of pix.data[rand].images) {
var img = create('img');
img.classList.add('d-block', 'w-100');
img.src = image;
append(carouselItem, img);
}
} else {
duplicate();
}
initial = false;
}
document.getElementById("dataBtn").addEventListener("click", test);
<div>
<div id="container"></div>
<button id="dataBtn">Add Pictures!</button>
</div>
<div id="carouselExampleControls" class="carousel slide" data-ride="carousel">
<div class="carousel-inner">
<div class="carousel-item">
</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" 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>
Try it..
Result Size: 497 x 476
<html>
<title>Multiple slideshow</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<body>
​
<h2 class="w3-center">Manual Slideshow</h2>
​
<div class="w3-content w3-display-container">
<img class="mySlides1" src="img_snowtops.jpg" style="width:100%">
<img class="mySlides1" src="img_lights.jpg" style="width:100%">
<img class="mySlides1" src="img_mountains.jpg" style="width:100%">
<img class="mySlides1" src="img_forest.jpg" style="width:100%">
<button class="w3-button w3-black w3-display-left" onclick="plusDivs(-1, 0)">❮</button>
<button class="w3-button w3-black w3-display-right" onclick="plusDivs(1, 0)">❯</button>
</div>
​
<div class="w3-content w3-display-container">
<img class="mySlides2" src="img_la.jpg" style="width:100%">
<img class="mySlides2" src="img_ny.jpg" style="width:100%">
<img class="mySlides2" src="img_chicago.jpg" style="width:100%">
<button class="w3-button w3-black w3-display-left" onclick="plusDivs(-1, 1)">❮</button>
<button class="w3-button w3-black w3-display-right" onclick="plusDivs(1, 1)">❯</button>
</div>
​
<script>
var slideIndex = [1,1];
var slideId = ["mySlides1", "mySlides2"]
showDivs(1, 0);
showDivs(1, 1);
​
function plusDivs(n, no) {
showDivs(slideIndex[no] += n, no);
}
​
function showDivs(n, no) {
var i;
var x = document.getElementsByClassName(slideId[no]);
if (n > x.length) {slideIndex[no] = 1}
if (n < 1) {slideIndex[no] = x.length}
for (i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
x[slideIndex[no]-1].style.display = "block";
}
</script>
​
</body>
</html>
​

Why is Bootstrap 4 carousel pause function not working when it's getting called from the event of an element inside of the carousel?

So I was trying to wrap my head around this issue, and I asked the question yesterday:
Carousel('pause') isn't working on mobile devices
I found the symptom so I'm asking a new question with a new focus.
The question title is not telling everything, because it would be too large:
This is only happening on phones, using mobile browsers, On desktop is totally fine.
Basically, if you have a Bootstrap 4 carousel, and you have any element that is inside of the div with the id of the carousel and you want to attach an event on that element (like a click) to pause the carousel, it wont work AT ALL, the slider keeps cycling.
I've tried click, mousedown, mouseup, I've tried setting the selector's click event on body, tried calling a click event on a selector that is outside to pause it, used parents, etc, and it wouldn't work.
Created a button that is right outside the carousel, attached a click event to it and it works.
I'm using the latest BS (4.4.1)
This is my code:
Blade file:
<div id='slider'>
<button class='pause-carousel' role='button'>Pause from outside</button>
<div id='sme-directory-gallery' class='carousel slide' data-ride='carousel'>
<button class='pause-carousel-2' role='button'>Pause from inside</button>
<div class='carousel-inner'>
#foreach($directoryInfo->videos as $index => $video)
<div class='item carousel-item {{ $index === 0 ? 'active' : '' }}' data-slide-number='{{ $index }}'>
<div class='video-mask'></div>
<div class='d-flex justify-content-center'>
<div class='embed-responsive embed-responsive-21by9'>
<iframe class='embed-responsive-item player' src='{{ 'https://www.youtube.com/embed/' . substr($video->url, strrpos($video->url, 'v=') + 2) }}' allowfullscreen></iframe>
</div>
</div>
</div>
#endforeach
#foreach($directoryInfo->images as $index => $image)
<div class='item carousel-item {{ ($index + sizeof($directoryInfo->videos)) === 0 ? 'active' : '' }}' data-slide-number='{{ $index + sizeof($directoryInfo->videos) }}'>
<div class='d-flex justify-content-center'>
<img src='{{ asset('storage/' . $image->path) }}' class='img-fluid' alt='imagen'>
</div>
</div>
#endforeach
<a class='carousel-control-prev' href='#sme-directory-gallery' role='button' data-slide='prev'>
<div class='rounded-circle'>
<span class='carousel-control-prev-icon' aria-hidden='true'></span>
<span class='sr-only'>Previous</span>
</div>
</a>
<a class='carousel-control-next' href='#sme-directory-gallery' role='button' data-slide='next'>
<div class='rounded-circle'>
<span class='carousel-control-next-icon' aria-hidden='true'></span>
<span class='sr-only'>Next</span>
</div>
</a>
</div>
<ul class='carousel-indicators list-inline'>
#foreach($directoryInfo->videos as $index => $video)
<li class='list-inline-item my-2 {{ $index === 0 ? 'active' : '' }}'>
<a id='carousel-selector-{{ $index + sizeof($directoryInfo->videos) }}' class='sme-gallery-anchor' data-slide-to='{{ $index }}' data-target='#sme-directory-gallery'>
<img src='{{ 'https://img.youtube.com/vi/' . substr($video->url, strrpos($video->url, 'v=') + 2) . '/mqdefault.jpg' }}' class='img-fluid'>
<div class='text-white sme-gallery-middle-icon'>
<span class='fas fa-play'></span>
</div>
</a>
</li>
#endforeach
#foreach($directoryInfo->images as $index => $image)
<li class='list-inline-item {{ $index + sizeof($directoryInfo->videos) === 0 ? 'active' : '' }}'>
<a id='carousel-selector-{{ $index + sizeof($directoryInfo->videos) }}' data-slide-to='{{ $index + sizeof($directoryInfo->videos) }}' data-target='#sme-directory-gallery'>
<img src='{{ asset('storage/' . $image->path) }}' class='img-fluid'>
</a>
</li>
#endforeach
</ul>
</div>
</div>
Javascript:
$(document).ready(function () {
$('.carousel-indicators').scrollLeft(0);
$('#sme-directory-gallery').carousel();
$('.pause-carousel').on('click', function () {
$('#sme-directory-gallery').carousel('pause'); // it works
});
$('.pause-carousel-2').on('click', function () {
$('#sme-directory-gallery').carousel('pause'); // it wont work
});
$('#sme-directory-gallery .video-mask').mouseup(function () {
var iframe = $(this).closest('.item').find('iframe');
var iframe_source = iframe.attr('src');
if (iframe_source.includes('?rel=0')) {
iframe_source = iframe_source.replace('?rel=0', '');
}
iframe_source = iframe_source + '?autoplay=1';
iframe.attr('src', iframe_source);
$(this).toggle();
$('#sme-directory-gallery').carousel('pause');
});
$('#sme-directory-gallery').on('slide.bs.carousel', function (e) {
$('#sme-directory-gallery').carousel('cycle');
var iframeID = $(this).find('iframe').attr('id');
if (iframeID != undefined) {
callPlayer(iframeID, 'stopVideo');
}
$('.video-mask').show();
$('#sme-directory-gallery').find('iframe').each(function (key, value) {
var url = $(this).attr('src');
if (url.includes('?autoplay')) {
var new_url = url.substring(0, url.indexOf('?'));
$(this).attr('src', new_url);
}
});
setTimeout(() => {
var scrollTo = $('.list-inline-item.active').position().left;
if ($('.list-inline-item.active').index() > 0) {
scrollTo = $('.list-inline-item.active').prev('.list-inline-item').position().left;
}
var finalOrFirst = 0;
if (e.direction === 'right') {
if ($('.list-inline-item.active').is(':last-child')) {
finalOrFirst = 99999;
}
} else {
if ($('.list-inline-item.active').is(':first-child')) {
finalOrFirst = -99999;
}
}
var currentScroll = $('.carousel-indicators').scrollLeft();
var scrollResult = currentScroll + scrollTo + finalOrFirst;
$('.carousel-indicators').animate({scrollLeft: scrollResult}, 500);
}, 10);
});
});
What exactly is happening here, how do I fix it?
Thanks in advance.
Try this to catch the issue:
Put console.log or alert() to check if event is triggered or not.
$('.pause-carousel-2').on('click', function () {
console.log('Button Clicked');
$('#sme-directory-gallery').carousel('pause'); // it wont work
});
Case 1:
If "Button Click" is not printed in console, then you may try:
$('body').on('click','.pause-carousel-2',function(){ ...
Case 2:
If "Button Click" is printed, then there is a workaround for this issue, which you can try.
Use Trigger
$('.pause-carousel-2').on('click', function () {
$('.pause-carousel').trigger("click");
});
and hide the Pause button which is outside
Please share your result, will try to fix your issue.
If you use .carousel() as a varaible it will work. var slider = $('#element').carousel(); And you can use in all events. slider.carousel('pause'); , for starting again: slider.carousel({'pause': false});
When you use multiple element click events:
$('#btn1, #btn2').click(function(){
slider.carousel('pause');
});
In an another event (hover):
$('#yourSlider').hover(function(){
slider.carousel('pause');
}, function(){
slider.carousel({'pause': false});
});
If you don't assign it to a variable, the carousel will be restarted
within each event.
I added an examp (it works):
$(function(){
var slider = $('#carouselExampleSlidesOnly').carousel({
interval: 1000
});
$('#pause').click(function(){
slider.carousel('pause');
});
$('#start').click(function(){
slider.carousel({'pause': false});
});
});
.carousel-item{
padding-top: 45px;
text-align: center;
height:150px;
width:100%;
color:#fff;
background-color: #666;
font-size: 2rem;
font-weight: 700;
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container p-4">
<button id="pause" class="btn btn-sm btn-warning">Pause</button>
<button id="start" class="ml-2 btn btn-sm btn-primary">Start</button>
</div>
<div id="carouselExampleSlidesOnly" class="carousel slide" data-ride="carousel" style="width: 90%; marign:auto">
<div class="carousel-inner">
<div class="carousel-item active">
Slide 1
</div>
<div class="carousel-item">
Slide 2
</div>
<div class="carousel-item">
Slide 3
</div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
Set the pause to false and that will take care of the issue
$('.carousel').carousel({
pause: "false"
});
you can see an example here: https://jsfiddle.net/KyleMit/XFcSv/
I have a problem similar to this one: in some case the code doesn't work in some case works. The only difference I have found is about the presence of the class "pointer-event" in the tag of the carousel element.
To solve this problem I have use a boolean variable with the event "slide.bs.carousel" to avoid carousel to slide when paused.
HTML CODE
<section id="slideshow" class="carousel slide">
<div class="carousel-inner" id="images" >
<div class="carousel-item " >
<img src="..." class="d-block w-100" alt='bla bla bla' >
</div>
<div class="carousel-item " >
<img src="..." class="d-block w-100" alt='bla bla bla' >
</div>
<div class="carousel-item " >
<img src="..." class="d-block w-100" alt='bla bla bla' >
</div>
</div>
<a class="carousel-control-pause" href="#slideshow" role="button" >
<span class="pause-icon">
||
</span>
<span class="play-icon d-none">
|>
</span>
</a>
<a class="carousel-control-prev" href="#slideshow" role="button" data-slide="prev" >
<--
</a>
<a class="carousel-control-next" href="#slideshow" role="button" data-slide="next" >
-->
</a>
</section>
JAVASCRIPT CODE
$(document).ready(function(){
var carousel = $('#slideshow').carousel({
interval: 5000,
ride: true
});
var carousel_paused = false;
//on init the carousel is paused
$('#slideshow .carousel-control-pause').on('click', function(e){
e.preventDefault();
var hideclass= "d-none";
var pause= $(this).children(".pause-icon");
if( $(pause).is(":hidden"))
{
//play
$(pause).removeClass(hideclass);
$(this).children(".play-icon").addClass(hideclass);
carousel.carousel('cycle');
carousel_paused = false;
}
else
{
//pause
$(pause).addClass(hideclass);
$(this).children(".play-icon").removeClass(hideclass);
carousel.carousel('pause');
carousel_paused = true;
}
});
carousel.on('slide.bs.carousel', function (e) {
console.log("slide pre");
//prevent slide if paused
if(carousel_paused)
e.preventDefault();
});
carousel.on('slid.bs.carousel', function (e) {
console.log("slide done");
});
});
The code is for example and is not tested in mobile.

Remove carousel arrows if the image is not loaded

I am currently trying to remove the arrows from the carousel when there is no image present. The reason for me trying to do so, is simply because I am trying to load several images into a carousel from a database into a given section. This section is recreated multiple times and it doesn't always contain images.
The issue that I am having is that, whenever the bootstrap carousel doesn't have any images loaded, it just displays the carousel arrows on the side. This gives a bad look to the current section and I would like to dispose of that.
How can I remove the carousel arrows when there aren't any images
loaded in the carousel?
Here is a JsFiddle which contains what I've done so far, it is heavy inspired by several other posts. This only removes the left arrow on the first slide and the right arrow on the last slide.
Here you can preview how does the carousel look whenever there are absent images. I have set a black background of 400px in order for the arrows to be more easily spotted. Absent Images JsFiddle
Here is the code I have so far:
<div class="container">
<div id="main_area">
<!-- Slider -->
<div class="row">
<div class="col-xs-12" id="slider">
<!-- Top part of the slider -->
<div class="row">
<div class="col-sm-8" id="carousel-bounding-box">
<div class="carousel slide" id="myCarousel">
<!-- Carousel items -->
<div class="carousel-inner">
<div class="active item" data-slide-number="0">
<img src="http://placehold.it/770x300&text=one"></div>
<div class="item" data-slide-number="1">
<img src="http://placehold.it/770x300&text=two"></div>
<div class="item" data-slide-number="2">
<img src="http://placehold.it/770x300&text=three"></div>
<div class="item" data-slide-number="3">
<img src="http://placehold.it/770x300&text=four"></div>
<div class="item" data-slide-number="4">
<img src="http://placehold.it/770x300&text=five"></div>
<div class="item" data-slide-number="5">
<img src="http://placehold.it/770x300&text=six"></div>
</div><!-- Carousel nav -->
<a class="left carousel-control" href="#myCarousel" role="button" data-slide="prev">
<span class="glyphicon glyphicon-chevron-left"></span>
</a>
<a class="right carousel-control" href="#myCarousel" role="button" data-slide="next" id="arrow-right">
<span class="glyphicon glyphicon-chevron-right"></span>
</a>
</div>
</div>
</div>
</div>
</div>
</div><!--/Slider-->
</div>
JQuery Code:
jQuery(document).ready(function($) {
$('.carousel').carousel({
interval: false,
})
$(document).ready(function () { // on document ready
checkitem();
});
$('#myCarousel').on('slid.bs.carousel', checkitem);
function checkitem() // check function
{
var $this = $('#myCarousel');
if ($('.carousel-inner .item:first').hasClass('active')) {
$this.children('.left.carousel-control').hide();
} else if ($('.carousel-inner .item:last').hasClass('active')) {
$this.children('.right.carousel-control').hide();
} else {
$this.children('.carousel-control').show();
}
}
$("img").error(function(){
$(this).hide('#arrow-right');
});
});
Here are the answers that I've already checked for solutions:
Link 1Link 2
Thank you in advance.
Using jQuery you could try something like..
$(document).ready(function(){
if($('.carousel-inner .item img').attr('src') == '') {
$('.carousel-control').css('display', 'none');
}
});
fiddle

Each time window resizes, the append method keeps adding to container

I'm trying to switch out my images in Bootstrap's carousel at the 768px breakpoint only for responsive purposes. So I decided to use the resize() method and append the smaller images to the .carousel-inner div when they reach equal to or less than to 768px or maintain large images if window is larger than 768. However, when ever I resize the window it keeps appending those images over and over again until I stop resizing. Only returns to normal when I refresh. Which this all makes sense that it the code executes every time the window gets resized. So I was wondering if there is a method out there that I should be trying instead? I kind want it to act like a media query... I have pasted my code below and you can check it out on my GitHub: https://ldgoncalves.github.io/ChamberStat/html/index.html
I'm using Laravel 5.3 for this as well.
$(window).on("resize load", function () {
if ($(window).width() <= 768) {
var smallerImg = '<div class="item active"><img src="{{asset('images/slide4.png')}}" alt="First slide of a customer review"></div>' +
'<div class="item"><img src="{{asset('images/slide5.png')}}" alt="Second slide of a customer review"></div>' +
'<div class="item"><img src="{{asset('images/slide6.png')}}" alt="Third slide of a customer review"></div>'+
'<div class="item"><img src="{{asset('images/slide7.png')}}" alt="Fourth slide of a customer review"></div>'+
'<div class="item"><img src="{{asset('images/slide8.png')}}" alt="Fifth slide of a customer review"></div>'+
'<div class="item"><img src="{{asset('images/slide9.png')}}" alt="Sixth slide of a customer review"></div>';
$('.carousel-inner').append(smallerImg);
}
else{
var largerImg = '<div class="item active"><img src="{{asset('images/slide1.png')}}" alt="First slide of customer reviews"></div>' +
'<div class="item"><img src="{{asset('images/slide2.png')}}" alt="Second slide of customer reviews"></div>' +
'<div class="item"><img src="{{asset('images/slide3.png')}}" alt="Third slide of customer reviews"></div>';
$('.carousel-inner').append(largerImg);
}
});
<!-- Testimonials -->
<section id="testimonials" class="row">
<h1 class="col-xs-12 col-md-12">Testimonials</h1>
<p class="col-xs-12 col-md-12">ChamberStat will get you organized, but don't take our word for it! See what
our customers are saying.</p>
<!-- bootstrap carousel -->
<div class="clearfix hidden-sm-up"></div>
<div id="testimonials-slide" class="carousel slide" data-ride="carousel">
<ol class="carousel-indicators col-lg-1">
<li data-target="#testimonials-slide" data-slide-to="0" class="active"></li>
<li data-target="#testimonials-slide" data-slide-to="1"></li>
<li data-target="#testimonials-slide" data-slide-to="2"></li>
<li data-target="#testimonials-slide" data-slide-to="3"></li>
<li data-target="#testimonials-slide" data-slide-to="4"></li>
<li data-target="#testimonials-slide" data-slide-to="5"></li>
</ol>
<div class="carousel-inner" role="listbox">
</div>
<a class="left carousel-control" href="#testimonials-slide" role="button" data-slide="prev">
<span class="icon-prev" aria-hidden="true"></span>
<span class="sr-only">Previous</span>
</a>
<a class="right carousel-control" href="#testimonials-slide" role="button" data-slide="next">
<span class="icon-next" aria-hidden="true"></span>
<span class="sr-only">Next</span>
</a>
</div>
</section>
You only want the content change to happen when the mode changes. And you probably want to empty() the list when changing content. Something like this:
$(window).on("resize load", function () {
var largerImg = '...';
var smallerImg = '...';
var $carousel = $('.carousel-inner');
var lastMode = $carousel.hasClass('small') ? 'small' : 'large';
var newMode = $(window).width() <= 768 ? 'small' : 'large';
if (lastMode === newMode)
return;
if (newMode === 'small') {
$carousel.addClass('small').empty().append(smallerImg);
} else{
$carousel.removeClass('small').empty().append(largerImg);
}
});
Quick idea: You could store the last window size in a var. An only change the images, if oldSize > breakpoint && newValue <= breakpoint. And vice versa for the other "mediaQuery".

Categories

Resources