How can you change an image on a bootstrap carousel on click? - javascript

I currently have a bootstrap carousel with 3 images each image has a caption I want it so when you click on the caption on the first carousel image the image will change to a gif but it isn't working using basic JavaScript.
I want plymouthImg to change into permitionImg, currently permitionImg display is set to none!important
<div id="carouselExampleCaptions" class="carousel slide" data-bs-ride="carousel">
<div class="carousel-inner">
<div class="carousel-item active">
<img id="plymouthImg" src="imgs/plymouth1.jpg" class="d-block w-100" alt="Roland Levinsky Building">
<img id="permitionImg" src="imgs/plymouthbaw.gif" class="d-block w-100" alt="Permition">
<div class="carousel-caption d-md-block">
<h3 onclick="changeText()" class="plymouth">Welcome to the University of Plymouth</h3>
<h3 class="permition">Welcome to Permition</h3>
</div>
</div>
This is the JavaScript function on the h3
function changeText() {
const plymouthText = document.querySelector('.plymouth');
const permitionText = document.querySelector('.permition');
const plymouthImg = document.getElementById('plymouthImg');
const permitionImg = document.getElementById('permitionImg');
plymouthText.style.display = "none";
permitionText.style.display = "block";
plymouthImg.style.display = "none!important";
permitionImg.style.display = "block!important";
}

Figured it out myself so gonna leave my solution here in case anyone else has this problem. By wrapping the images in their own individual div and applying the display changes to the divs instead of the images it bypasses any styling that is overriding the JavaScript I wrote
HTML
<div id="carouselExampleCaptions" class="carousel slide" data-bs-ride="carousel">
<div class="carousel-inner">
<div class="carousel-item active">
<div id="plymouthImg">
<img src="imgs/plymouth1.jpg" class="d-block w-100" alt="Roland Levinsky Building">
</div>
<div id="permitionImg">
<img src="imgs/plymouthbaw.gif" class="d-block w-100" alt="Permition">
</div>
<div class="carousel-caption d-md-block">
<h3 onclick="changeText()" class="plymouth">Welcome to the University of Plymouth</h3>
<h3 class="permition">Welcome to Permition</h3>
</div>
JavaScript
function changeText() {
const plymouthText = document.querySelector('.plymouth');
const permitionText = document.querySelector('.permition');
const plymouthImg = document.getElementById('plymouthImg');
const permitionImg = document.getElementById('permitionImg');
plymouthText.style.display = "none";
permitionText.style.display = "block";
plymouthImg.style.display = "none";
permitionImg.style.display = "block";
}

Related

How to loop over carousel items using Vanilla Js

I'm fetching data from The Movie Database and i want the data retrieved to be displayed in my page on a carousel card with 3 slides.
Here is what i have done so far,
html,
<div class="details"><!--Movie details are to be displayed here--></div>
Js,
<script type="text/javascript">
function arrangement(resultFromServer) {
let gridHtml=" ";
let poster= "https://image.tmdb.org/t/p/w185/";
let element= document.querySelector(".details");
let index= [].indexOf.call(element.parentElement.children, element);
let selected = resultFromServer.results[index];
for (let i = 0; i < resultFromServer.results.length; i++) {
const movieResults =resultFromServer.results[i];
gridHtml += `
<div id="multi-item-example" class="carousel slide carousel-multi-item" data-ride="carousel">
<!--Indicators-->
<ol class="carousel-indicators">
<li data-target="#multi-item-example" data-slide-to="0" class="active"></li>
<li data-target="#multi-item-example" data-slide-to="1"></li>
<li data-target="#multi-item-example" data-slide-to="2"></li>
</ol>
<!--/.Indicators-->
<!--Slides-->
<div class="carousel-inner" role="listbox">
<!--First slide-->
<div class="carousel-item active">
<div class="row">
<div class="col-md-4">
<div class="card mb-2">
<img class="card-img-top" src="${poster}${movieResults.poster_path}"
alt="Card image cap">
<div class="card-body">
<h4 class="card-title">${movieResults.title}</h4>
<p class="card-text">Some quick example text to build on the card title and make up the bulk of the
card's content.</p>
<a class="btn btn-primary">Button</a>
</div>
</div>
</div>
</div>
</div>
</div>`;
}
let myPage= document.querySelector(".details");
myPage.innerHTML=gridHtml;
}
</script>
What i get from this is that the movie details are returned in a vertical arrangement. Can someone help please !
You need to use querySelector to check for an 'active' class.
function myFunction(e) {
var carousel = document.querySelector(".active");
if(carousel !==null){
carousel.classList.remove("active");
}
e.target.className = "active";
}
querySelector is used to find an active class on the page, if it exists (the if statement) then remove it and apply the active class on the next element, iterating through the entire collection.

