Adding Captions to Bootstrap Responsive Modal Image Gallery - javascript

I have a responsive modal image gallery through bootstrap and I'm a beginner at coding. My images were successfully sliding forward and backwards until I tried adding captions.
I've added hover captions to every image using this in my javascript:
$(".popup").wrap('<div class="alt-wrap"/>')
$('.modal-body>caption').remove();
$(".popup").each(function() {
$(this).after('<p class="alt">' + $(this).attr('alt') + '</p>');
})
Now, whenever I click my modal image, the hover caption works fine but once I click next/prev, the old images still remain.
How do I remove the old images/captions when I click next/prev through my modals?
The rest of my js looks like this:
var imagesList = $("div#imagesList");
var imagesListLength = imagesList.children().length;
var showImageGallery = function(imageNumber){
$('.modal-body>img').remove();
$('#imageModal').modal('show');
var image = imagesList.children()[imageNumber];
$(image).clone().appendTo('.modal-body');
$("#currentImageNumber").text(imageNumber);
}
var nextImage = function(){
$('.modal-body>img').remove();
var nextNum = parseInt($("#currentImageNumber").text());
if(nextNum == imagesListLength-1){ nextNum = -1;}
$("#currentImageNumber").text(nextNum+1);
var image = imagesList.children()[nextNum+1];
$(image).clone().appendTo('.modal-body');
}
var previousImage = function(){
$('.modal-body>img').remove();
var previousNum = parseInt($("#currentImageNumber").text());
if(previousNum == 0){ previousNum = imagesListLength;}
$("#currentImageNumber").text(previousNum-1);
var image = imagesList.children()[previousNum-1];
$(image).clone().appendTo('.modal-body');
}
$(window).keydown(function(event) {
if (event.key === 'ArrowLeft') {
previousImage();
}
if (event.key === 'ArrowRight') {
nextImage();
}
if (event.key === 'Escape') {
$('#close-modal').trigger('click')
}
})