Changing a bootstrap carousel's index with jquery reactivates auto-play

What I want to do:
I have a bootstrap carousel and 5 divs. When I hover on the first div I want to show the first carousel-item...etc
What I did:
I deactivated the auto play with data-interval="false"
When hovering those controlling items, the following function is called:
function changeImage(index) {
$("#carousel").carousel(index); // index is the active carousel-item's index
}
What happened:
Before hovering on any controlling item, the carousel doesn't auto play.
After hovering on any controlling item, the carousel displays the expected carousel-item, however the carousel starts auto-playing.
What I tried:
Using Jquery I set the interval to false after each time I navigate in the carousel:
function changeImage(index) {
$("#carousel").carousel(index);
$('#carousel').carousel({
interval: false
})
}
But it didn't work.
Full code:
<div id="carousel" class="carousel slide" data-interval="false">
<div class="carousel-inner">
<div class="carousel-item">
<img src="..."/>
</div>
<div class="carousel-item active">
<img src="..."/>
</div>
<div class="carousel-item">
<img src="..."/>
</div>
<div class="carousel-item">
<img src="..."/>
</div>
</div>
</div>
<div id="controls">
<div onmouseover="changeImage(0)">1</div>
<div onmouseover="changeImage(1)">2</div>
<div onmouseover="changeImage(2)">3</div>
<div onmouseover="changeImage(3)">4</div>
<div onmouseover="changeImage(4)">5</div>
</div>
<script>
$('#carousel').on('slide.bs.carousel', function () {
$('#carousel').carousel({
interval: false
})
})
function changeImage(index) {
$("#carousel").carousel(index);
}
</script>

Delete all Elements in a class EXCEPT two anchor tags