I just had to add:
$('.modal-body>.alt-wrap').remove();
under
var showImageGallery = function(imageNumber){
and
$('.modal-body>.alt-wrap').remove();
to my .popup, nextImage, and previousImage functions

Related

How can i replace from jquery to native Js

const img = document.querySelectorAll('img');
that code $(img[data-filter="${filter}"]).show(500);\ replace that code to native JavaScript(show(500) you can replace opacity or display);
i have 9 img at const img, each 3 img have different data-attribute.
Example i click on button and i need to hide or show not all img, but i need to choose 3 img with data-attribute such as I want. how can i write?
const btn = document.querySelectorAll('button');
const img = document.querySelectorAll('img');
function button() {
return function() {
if (this.dataset.check == "on") return;
btn.forEach(e => e.dataset.check = "off");
this.dataset.check = "on";
let filter = (this.dataset.filter == "all") ? "" : `="${ this.dataset.filter }"`;
$("img").hide(500);
$("img[data-filter" + filter + "]").show(500);
}
}
btn.forEach(item => {
item.onclick = button()
})

How to create carousel using javascript and hover to prev and next image with keypress?

I want to create carousel using javascript which have an array of infinity images and after last image ends it should start from first image.On page load the first image should be selected by default and have active border on first image. When keypress right arrow or left arrow the image active border should move accordingly to next or prev image. And when press enter the active border image should get selected and opens link.
I have tried creating carousel but on keypress arrow left or right it doesn't work.
// Hover
var active = document.querySelector(".hover") || document.querySelector(".myImg a");
document.addEventListener("keydown",handler);
document.addEventListener("mouseover",handler);
function handler(e){
console.log(e.which);
active.classList.remove("hover");
switch (e.keyCode) {
case 37:
active = active.previousElementSibling || active;
break;
case 39:
active = active.nextElementSibling || active;
break;
default: active = e.target;
}
active.classList.add("hover");
}
// Carousel
var carousel = document.querySelector('.content');
var slider = document.querySelector('.slider');
var next = document.querySelector('.next');
var prev = document.querySelector('.prev');
var imagesA = document.querySelector('.carousel-img');
// var vid = document.querySelector('.videos');
var direction;
next.addEventListener('click', function () {
direction = -1;
carousel.style.justifyContent = 'flex-start';
slider.style.transform = 'translate(-20%)';
});
prev.addEventListener('click', function () {
if (direction === -1) {
direction = 1;
slider.appendChild(slider.firstElementChild);
}
carousel.style.justifyContent = 'flex-end';
slider.style.transform = 'translate(20%)';
});
slider.addEventListener('transitionend', function () {
if (direction === 1) {
slider.prepend(slider.lastElementChild);
} else {
slider.appendChild(slider.firstElementChild);
}
slider.style.transition = 'none';
slider.style.transform = 'translate(0)';
setTimeout(() => {
slider.style.transition = 'all 0.5s';
})
}, false);
It can be like we see on netflix home carousel where we have list of movies covers but instead of mouse click or mouse over i want same behaviour with Keypress.Please help.
CODE HERE : codepen.io
The keydown events are working, but probably not doing what you expected them to do. Since you already have some logic that is handling next and previous events bound to click, you should extract them as named functions and also use them on the keydown events accordingly.
next.addEventListener("click", goNext);
function goNext() {
direction = -1;
carousel.style.justifyContent = "flex-start";
slider.style.transform = "translate(-10%)";
}
prev.addEventListener("click", goPrev);
function goPrev() {
if (direction === -1) {
direction = 1;
slider.appendChild(slider.firstElementChild);
}
carousel.style.justifyContent = "flex-end";
slider.style.transform = "translate(20%)";
}
Now you have your functions ready, just use them on the switch statement you have:
function handler(e) {
console.log(e.which);
active.classList.remove("hover");
switch (e.keyCode) {
case 37:
goPrev()
break;
case 39:
goNext()
break;
default:
active = e.target;
}
active.classList.add("hover");
}
fork of your pen
There are several other things you will have to fix / improve, so you should probably come back after tweaking your code with some more specific questions.

Canvas overlaying disappearing after enlarge twice on a page

So I am experiencing a weird bug that I do not know how to fix. When I click a button on my website called "Enlarge" it starts an overlay and inside there is a canvas that loads a protein structure. But when I click the close button and try to enlarge it again it loads up nothing and I can't seem to figure out why.
Example HTML
<!-- Expanded Canvas-->
<div id= "myNav" class ="overlay">
X
<div class = "overlay-content">
<div class = "fixed">
</div>
<div id = "viewer2">
<canvas id = "expandedCanvas"></canvas>
</div>
</div>
</div>
</div>
<a id = "expandImage" style = "cursor:pointer">[Enlarge]</a>
<script>
function closeNav() {
document.getElementById("myNav").style.width = "0%";
document.getElementById("sequence-label").style.display = "none";
document.getElementById("picked-atom-name").style.display = "none";
document.getElementById("proteinAlbum").style.display = "none";
}
</script>
The JS
function expandImage() {
expandImageButton = true;
//Start off as default for both the buttons not showing
show("antibodyOn", false);
show("antibodyOff", false);
//Reset the width
document.getElementById("myNav").style.width = "100%";
viewer.requestRedraw();
viewer = pv.Viewer(document.getElementById('viewer2'), {
antialias : true, fog : true,
outline : true, quality : 'high', style : 'phong',
selectionColor : 'white', transparency : 'screendoor',
background : '#111215', animateTime: 500, doubleClick : null,
});
//Fit to the nav bar
viewer.fitParent();
this.value = "";
this.blur();
// Same principle as the loadFromPdb
var XHR = new XMLHttpRequest();
XHR.open("GET", urlPdb, true);
XHR.send();
XHR.onreadystatechange = function () {
if (XHR.readyState === 4) {
if (XHR.status === 200 || XHR.status === 0) {
staticProteinLabel = XHR.responseText.slice(0, XHR.responseText.indexOf("\n")).substr(62, 4).trim();
var canvasStaticLabel = document.getElementById('static-label');
canvasStaticLabel.textContent = staticProteinLabel;
typeOfProtein = XHR.responseText.slice(0, XHR.responseText.indexOf("\n")).substr(10, 26).trim();
var result = XHR.responseText;
var allLines = result.split("\n");
var lineTwo = String(allLines[1]);
alert(lineTwo);
var antibodyText = "ANTIBODY";
if (typeOfProtein === "COMPLEX (ANTIBODY-ANTIGEN)") {
isAntibody = true;
anitbodyOn();
}
else if (lineTwo.indexOf(antibodyText) ) {
isAntibody = true;
antibodyOn();
}
}
}
}
io.fetchPdb(urlPdb, function(s) {
structure = s;
mol.assignHelixSheet(structure);
cartoon();
viewer.autoZoom();
});
}
So I was wondering if it was just the problem with the changing of the width and it can't load up the viewer again and how to go about fixing it?
So I was able to figure it out. The data inside of the canvas needs to be destroyed, so I wrote a little function to erase the data and clear the canvas so it can reload again.

limit javascript toggle according to select box value

Here is link of my current fiddle
jsFiddle
JS --
$('.click').on({
'click': function () {
var origsrc = $(this).attr('src');
var src = '';
if (origsrc == 'http://imageshack.us/a/img703/8236/l6hu.png') src = 'http://imageshack.us/a/img20/1651/fibz.png';
if (origsrc == 'http://imageshack.us/a/img20/1651/fibz.png') src = 'http://imageshack.us/a/img703/8236/l6hu.png';
$(this).attr('src', src);
}
});
i am able to toggle image onclick with another image and vice versa. This is okay, but i want to limit the toggle only when green image is already selected. If i select 3 from select box then i can toggle white image into green image only 3 times, not more than 3. I also need help for another scenerio - if i select 3 from select box and toggle first 3 image and next moment i change the 2nd image into white and click 5th image to turn green then it will be possible. I am week in javascript or jquery, so need proper information about this problem. So plz help me out.
Here is a more comprehensive approach fiddle which will keep your limit in sync and handle discrepancies when the limit changes.
var quantity = 0; // will maintain limit
var stack = []; // will maintain ordered green buttons
$("#select").change(runWrapper);
function runWrapper() {
quantity = Number($("#select").val()); // set the limit
groom(); // turn off those that were turned on last
//run(); // this is your run function, uncomment
}
function groom(){
// let's test if we are over the limit
while(stack.length > quantity) {
// remove last which was set to green
$(stack.pop()).trigger("click")
// to remove the oldest/first set to green use
// $(stack.shift()).trigger("click")
}
}
$('.click').on({
'click': function () {
var origsrc = $(this).attr('src');
var src = '';
if (origsrc == 'http://imageshack.us/a/img703/8236/l6hu.png') {
// limit reached
if(stack.length >= quantity) {
alert(quantity + " limit reached!");
return;
}
src = 'http://imageshack.us/a/img20/1651/fibz.png';
// turning green push the DOM reference to the top of the stack
stack.push(this);
}
if (origsrc == 'http://imageshack.us/a/img20/1651/fibz.png') {
src = 'http://imageshack.us/a/img703/8236/l6hu.png';
// turning white remove the DOM reference from stack
var self = this;
stack = $.grep(stack, function(val) {
return self != val;
})
console.warn(stack);
}
$(this).attr('src', src);
}
});
You can update the function like this - fiddle is here - http://jsfiddle.net/4QkM8/5/
I changed id of select box to selQty
var selectedCount = 0;
$('.click').on({
'click': function () {
var origsrc = $(this).attr('src');
var src = '';
if (origsrc == 'http://imageshack.us/a/img703/8236/l6hu.png'){ if (selectedCount < $('#selQty').val()){src = 'http://imageshack.us/a/img20/1651/fibz.png';
selectedCount ++;
} }
if (origsrc == 'http://imageshack.us/a/img20/1651/fibz.png') {src = 'http://imageshack.us/a/img703/8236/l6hu.png';selectedCount --;}
$(this).attr('src', src == '' ? origsrc : src);
}
});
use a variable to keep track of how many items have been selected, and compare it to the quantity in the select box.
var count = 0;
var unselected_img = 'http://imageshack.us/a/img703/8236/l6hu.png';
var selected_img = 'http://imageshack.us/a/img20/1651/fibz.png';
$('.click').on({
'click': function () {
var max_allowed = parseInt($("#select").val(), 10);
var origsrc = $(this).attr('src');
var src = '';
if (origsrc == unselected_img && count < max_allowed) {
src = selected_img;
count++;
} else if (origsrc == selected_img) {
src = unselected_img;
count--;
} else {
alert("Too many selected.");
}
if (src) {
$(this).attr('src', src);
}
}
});
DEMO

Twitter Bootstrap - Scrolling to #ID using Carousel Images

I am working on twitter bootstrap carousel in a project and have to customize it to apply a custom animation like marquee tag animation. Each item should slide like marquee text element.
I am stuck here and cannot go ahead. Do i have to specify some scrolling time to delay the scrolling between items or something else? (I know we can use interval attribute for time to delay between automatically cycling an item, but i could not achieve marquee effect using it)
Maybe this can help you...
Step 1
Add this JavaScript to your page.
$(function() {
function filterPath(string) {
return string
.replace(/^\//, '')
.replace(/(index|default).[a-zA-Z]{3,4}$/, '')
.replace(/\/$/, '');
}
var locationPath = filterPath(location.pathname);
var scrollElem = scrollableElement('html', 'body');
$('a[href*=#]').each(function() {
var thisPath = filterPath(this.pathname) || locationPath;
if (locationPath == thisPath
&& (location.hostname == this.hostname || !this.hostname)
&& this.hash.replace(/#/, '')) {
var $target = $(this.hash), target = this.hash;
if (target) {
var targetOffset = $target.offset().top;
$(this).click(function(event) {
event.preventDefault();
$(scrollElem).animate({scrollTop: targetOffset}, 400, function() {
location.hash = target;
});
});
}
}
});
// use the first element that is "scrollable"
function scrollableElement(els) {
for (var i = 0, argLength = arguments.length; i < argLength; i++) {
var el = arguments[i],
$scrollElement = $(el);
if ($scrollElement.scrollTop() > 0) {
return el;
} else {
$scrollElement.scrollTop(1);
var isScrollable = $scrollElement.scrollTop() > 0;
$scrollElement.scrollTop(0);
if (isScrollable) {
return el;
}
}
}
return [];
}
});
Step 2
Add an around the images in the carousel - with the ID of the containing element you want to scroll to inserted in the href="#ID"
Then make sure there is a div on the page with the matching ID (if there is not, it won't do anything).
This works amazingly well for me - I know bootstrap will probably have something like this built in, but this works 100% of the time.
Cheers!
I can't remember where I got this code, but if anyone knows I'd like to give credit to them as it's an awesome piece of code.

Categories