Hey I have made a function that fills an empty container of a slideshow with images, with each image being contained in it's own div.
My webpage has an undetermined amount of modal images which , when clicked, open a slideshow album of images. I got this working for 1 image then realized that to have it work for an undetermined amount of slideshows of undetermined size I should make a function that fills the slideshow div. I planned to have each modal image to have a data attribute of "1,2,3...etc" and have a bunch an array with multiple objects each named similarly "1,2,3...etc" then I'd use this information to create and append the correct divs and images to the slideshow container.
I have successfully done this but I THINK I need to clear the parent .modal-content div of all it's children EXCEPT the two buttons (.next and .prev), because the modal seems to open the correct slideshow, but only on the first time it is clicked, the other times it just keeps adding more and more of the array to it. I believe clearing the div upon closing the slideshow should fix this IF IN FACT IT COMPLETELY GETS RID OF THE INNER ELEMENTS, which I think my code should do but I got it off of stackoverflow so idk for certain.
I have this code to delete the content of the div (Note this is really where I need to add the code that excludes those 2 elements, but I've included more code for context):
function clearSlides(){
var myNode = document.getElementById("modal_content");
while (myNode.firstChild) {
myNode.removeChild(myNode.firstChild);
}
}
This is my HTML:
<div class="row">
<div class="column">
<img id="modal-1" src="https://www.yosemitehikes.com/images/wallpaper/yosemitehikes.com-bridalveil-winter-1200x800.jpg" style="max-width:100%" data-modal="1" onclick="fillSlides(this); openModal(); currentSlide(1); " class="hover-shadow cursor">
</div>
</div>
<div id="myModal" class="modal">
<span class="close cursor" onclick="clearSlides(); closeModal();">×</span>
<div class="modal-content" id="modal_content">
<a class="prev" onclick="plusSlides(-1)">❮</a>
<a class="next" onclick="plusSlides(1)">❯</a>
</div>
</div>
.modal-content div get's filled with this js function:
function fillSlides(modalID){
var container = document.getElementsByClassName("modal-content");
var slides = {
"1": ["Images/LS_01.jpg", "Images/LS_02.jpg", "Images/LS_03.jpg", "Images/LS_04.jpg" ],
"2": ["Images/LS_05.jpg", "Images/LS_06.jpg", "Images/LS_07.jpg", "Images/LS_08.jpg" ],
"3": ["Images/LS_09.jpg", "Images/LS_10.jpg", "Images/LS_11.jpg", "Images/LS_12.jpg" ]
};
var modal_num = modalID.getAttribute('data-modal');
//alert(slides[modal_num].length);
for (var i = 0 ; i < slides[modal_num].length; i++) {
var the_divs = document.createElement('div');
var s_img = document.createElement('img');
the_divs.className = 'mySlides';
s_img.src = slides[modal_num][i];
the_divs.appendChild(s_img);
container[0].appendChild(the_divs);
}
}
Please let me know if further clarification is required.
As per comments keep your controls outside of #modal_content use innerHTML='' to wipe everything within it.
Demo
function clearSlides() {
var content = document.getElementById('modal_content');
content.innerHTML = '';
}
function closeModal() {
document.getElementById('myModal').style.display = "none";
}
<div class="row">
<div class="column">
<img id="modal-1" src="https://www.yosemitehikes.com/images/wallpaper/yosemitehikes.com-bridalveil-winter-1200x800.jpg" style="max-width:100%" data-modal="1" onclick="fillSlides(this); openModal(); currentSlide(1); " class="hover-shadow cursor">
</div>
</div>
<div id="myModal" class="modal">
<div class="close cursor" onclick="clearSlides(); closeModal();">×</div>
<div class="modal-content" id="modal_content">
<div class="mySlides">
<div class="numbertext">1 / 4</div>
<img src="http://chasingseals.com/wp-content/uploads/2014/02/greenlandBanner2000x800.jpg" class="img">
</div>
<div class="mySlides">
<div class="numbertext">2 / 4</div>
<img src="http://www.catholicevangelism.org/wp-content/uploads/2013/06/1200x800.gif" class="img">
</div>
<div class="mySlides">
<div class="numbertext">3 / 4</div>
<img src="http://www.a1carpet-to.com/wp-content/uploads/2015/08/600x400.png" class="img">
</div>
<div class="mySlides">
<div class="numbertext">4 / 4</div>
<img src="https://support.kickofflabs.com/wp-content/uploads/2016/06/800x1200.png" class="img">
</div>
</div>
</div>
<a class="prev" onclick="plusSlides(-1)">❮</a>
<a class="next" onclick="plusSlides(1)">❯</a>
Since you are adding class 'mySlides' to your slides, you can check if the element you are removing actually contains mySlides class. If it does not you should not remove it.
Also you can move buttons to a separate div. This would separate your slides and controls so it gives you more freedom to manipulate modal content.

Bootstrap Carousel disable cloning after last slide

Hello All these codes working ok for me except one thing - I'd like to stop it when is come to last slide ( 6th slide ) but he is going to clone 1 , 2 and 3 more slides (depends of resolution) and after that it's stops. I am beginner in java script and cannot find solution..Please anyone:
HTML
<div id="package" class="carousel carousel-showmanymoveone slide row" data-ride="carousel">
<div class="carousel-inner">
<div class="item active">
<div class="col-xs-6 col-sm-4 col-xl-3"><img src="http://placehold.it/500/0054A6/fff/&text=1" class="img-responsive"></div>
</div>
<div class="item">
<div class="col-xs-6 col-sm-4 col-xl-3"><img src="http://placehold.it/500/0054A6/fff/&text=2" class="img-responsive"></div>
</div>
<div class="item">
<div class="col-xs-6 col-sm-4 col-xl-3"><img src="http://placehold.it/500/0054A6/fff/&text=3" class="img-responsive"></div>
</div>
<div class="item">
<div class="col-xs-6 col-sm-4 col-xl-3"><img src="http://placehold.it/500/0054A6/fff/&text=4" class="img-responsive"></div>
</div>
<div class="item">
<div class="col-xs-6 col-sm-4 col-xl-3"><img src="http://placehold.it/500/0054A6/fff/&text=5" class="img-responsive"></div>
</div>
<div class="item">
<div class="col-xs-6 col-sm-4 col-xl-3"><img src="http://placehold.it/500/0054A6/fff/&text=6" class="img-responsive"></div>
</div>
</div>
<a class="left carousel-control" href="#package" data-slide="prev"><i class="glyphicon glyphicon-chevron-left strel"></i></a>
<a class="right carousel-control" href="#package" data-slide="next"><i class="glyphicon glyphicon-chevron-right strel"></i></a>
</div>
JAVASCRIPT
(function(){
// setup your carousels as you normally would using JS
// or via data attributes according to the documentation
// http://getbootstrap.com/javascript/#carousel
$('#package').carousel({ interval: false, pause:true });
}());
(function(){
$('.carousel-showmanymoveone .item').each(function(){
var itemToClone = $(this);
for (var i=1;i<4;i++) {
itemToClone = itemToClone.next();
// wrap around if at end of item collection
if (!itemToClone.length) {
itemToClone = $(this).siblings(':first');
}
// grab item, clone, add marker class, add to collection
itemToClone.children(':first-child').clone()
.addClass("cloneditem-"+(i))
.appendTo($(this));
//listener for after slide
jQuery('.carousel-showmanymoveone').on('slid.bs.carousel', function(){
//Each slide has a .item class to it, you can get the total number of slides like this
var totalItems = jQuery('.carousel-showmanymoveone .item').length;
//find current slide number
var currentIndex = jQuery('.carousel-showmanymoveone .item div.active').index() + 1;
//if slide number is last then stop carousel
if(totalItems == currentIndex){
clearInterval(jQuery('.carousel-showmanymoveone .item').data('bs.carousel').interval);
} // end of if
});
}
});
}());
Setting the wrap option to false makes the carousel to stop cycling automatically.
$('#package').carousel({
interval: 1000,
wrap: false
});
Also, you can use data-wrap="false" in the carousel's HTML
EDIT
You can detect first and last slide with this code:
$('#package').on('slid.bs.carousel', '', function() {
var $this = $(this);
if($('.carousel-inner .item:first').hasClass('active')) {
console.log('first slide');
} else if($('.carousel-inner .item:last').hasClass('active')) {
console.log('last slide');
}
});

Javascript in html tags to avoid repetition

I am a newbie to JavaScript and I need to use it with bootstrap for my own web page. My question is now how can I make a loop so that pictures names (stored as an array) can emerge in the right places of the HTML code so I do not have to copy the blocks of code for each picture.
For example :
<div class="row">
<div class="col-md-3 col-xs-6 portfolio-item">
<img class="img-responsive" src="01.jpg">
</div>
</div>
<div class="row">
<div class="col-md-3 col-xs-6 portfolio-item">
<img class="img-responsive" src="01.jpg">
</div>
</div>
<div class="row">
<div class="col-md-3 col-xs-6 portfolio-item">
<img class="img-responsive" src="02.jpg">
</div>
</div>
<div class="row">
<div class="col-md-3 col-xs-6 portfolio-item">
<img class="img-responsive" src="03.jpg">
</div>
</div>
As we can see here the only different text is the src.How can I store the names (paths) in an array and make a loop that changes the src property?
Thank you!
Try this demo: http://jsbin.com/pinoxeqapi/1/edit?html,output
I think that's what you're looking for.
CODE
$(function () {
var images = ["01.jpg", "01.jpg", "02.jpg", "03.jpg"];
$.each(images, function (index, element) {
var imgContainer = "<div class='row'><div class='col-md-3 col-xs-6 portfolio-item><img class='img-responsive' src='" + element + "'></div></div>";
$("body").append(imgContainer);
});
});
First Include JQuery (If not)
<script>
var srcArray = ['01.jpg', '02.jpg', '03.jpg', '04.jpg'];
$(document).ready(function () {
for (var i = 0; i < srcArray.length; i++) {
$('div.row img.img-responsive').eq(i).attr("src", srcArray[i]);
}
});
</script>
I would recommend using one of the templating frameworks described in some of the other answers. If you're interested to see how to implement this in pure JS:
var temp = document.querySelector('#portfolio-item-template');
['01.jpg', '02.jpg', '03.jpg', '04.jpg'].forEach(function(src) {
temp.content.querySelector(".img-responsive").src = src;
var newImg = document.importNode(temp.content, true);
document.querySelector('#insertion-point').appendChild(newImg);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<template id="portfolio-item-template">
<div class="row">
<div class="col-md-3 col-xs-6 portfolio-item">
<img class="img-responsive">
</div>
</div>
</template>
<div id="insertion-point">
</div>
You can use a template stored in the HTML and then generate the actual elements using an array of the image sources. Something like John Resig's micro-templates can achieve this.
<script type="text/template" id="img-tmpl">
<div class="row">
<div class="col-md-3 col-xs-6 portfolio-item>
<img class="img-responsive" src="<%= src %>">
</div>
</div>
</script>

Categories

Resources