I'm using PhotoSwipe in conjunction with Jquery Masonry and navigation does not respond to input. Neither the navigation arrows or key board input (key codes 37 and 39), do not locate images forward or backwards.
</head>
<body>
<div class="page">
<div class="header-container">
<header class="wrapper clearfix">
<div class="menumain">
<div id="logotype">
TEST
</div>
<nav class="menudesktop">
<div class="menu">
<ul>
<li>PORTFOLIO</li>
<li>BIO</li>
<li>CONTACT</li>
<li><i class="fa fa-instagram fa-lg"></i></li>
<li><i class="fa fa-twitter fa-lg"></i></li>
</ul>
</div>
</nav>
<a class="mtoggle"></a>
</header>
</div>
<div class="container-fluid">
<div class="main clearfix">
<div id="content">
<!-- Portfolio Rendering -->
<div class="grid">
<div class="grid-sizer">
<div class="grid-item">
<a href="fashion/01.jpg" data-size="900x1200" data-med="fashion/600/01.jpg" data-med-size="600x800" data-author="">
<img src="fashion/600/01.jpg" alt="" class="over" /><div class="overlay"><img class="zoom" src="images/mag.png" alt="mag" width="37" height="39"></div>
</a>
</div>
<div class="grid-item">
<a href="fashion/02.jpg" data-size="900x1200" data-med="fashion/600/02.jpg" data-med-size="600x900" data-author="">
<img src="fashion/600/02.jpg" alt="" class="over" /><div class="overlay"><img class="zoom" src="images/mag.png" alt="mag" width="37" height="39"></div>
</a>
</div>
<div class="grid-item">
<a href="fashion/03.jpg" data-size="900x1200" data-med="fashion/600/03.jpg" data-med-size="600x800" data-author="">
<img src="fashion/600/03.jpg" alt="" class="over" /><div class="overlay"><img class="zoom" src="images/mag.png" alt="mag" width="37" height="39"></div>
</a>
</div>
<div class="grid-item">
<a href="fashion/04.jpg" data-size="900x1200" data-med="fashion/600/04.jpg" data-med-size="600x906" data-author="">
<img src="fashion/600/04.jpg" alt="" class="over" /><div class="overlay"><img class="zoom" src="images/mag.png" alt="mag" width="37" height="39"></div>
</a>
</div>
</div>
</div>
</div></div></div>
<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">
<div class="pswp__bg"></div>
<div class="pswp__scroll-wrap">
<div class="pswp__container">
<div class="pswp__item"></div>
<div class="pswp__item"></div>
<div class="pswp__item"></div>
</div>
<div class="pswp__ui pswp__ui--hidden">
<div class="pswp__top-bar">
<button class="pswp__button pswp__button--close" title="Close (Esc)"></button>
<button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>
<button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)"></button>
<button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)"></button>
<div class="pswp__preloader">
<div class="pswp__preloader__icn">
<div class="pswp__preloader__cut">
<div class="pswp__preloader__donut"></div>
</div>
</div>
</div>
</div>
<!-- <div class="pswp__loading-indicator"><div class="pswp__loading-indicator__line"></div></div> -->
</div></div></div>
<script type="text/javascript">
(function() {
var initPhotoSwipeFromDOM = function(gallerySelector) {
var parseThumbnailElements = function(el) {
var thumbElements = el.childNodes,
numNodes = thumbElements.length,
items = [],
el,
childElements,
thumbnailEl,
size,
item;
for(var i = 0; i < numNodes; i++) {
el = thumbElements[i];
// include only element nodes
if(el.nodeType !== 1) {
continue;
}
childElements = el.children;
size = el.getAttribute('data-size').split('x');
// create slide object
item = {
src: el.getAttribute('href'),
w: parseInt(size[0], 10),
h: parseInt(size[1], 10),
author: el.getAttribute('data-author')
};
item.el = el; // save link to element for getThumbBoundsFn
if(childElements.length > 0) {
item.msrc = childElements[0].getAttribute('src'); // thumbnail url
if(childElements.length > 1) {
item.title = childElements[1].innerHTML; // caption (contents of figure)
}
}
var mediumSrc = el.getAttribute('data-med');
if(mediumSrc) {
size = el.getAttribute('data-med-size').split('x');
// "medium-sized" image
item.m = {
src: mediumSrc,
w: parseInt(size[0], 10),
h: parseInt(size[1], 10)
};
}
// original image
item.o = {
src: item.src,
w: item.w,
h: item.h
};
items.push(item);
}
return items;
};
// find nearest parent element
var closest = function closest(el, fn) {
return el && ( fn(el) ? el : closest(el.parentNode, fn) );
};
var onThumbnailsClick = function(e) {
e = e || window.event;
e.preventDefault ? e.preventDefault() : e.returnValue = false;
var eTarget = e.target || e.srcElement;
var clickedListItem = closest(eTarget, function(el) {
return el.tagName === 'A';
});
if(!clickedListItem) {
return;
}
var clickedGallery = clickedListItem.parentNode;
var childNodes = clickedListItem.parentNode.childNodes,
numChildNodes = childNodes.length,
nodeIndex = 0,
index;
for (var i = 0; i < numChildNodes; i++) {
if(childNodes[i].nodeType !== 1) {
continue;
}
if(childNodes[i] === clickedListItem) {
index = nodeIndex;
break;
}
nodeIndex++;
}
if(index >= 0) {
openPhotoSwipe( index, clickedGallery );
}
return false;
};
var photoswipeParseHash = function() {
var hash = window.location.hash.substring(1),
params = {};
if(hash.length < 5) { // pid=1
return params;
}
var vars = hash.split('&');
for (var i = 0; i < vars.length; i++) {
if(!vars[i]) {
continue;
}
var pair = vars[i].split('=');
if(pair.length < 2) {
continue;
}
params[pair[0]] = pair[1];
}
if(params.gid) {
params.gid = parseInt(params.gid, 10);
}
return params;
};
var openPhotoSwipe = function(index, galleryElement, disableAnimation, fromURL) {
var pswpElement = document.querySelectorAll('.pswp')[0],
gallery,
options,
items;
items = parseThumbnailElements(galleryElement);
// define options (if needed)
options = {
galleryUID: galleryElement.getAttribute('data-pswp-uid'),
getThumbBoundsFn: function(index) {
// See Options->getThumbBoundsFn section of docs for more info
var thumbnail = items[index].el.children[0],
pageYScroll = window.pageYOffset || document.documentElement.scrollTop,
rect = thumbnail.getBoundingClientRect();
return {x:rect.left, y:rect.top + pageYScroll, w:rect.width};
},
addCaptionHTMLFn: function(item, captionEl, isFake) {
if(!item.title) {
captionEl.children[0].innerText = '';
return false;
}
captionEl.children[0].innerHTML = item.title + '<br/><small>Photo: ' + item.author + '</small>';
return true;
},
};
if(fromURL) {
if(options.galleryPIDs) {
// parse real index when custom PIDs are used
// http://photoswipe.com/documentation/faq.html#custom-pid-in-url
for(var j = 0; j < items.length; j++) {
if(items[j].pid == index) {
options.index = j;
break;
}
}
} else {
options.index = parseInt(index, 10) - 1;
}
} else {
options.index = parseInt(index, 10);
}
// exit if index not found
if( isNaN(options.index) ) {
return;
}
var radios = document.getElementsByName('gallery-style');
for (var i = 0, length = radios.length; i < length; i++) {
if (radios[i].checked) {
if(radios[i].id == 'radio-all-controls') {
} else if(radios[i].id == 'radio-minimal-black') {
options.mainClass = 'pswp--minimal--dark';
options.barsSize = {top:0,bottom:0};
options.captionEl = false;
options.fullscreenEl = false;
options.shareEl = false;
options.bgOpacity = 0.85;
options.tapToClose = true;
options.tapToToggleControls = false;
}
break;
}
}
if(disableAnimation) {
options.showAnimationDuration = 0;
}
// Pass data to PhotoSwipe and initialize it
gallery = new PhotoSwipe( pswpElement, PhotoSwipeUI_Default, items, options);
// see: http://photoswipe.com/documentation/responsive-images.html
var realViewportWidth,
useLargeImages = false,
firstResize = true,
imageSrcWillChange;
gallery.listen('beforeResize', function() {
var dpiRatio = window.devicePixelRatio ? window.devicePixelRatio : 1;
dpiRatio = Math.min(dpiRatio, 2.5);
realViewportWidth = gallery.viewportSize.x * dpiRatio;
if(realViewportWidth >= 1200 || (!gallery.likelyTouchDevice && realViewportWidth > 800) || screen.width > 1200 ) {
if(!useLargeImages) {
useLargeImages = true;
imageSrcWillChange = true;
}
} else {
if(useLargeImages) {
useLargeImages = false;
imageSrcWillChange = true;
}
}
if(imageSrcWillChange && !firstResize) {
gallery.invalidateCurrItems();
}
if(firstResize) {
firstResize = false;
}
imageSrcWillChange = false;
});
gallery.listen('gettingData', function(index, item) {
if( useLargeImages ) {
item.src = item.o.src;
item.w = item.o.w;
item.h = item.o.h;
} else {
item.src = item.m.src;
item.w = item.m.w;
item.h = item.m.h;
}
});
gallery.init();
};
// select all gallery elements
var galleryElements = document.querySelectorAll( gallerySelector );
for(var i = 0, l = galleryElements.length; i < l; i++) {
galleryElements[i].setAttribute('data-pswp-uid', i+1);
galleryElements[i].onclick = onThumbnailsClick;
}
// Parse URL and open gallery if it contains #&pid=3&gid=1
var hashData = photoswipeParseHash();
if(hashData.pid && hashData.gid) {
openPhotoSwipe( hashData.pid, galleryElements[ hashData.gid - 1 ], true, true );
}
};
initPhotoSwipeFromDOM('.grid-item');
})();
</script>
FIXED
Removed the
<div class="grid-item">
<a href="fashion/01.jpg" data-size="900x1200" data-med="fashion/600/01.jpg" data-med-size="600x800" data-author="">
<img src="fashion/600/01.jpg" alt="" class="over" /><div class="overlay"><img class="zoom" src="images/mag.png" alt="mag" width="37" height="39"></div>
</a>
</div>
and replaced with:
<a class="grid-item" href="fashion/01.jpg" data-size="900x1200" data-med="fashion/600/01.jpg" data-med-size="600x800" data-author="">
<img src="fashion/600/01.jpg" alt="" class="over" /><div class="overlay"><img class="zoom" src="images/mag.png" alt="mag" width="37" height="39"></div>
</a>
Related
I already built a simple product configurator using HTML/CSS and JS (jQuery), but my project needs advanced filtering based on user's values.
Short project description - a special strollers configurator where You can select a product, put some accessories and order it.
What do I need?
Advanced filtering based on user's measurements (height, weight up to 10 unique values) which will show only compatibile products. Every stroller has a value range (Stroller1 has a height range from 100 to 130 cm). How to add this kind of form to my already existing project?
Code snippet:
jQuery(document).ready(function($) {
function ProductBuilder(element) {
this.element = element;
this.stepsWrapper = this.element.children('.cd-builder-steps');
this.steps = this.element.find('.builder-step');
this.models = this.element.find('[data-selection="models"]');
this.summary;
this.optionsLists = this.element.find('.options-list');
//podsumowanie
this.fixedSummary = this.element.find('.cd-builder-footer');
this.modelPreview = this.element.find('.selected-product').find('img');
this.totPriceWrapper = this.element.find('.tot-price').find('b');
//nawigacja
this.mainNavigation = this.element.find('.cd-builder-main-nav');
this.secondaryNavigation = this.element.find('.cd-builder-secondary-nav');
//sprawdza, czy wszystko sie poprawnie zaladowalo
this.loaded = true;
this.bindEvents();
}
ProductBuilder.prototype.bindEvents = function() {
var self = this;
//wykrywa klikniecie na nawigacje z lewej strony
this.mainNavigation.on('click', 'li:not(.active)', function(event) {
event.preventDefault();
self.loaded && self.newContentSelected($(this).index());
});
//wykrywa klikniecie na dole
this.secondaryNavigation.on('click', '.nav-item li:not(.buy)', function(event) {
event.preventDefault();
var stepNumber = ($(this).parents('.next').length > 0) ? $(this).index() + 1 : $(this).index() - 1;
self.loaded && self.newContentSelected(stepNumber);
});
//wykrywa klik na liscie u gory (podsumowanie, kolory itd)
this.optionsLists.on('click', '.js-option', function(event) {
self.updateListOptions($(this));
});
//wykrywa klik podczas "ubierania" sprzetu
this.stepsWrapper.on('click', '.cd-product-customizer a', function(event) {
event.preventDefault();
self.customizeModel($(this));
});
};
ProductBuilder.prototype.newContentSelected = function(nextStep) {
//sprawdza, czy produkt zostal wybrany
if (this.fixedSummary.hasClass('disabled')) {
//jesli nie - pokazuje alert
this.fixedSummary.addClass('show-alert');
} else {
//jezeli zostal wybrany, przechodzi dalej
//sprawdza, czy kolor zostal wybrany
if (this.steps.filter('.active').is('[data-selection="colors"]')) {
//jezeli kolor zostal zmieniony, zaktualizuj zdjecie
var imageSelected = this.steps.filter('.active').find('.cd-product-previews').children('.selected').children('img').attr('src');
this.modelPreview.attr('src', imageSelected);
}
//zaktualizuj podglad produktu na dole
if (nextStep + 1 >= this.steps.length) {
this.createSummary();
}
this.showNewContent(nextStep);
this.updatePrimaryNav(nextStep);
this.updateSecondaryNav(nextStep);
}
}
ProductBuilder.prototype.showNewContent = function(nextStep) {
var actualStep = this.steps.filter('.active').index() + 1;
if (actualStep < nextStep + 1) {
//nawiguj do nastepnej sekcji
this.steps.eq(actualStep - 1).removeClass('active back').addClass('move-left');
this.steps.eq(nextStep).addClass('active').removeClass('move-left back');
} else {
//powroc do poprzedniej sekcji
this.steps.eq(actualStep - 1).removeClass('active back move-left');
this.steps.eq(nextStep).addClass('active back').removeClass('move-left');
}
}
ProductBuilder.prototype.updatePrimaryNav = function(nextStep) {
this.mainNavigation.find('li').eq(nextStep).addClass('active').siblings('.active').removeClass('active');
}
ProductBuilder.prototype.updateSecondaryNav = function(nextStep) {
(nextStep == 0) ? this.fixedSummary.addClass('step-1'): this.fixedSummary.removeClass('step-1');
this.secondaryNavigation.find('.nav-item.next').find('li').eq(nextStep).addClass('visible').removeClass('visited').prevAll().removeClass('visited').addClass('visited').end().nextAll().removeClass('visible visited');
this.secondaryNavigation.find('.nav-item.prev').find('li').eq(nextStep).addClass('visible').removeClass('visited').prevAll().removeClass('visited').addClass('visited').end().nextAll().removeClass('visible visited');
}
ProductBuilder.prototype.createSummary = function() {
var self = this;
this.steps.each(function() {
var step = $(this);
if ($(this).data('selection') == 'colors') {
//podsumowanie - kolor
var colorSelected = $(this).find('.cd-product-customizer').find('.selected'),
color = colorSelected.children('a').data('color'),
colorName = colorSelected.data('content'),
imageSelected = $(this).find('.cd-product-previews').find('.selected img').attr('src');
self.summary.find('.summary-color').find('.color-label').text(colorName).siblings('.color-swatch').attr('data-color', color);
self.summary.find('.product-preview').attr('src', imageSelected);
} else if ($(this).data('selection') == 'accessories') {
var selectedOptions = $(this).find('.js-option.selected'),
optionsContent = '';
if (selectedOptions.length == 0) {
optionsContent = '<li><p>Nie wybrano żadnych akcesoriów;</p></li>';
} else {
selectedOptions.each(function() {
optionsContent += '<li><p>' + $(this).find('p').text() + '</p></li>';
});
}
self.summary.find('.summary-accessories').children('li').remove().end().append($(optionsContent));
}
});
}
ProductBuilder.prototype.updateListOptions = function(listItem) {
var self = this;
if (listItem.hasClass('js-radio')) {
//pozwala na wybranie tylko jednej opcji w produktach
var alreadySelectedOption = listItem.siblings('.selected'),
price = (alreadySelectedOption.length > 0) ? -Number(alreadySelectedOption.data('price')) : 0;
//odznaczenie opcji
(listItem.hasClass('selected')) ?
price = -Number(listItem.data('price')): price = Number(listItem.data('price')) + price;
//odznacz wszystkie opcje
alreadySelectedOption.removeClass('selected');
//przelacz opcje
listItem.toggleClass('selected');
//zaktualizuj totalPrice
(listItem.parents('[data-selection="models"]').length == 0) && self.updatePrice(price);
} else {
//mozna wybrac jedna niz wiecej opcji
var price = (listItem.hasClass('selected')) ? -Number(listItem.data('price')) : Number(listItem.data('price'));
//przelacz opcje
listItem.toggleClass('selected');
//zaktualizuj totalPrice
self.updatePrice(price);
}
if (listItem.parents('[data-selection="models"]').length > 0) {
self.updateModelContent(listItem);
}
};
ProductBuilder.prototype.updateModelContent = function(model) {
var self = this;
if (model.hasClass('selected')) {
var modelType = model.data('model'),
modelImage = model.find('img').attr('src');
this.modelPreview.attr('src', modelImage);
//usun tresc odnoszaca sie do innego modelu
this.models.siblings('li').remove();
//zaladuj nowa tresc
$.ajax({
type: "GET",
dataType: "html",
url: modelType + ".html",
beforeSend: function() {
self.loaded = false;
model.siblings().removeClass('loaded');
},
success: function(data) {
self.models.after(data);
self.loaded = true;
model.addClass('loaded');
//aktywuj nawigacje
self.fixedSummary.add(self.mainNavigation).removeClass('disabled show-alert');
//zaktualizuj dane obiektu
self.steps = self.element.find('.builder-step');
self.summary = self.element.find('[data-selection="summary"]');
//wykrywa klik na liscie opcji
self.optionsLists.off('click', '.js-option');
self.optionsLists = self.element.find('.options-list');
self.optionsLists.on('click', '.js-option', function(event) {
self.updateListOptions($(this));
});
//nie wczytuj animacji przy pierwszym wczytaniu nowej zawartosci
self.element.find('.first-load').removeClass('first-load');
},
error: function(jqXHR, textStatus, errorThrown) {}
});
//zaktualizuj cene
this.totPriceWrapper.text(model.data('price'));
} else {
//nie wybrano produktu
this.fixedSummary.add(this.mainNavigation).addClass('disabled');
//zaktualizuj cene
this.totPriceWrapper.text('0');
this.models.find('.loaded').removeClass('loaded');
}
};
ProductBuilder.prototype.customizeModel = function(target) {
var parent = target.parent('li')
index = parent.index();
//zaktualizuj podsumowanie
var price = (parent.hasClass('selected')) ?
0 :
Number(parent.data('price')) - parent.siblings('.selected').data('price');
this.updatePrice(price);
target.parent('li').addClass('selected').siblings().removeClass('selected').parents('.cd-product-customizer').siblings('.cd-product-previews').children('.selected').removeClass('selected').end().children('li').eq(index).addClass('selected');
};
ProductBuilder.prototype.updatePrice = function(price) {
var actualPrice = Number(this.totPriceWrapper.text()) + price;
this.totPriceWrapper.text(actualPrice);
};
if ($('.cd-product-builder').length > 0) {
$('.cd-product-builder').each(function() {
new ProductBuilder($(this));
});
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<div class="cd-product-builder">
<header class="main-header">
<h1>Wybierz odpowiedni produkt</h1>
<nav class="cd-builder-main-nav disabled">
<ul>
<li class="active">Produkt</li>
<li>Kolorystyka</li>
<li>Akcesoria</li>
<li>Podsumowanie</li>
</ul>
</nav>
</header>
<div class="cd-builder-steps">
<ul>
<li data-selection="models" class="active builder-step">
<section class="cd-step-content">
<header>
<h1>Wybierz produkt</h1>
<span class="steps-indicator">Step <b>1</b> of 4</span>
</header>
<!-- ponizej sa wszystkie 4 produkty -->
<ul class="models-list options-list cd-col-2">
<li class="js-option js-radio" data-price="2499" data-model="product-01">
<span class="name">Tatalu</span>
<img src="img/tat01.jpg" alt="wzrost100">
<span class="price">Idealny dla dzieci do 100 cm wzrostu. <br>Dostępny już od 2499 zł</span>
<div class="radio"></div>
</li>
<li class="js-option js-radio" data-price="3549" data-model="product-02">
<span class="name">Mamalu</span>
<img src="img/mam01.jpg" alt="wzrost130">
<span class="price">Idealny dla dzieci do 130 cm wzrostu. <br>Dostępny już od 3549 zł</span>
<div class="radio"></div>
</li>
<li class="js-option js-radio" data-price="4499" data-model="product-03">
<span class="name">Ulises</span>
<img src="img/ule01.jpg" alt="wzrost150">
<span class="price">Idealny dla dzieci do 150 cm wzrostu. <br>Dostępny już od 4499 zł</span>
<div class="radio"></div>
</li>
<li class="js-option js-radio" data-price="5999" data-model="product-04">
<span class="name">Ursus</span>
<img src="img/ursus02.jpg" alt="wzrost180">
<span class="price">Idealny dla dorosłych do 180 cm wzrostu. <br>Dostępny już od 5999 zł</span>
<div class="radio"></div>
</li>
</ul>
</section>
</li>
</ul>
</div>
<footer class="cd-builder-footer disabled step-1">
<div class="selected-product">
<img src="img/tat01.jpg" alt="Product preview">
<div class="tot-price">
<span>Podsumowanie</span>
<span class="total"><b>0</b> zł</span>
</div>
</div>
<nav class="cd-builder-secondary-nav">
<ul>
<li class="next nav-item">
<ul>
<li class="visible">Kolorystyka</li>
<li>Akcesoria</li>
<li>Podsumowanie</li>
<li class="buy">Kup teraz</li>
</ul>
</li>
<li class="prev nav-item">
<ul>
<li class="visible">Produkt</li>
<li>Produkt</li>
<li>Kolorystyka</li>
<li>Akcesoria</li>
</ul>
</li>
</ul>
</nav>
<span class="alert">Aby kontynuować, wybierz produkt</span>
</footer>
</div>
What do I need? Advanced filtering based on user's measurements (height, weight up to 10 unique values) which will show only compatibile products. Every stroller has a value range (Stroller1 has a height range from 100 to 130 cm). How to add this kind of form to my already existing project?
I have the following landing page
When the page loads I want the left page to be active as shown unfortunately for now when the page loads both the left menu and the right menu are active.If I click on the right menu it does not work.
Hosted site
https://leskoy.bonusgigs.com/
window.onload = function() {
document.getElementById('scarves').className = '';
document.getElementsByClassName('rightlinks')[0].className = 'active'
};
function openLeftMenu(menu) {
if (menu === 'scarves') {
document.getElementById('scarves').className = '';
document.getElementById('stockists').className = 'content';
document.getElementById('scarvesBtn').className = 'active';
document.getElementById('stockistsBtn').className = '';
}
if (menu === 'stockists') {
document.getElementById('stockists').className = '';
document.getElementById('scarves').className = 'content';
document.getElementById('stockistsBtn').className = 'active';
document.getElementById('scarvesBtn').className = '';
}
}
window.onload = function() {
document.getElementById('why').className = '';
document.getElementsByClassName('tablinks')[0].className = 'active'
};
function openMenu(menu) {
if (menu === 'why') {
document.getElementById('why').className = '';
document.getElementById('process').className = 'content';
document.getElementById('whyBtn').className = 'active';
document.getElementById('processBtn').className = '';
}
if (menu === 'process') {
document.getElementById('process').className = '';
document.getElementById('why').className = 'content';
document.getElementById('processBtn').className = 'active';
document.getElementById('whyBtn').className = '';
}
if (menu === 'connect') {
document.getElementById('connect').className = '';
document.getElementById('process').className = 'content';
document.getElementById('connectBtn').className = 'active';
document.getElementById('whyBtn').className = '';
}
if (menu === 'faq') {
document.getElementById('faq').className = '';
document.getElementById('process').className = 'content';
document.getElementById('faqBtn').className = 'active';
document.getElementById('whyBtn').className = '';
}
}
<div class="leftpane">
<nav style="margin-top: 30px;" id="menu">
<a class="tablinks " onclick="openMenu('why')" id="whyBtn">
<h2 class="cooler">why<span class="arrow"></span></h2>
</a>
<a class="tablinks" onclick="openMenu('process')" id="processBtn">
<h2 class="cooler">process<span class="arrow"></span></h2>
</a>
</nav>
</div>
<div class="middlepane">
<div class="content" id="why"></div>
<div class="content" id="process"></div>
<div class="content" id="scarves"></div>
<div class="content" id="stockists"></div>
</div>
<div class="rightpane">
<div style="margin-top: 60%;">
<nov id="menu">
<a class="rightlinks" onclick="openLeftMenu('scarves')" id="scarvesBtn">
<h2 class="drool">scarves<span class="arrow"></span></h2>
</a>
<a class="rightlinks" onclick="openLeftMenu('stockists')" id="stockistsBtn">
<h2 class="drool">stockists<span class="arrow"></span></h2>
</a>
</nov>
</div>
</div>
Here is how to do more than one thing in the onload.
Also note how I cache the elements and address the first of the class using querySelector
window.addEventListener("DOMContentLoaded", function() {
const scarves = document.getElementById('scarves');
const scarvesBtn = document.getElementById('scarvesBtn');
const stockists = document.getElementById('stockists');
const stockistsBtn = document.getElementById('stockistsBtn');
const why = document.getElementById('why');
const rightlinks = document.querySelector('.rightlinks');
const tablinks = document.querySelector('.tablinks')
const openLeftMenu = menu => {
scarves.classList.toggle("content", menu === 'stockists')
scarvesBtn.classList.toggle("active", menu === 'scarves')
stockists.classList.toggle("content", menu === 'scarves')
.classList.toggle("active", menu === 'stockists')
}
// init
scarves.classList.remove("active");
why.classList.remove("active");
rightlinks.classList.add("active");
tablinks.classList.add("active");
});
I want to build some simple photo gallery with PhotoSwipe: http://codepen.io/dimsemenov/pen/ZYbPJM.
All code is work fine, but when I try to add new HTML, some function like Previous / Next button does not work.
Original code
<div class="my-gallery" itemscope itemtype="http://schema.org/ImageGallery">
<figure itemprop="associatedMedia" itemscope itemtype="http://schema.org/ImageObject">
<a href="https://farm3.staticflickr.com/2567/5697107145_a4c2eaa0cd_o.jpg" itemprop="contentUrl" data-size="1024x1024">
<img src="https://farm3.staticflickr.com/2567/5697107145_3c27ff3cd1_m.jpg" itemprop="thumbnail" alt="Image description" />
</a>
<figcaption itemprop="caption description">Image caption 1</figcaption>
</figure>
<figure itemprop="associatedMedia" itemscope itemtype="http://schema.org/ImageObject">
<a href="https://farm2.staticflickr.com/1043/5186867718_06b2e9e551_b.jpg" itemprop="contentUrl" data-size="964x1024">
<img src="https://farm2.staticflickr.com/1043/5186867718_06b2e9e551_m.jpg" itemprop="thumbnail" alt="Image description" />
</a>
<figcaption itemprop="caption description">Image caption 2</figcaption>
</figure>
And this code from my photo gallery
<div class="my-gallery" itemscope itemtype="http://schema.org/ImageGallery">
<div class="col-sm-3 col-md-2 thumb-container" data-image="o3gx9ze57" data-hotlink="9x16er3a7" data-sid="s25">
<div class="thumb">
<figure itemprop="associatedMedia" itemscope itemtype="http://schema.org/ImageObject">
<a href="https://farm3.staticflickr.com/2567/5697107145_a4c2eaa0cd_o.jpg" itemprop="contentUrl" data-size="1024x1024">
<img src="https://farm3.staticflickr.com/2567/5697107145_3c27ff3cd1_m.jpg" itemprop="thumbnail" alt="Image description" />
</a>
<figcaption itemprop="caption description">Image caption 1</figcaption>
</figure>
</div>
</div>
<div class="col-sm-3 col-md-2 thumb-container" data-image="o3gx9ze57" data-hotlink="9x16er3a7" data-sid="s25">
<div class="thumb">
<figure itemprop="associatedMedia" itemscope itemtype="http://schema.org/ImageObject">
<a href="https://farm2.staticflickr.com/1043/5186867718_06b2e9e551_b.jpg" itemprop="contentUrl" data-size="964x1024">
<img src="https://farm2.staticflickr.com/1043/5186867718_06b2e9e551_m.jpg" itemprop="thumbnail" alt="Image description" />
</a>
<figcaption itemprop="caption description">Image caption 2</figcaption>
</figure>
</div>
</div>
</div>
I know, the problem is from my JavaSrcipt code but I have no idea to fix it.
var initPhotoSwipeFromDOM = function(gallerySelector) {
// parse slide data (url, title, size ...) from DOM elements
// (children of gallerySelector)
var parseThumbnailElements = function(el) {
var thumbElements = el.childNodes,
numNodes = thumbElements.length,
items = [],
figureEl,
linkEl,
size,
item;
for(var i = 0; i < numNodes; i++) {
figureEl = thumbElements[i]; // <figure> element
// include only element nodes
if(figureEl.nodeType !== 1) {
continue;
}
linkEl = figureEl.children[0]; // <a> element
size = linkEl.getAttribute('data-size').split('x');
// create slide object
item = {
src: linkEl.getAttribute('href'),
w: parseInt(size[0], 10),
h: parseInt(size[1], 10)
};
if(figureEl.children.length > 1) {
// <figcaption> content
item.title = figureEl.children[1].innerHTML;
}
if(linkEl.children.length > 0) {
// <img> thumbnail element, retrieving thumbnail url
item.msrc = linkEl.children[0].getAttribute('src');
}
item.el = figureEl; // save link to element for getThumbBoundsFn
items.push(item);
}
return items;
};
// find nearest parent element
var closest = function closest(el, fn) {
return el && ( fn(el) ? el : closest(el.parentNode, fn) );
};
// triggers when user clicks on thumbnail
var onThumbnailsClick = function(e) {
e = e || window.event;
e.preventDefault ? e.preventDefault() : e.returnValue = false;
var eTarget = e.target || e.srcElement;
// find root element of slide
var clickedListItem = closest(eTarget, function(el) {
return (el.tagName && el.tagName.toUpperCase() === 'FIGURE');
});
if(!clickedListItem) {
return;
}
// find index of clicked item by looping through all child nodes
// alternatively, you may define index via data- attribute
var clickedGallery = clickedListItem.parentNode,
childNodes = clickedListItem.parentNode.childNodes,
numChildNodes = childNodes.length,
nodeIndex = 0,
index;
for (var i = 0; i < numChildNodes; i++) {
if(childNodes[i].nodeType !== 1) {
continue;
}
if(childNodes[i] === clickedListItem) {
index = nodeIndex;
break;
}
nodeIndex++;
}
if(index >= 0) {
// open PhotoSwipe if valid index found
openPhotoSwipe( index, clickedGallery );
}
return false;
};
// parse picture index and gallery index from URL (#&pid=1&gid=2)
var photoswipeParseHash = function() {
var hash = window.location.hash.substring(1),
params = {};
if(hash.length < 5) {
return params;
}
var vars = hash.split('&');
for (var i = 0; i < vars.length; i++) {
if(!vars[i]) {
continue;
}
var pair = vars[i].split('=');
if(pair.length < 2) {
continue;
}
params[pair[0]] = pair[1];
}
if(params.gid) {
params.gid = parseInt(params.gid, 10);
}
return params;
};
var openPhotoSwipe = function(index, galleryElement, disableAnimation, fromURL) {
var pswpElement = document.querySelectorAll('.pswp')[0],
gallery,
options,
items;
items = parseThumbnailElements(galleryElement);
// define options (if needed)
options = {
// define gallery index (for URL)
galleryUID: galleryElement.getAttribute('data-pswp-uid'),
getThumbBoundsFn: function(index) {
// See Options -> getThumbBoundsFn section of documentation for more info
var thumbnail = items[index].el.getElementsByTagName('img')[0], // find thumbnail
pageYScroll = window.pageYOffset || document.documentElement.scrollTop,
rect = thumbnail.getBoundingClientRect();
return {x:rect.left, y:rect.top + pageYScroll, w:rect.width};
}
};
// PhotoSwipe opened from URL
if(fromURL) {
if(options.galleryPIDs) {
// parse real index when custom PIDs are used
// http://photoswipe.com/documentation/faq.html#custom-pid-in-url
for(var j = 0; j < items.length; j++) {
if(items[j].pid == index) {
options.index = j;
break;
}
}
} else {
// in URL indexes start from 1
options.index = parseInt(index, 10) - 1;
}
} else {
options.index = parseInt(index, 10);
}
// exit if index not found
if( isNaN(options.index) ) {
return;
}
if(disableAnimation) {
options.showAnimationDuration = 0;
}
// Pass data to PhotoSwipe and initialize it
gallery = new PhotoSwipe( pswpElement, PhotoSwipeUI_Default, items, options);
gallery.init();
};
// loop through all gallery elements and bind events
var galleryElements = document.querySelectorAll( gallerySelector );
for(var i = 0, l = galleryElements.length; i < l; i++) {
galleryElements[i].setAttribute('data-pswp-uid', i+1);
galleryElements[i].onclick = onThumbnailsClick;
}
// Parse URL and open gallery if it contains #&pid=3&gid=1
var hashData = photoswipeParseHash();
if(hashData.pid && hashData.gid) {
openPhotoSwipe( hashData.pid , galleryElements[ hashData.gid - 1 ], true, true );
}
};
// execute above function
initPhotoSwipeFromDOM('.my-gallery');
How to fix that?
Live Demo here : http://codepen.io/dimsemenov/pen/ZYbPJM
execute above function initPhotoSwipeFromDOM('.thumb'); – Alive to Die 24 mins ago
#alive to die : not work
your hashData (in L198) is an empty object (without .pid)
the fundtion photoswipeParseHash return {},
so the if in L199 is not true,
which cause your openPhotoSwipe not executed.
So I'm making a dental website, this page I'm working on is for dental cases. So let's say there are three dental treatments, Dental Implants, Root Canal and Tooth Extraction. I'm developing something like, if someone clicks on Dental Implants, he can see a modal window, for the cases for that particular treatment. When he clicks on one of the cases, he can see a slideshow for that case. It works perfectly, but the only thing is that when I click on the dental implants or fracture case, I'm seeing the same modal window content. I found the code from w3school's website. Is there any way I can have multiple modal windows with different content? Thanks so much.
Screenshot of the window
I have a large project that use what you want. I'll try to reduce other codes for you understand better. I'll need to include in your bootstrap plugin.
1) Bellow you'll see two pictures with initial image and after click on some image:
2) Html (I insert dynamically all of datas by jquery with request on a server):
<div class="row content-side-imagem">
<div id="fourth-slide" class="carousel slide" produto1-ini="0" produto1-fim="0" produto1-seq="0" produto1-qtpagina="0">
<div class="carousel-inner">
<div class="item active">
<div class="col-sm-4 fourth-slide-imagem" >
<a class="galeriaImagens" data-toggle="modal" data-target="#galeriaImagens" data-backdrop="false">
<img id="produto1-imagem1" src="" alt="" title="" class="img-responsive center-block" >
<div class="carousel-caption">
<p id="produto1-legenda1" class="fourth-slide-legenda">
</p>
<p id="produto1-item1">
</p>
</div>
</a>
</div>
<div class="col-sm-4 fourth-slide-imagem" >
<a class="galeriaImagens" data-toggle="modal" data-target="#galeriaImagens" data-backdrop="false">
<img id="produto1-imagem2" src="" alt="" title="" class="img-responsive center-block" >
<div class="carousel-caption">
<p id="produto1-legenda2" class="fourth-slide-legenda">
</p>
<p id="produto1-item2">
</p>
</div>
</a>
</div>
<div class="col-sm-4 fourth-slide-imagem" >
<a class="galeriaImagens" data-toggle="modal" data-target="#galeriaImagens" data-backdrop="false">
<img id="produto1-imagem3" src="" alt="" title="" class="img-responsive center-block" >
<div class="carousel-caption">
<p id="produto1-legenda3" class="fourth-slide-legenda">
</p>
<p id="produto1-item3">
</p>
</div>
</a>
</div>
</div>
</div>
<div class="slides-control">
<a title="Imagem Anterior" id="tras-produto1-slide" class="carousel-control" href="#fourth-slide" data-slide="prev">
<i class="fa fa-angle-left"></i>
</a>
<a title="Imagem Posterior" id="frente-produto1-slide" class="direita carousel-control" href="#fourth-slide" data-slide="next">
<i class="fa fa-angle-right"></i>
</a>
</div>
</div>
</div>
<div class="modal fade" id="galeriaImagens" role="dialog">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<div class="numSlide5">
<p class="numSlide5Texto text-center"></p>
</div>
</div>
<div class="modal-body">
<div class="carousel slide" id="fith-slide" data-ride="carousel">
<div class="carousel-inner">
<div class="item">
<img id="slide5-imagem1" alt="" title="" src="" class="img-responsive center-block">
<div class="carousel-caption">
<div id="slide5-legenda1" class="fith-slide-legenda">
</div>
</div>
</div>
</div>
<div class="slides-control">
<a title="Imagem Anterior" id="tras-slide5-slide" class="carousel-control" href="#fith-slide" data-slide="prev">
<i class="fa fa-angle-left"></i>
</a>
<a title="Imagem Posterior" id="frente-slide5-slide" class="direita carousel-control" href="#fith-slide" data-slide="next">
<i class="fa fa-angle-right"></i>
</a>
</div>
</div>
</div>
</div>
</div>
3) jquery (call for first line carousel and for the second inside modal)
$(document).ready(function () {
$('.galeriaImagens').click(function () {
var descricaoLegenda = $(this).children('div.carousel-caption').children('.fourth-slide-legenda').text();
var listaLegenda = $('#fith-slide').children('.carousel-inner').children('.item')
.children('.carousel-caption').children('.fith-slide-legenda');
$('#fith-slide').find('.item.active').removeClass('active');
$.each(listaLegenda, function (index, value) {
if (descricaoLegenda == value.innerText)
{
var selecao = value;
$(selecao).parents('.item').addClass('active');
}
});
var totalItems = $('#fith-slide .item').length;
var currentIndex = $('#fith-slide div.active').index() + 1;
$('.numSlide5Texto').html('' + currentIndex + '/' + totalItems + '');
$('#fith-slide').bind('slid', function () {
currentIndex = $('#fith-slide div.active').index() + 1;
$('.numSlide5Texto').html('' + currentIndex + '/' + totalItems + '');
});
});
// slide 1 - imagens
var urlDestino = "";
var idEnvio = 0;
var nrReg = 0;
var idProduto = 0;
var frente = "S";
function slide1() {
$.ajax({
url: urlDestino,
type: "POST",
data: { "id": idEnvio, "idProduto": idProduto, "nrRegistro": nrReg },
async: true,
dataType: "json",
success: function (data) {
if (document.getElementById("fourth-slide").getAttribute("produto1-ini") == 0) {
if (data.lista.length == 0 || data.lista == "0") {
$('#fotos-imovel').hide();
$('.fotos-imovel-icone').hide();
}
}
if (data.lista.length == 0)
return;
if (data == "") {
return;
}
var i = data.lista.length;
if (i > 0) {
i = i - 1;
}
var item = document.getElementById("fourth-slide").getAttribute("produto1-seq");
if (frente == "N") {
var qtdPagina = document.getElementById("fourth-slide").getAttribute("produto1-qtpagina");
qtdPagina = parseInt(qtdPagina);
item = item - (3 + qtdPagina);
}
if (i == 2) {
item++;
$('#produto1-item1').html(item + " / " + data.qtd);
$('#produto1-legenda1').html(data.lista[0].Descricao);
$('#produto1-imagem1').attr("src", data.lista[0].EnderecoImagem);
$('#produto1-imagem1').attr("title", data.lista[0].Descricao);
$('#produto1-imagem1').attr("alt", data.lista[0].DescricaoAlternativa);
$('#produto1-imagem1').attr("width", data.lista[0].Largura);
$('#produto1-imagem1').attr("height", data.lista[0].Altura);
item++;
$('#produto1-item2').html(item + " / " + data.qtd);
$('#produto1-legenda2').html(data.lista[1].Descricao);
$('#produto1-imagem2').attr("src", data.lista[1].EnderecoImagem);
$('#produto1-imagem2').attr("title", data.lista[1].Descricao);
$('#produto1-imagem2').attr("alt", data.lista[1].DescricaoAlternativa);
$('#produto1-imagem2').attr("width", data.lista[1].Largura);
$('#produto1-imagem2').attr("height", data.lista[1].Altura);
item++;
$('#produto1-item3').html(item + " / " + data.qtd);
$('#produto1-legenda3').html(data.lista[2].Descricao);
$('#produto1-imagem3').attr("src", data.lista[2].EnderecoImagem);
$('#produto1-imagem3').attr("title", data.lista[2].Descricao);
$('#produto1-imagem3').attr("alt", data.lista[2].DescricaoAlternativa);
$('#produto1-imagem3').attr("width", data.lista[2].Largura);
$('#produto1-imagem3').attr("height", data.lista[2].Altura);
$('#produto1-imagem1').parent().show();
$('#produto1-imagem2').parent().show();
$('#produto1-imagem3').parent().show();
$('#fourth-slide').attr('produto1-ini', data.lista[0].IdImagem);
$('#fourth-slide').attr('produto1-fim', data.lista[2].IdImagem);
$('#fourth-slide').attr('produto1-seq', item);
$('#fourth-slide').attr('produto1-qtpagina', 3);
}
else if (i == 1) {
item++;
$('#produto1-item1').html(item + " / " + data.qtd);
$('#produto1-legenda1').html(data.lista[0].Descricao);
$('#produto1-nome1').text(data.lista[0].NomeclienteProduto);
$('#produto1-imagem1').attr("src", data.lista[0].EnderecoImagem);
$('#produto1-imagem1').attr("title", data.lista[0].Descricao);
$('#produto1-imagem1').attr("alt", data.lista[0].DescricaoAlternativa);
$('#produto1-imagem1').attr("width", data.lista[0].Largura);
$('#produto1-imagem1').attr("height", data.lista[0].Altura);
item++;
$('#produto1-item2').html(item + " / " + data.qtd);
$('#produto1-nome2').text(data.lista[1].NomeclienteProduto);
$('#produto1-imagem2').attr("src", data.lista[1].EnderecoImagem);
$('#produto1-imagem2').attr("title", data.lista[1].Descricao);
$('#produto1-imagem2').attr("alt", data.lista[1].DescricaoAlternativa);
$('#produto1-imagem2').attr("width", data.lista[1].Largura);
$('#produto1-imagem2').attr("height", data.lista[1].Altura);
$('#produto1-legenda2').html(data.lista[1].Descricao);
$('#produto1-imagem1').parent().show();
$('#produto1-imagem2').parent().show();
$('#produto1-imagem3').parent().hide();
$('#fourth-slide').attr('produto1-ini', data.lista[0].IdImagem);
$('#fourth-slide').attr('produto1-fim', data.lista[1].IdImagem);
$('#fourth-slide').attr('produto1-seq', item);
$('#fourth-slide').attr('produto1-qtpagina', 2);
}
else {
item++;
$('#produto1-item1').html(item + " / " + data.qtd);
$('#produto1-legenda1').html(data.lista[0].Descricao);
$('#produto1-nome1').text(data.lista[0].NomeclienteProduto);
$('#produto1-imagem1').attr("src", data.lista[0].EnderecoImagem);
$('#produto1-imagem1').attr("title", data.lista[0].Descricao);
$('#produto1-imagem1').attr("alt", data.lista[0].DescricaoAlternativa);
$('#produto1-imagem1').attr("width", data.lista[0].Largura);
$('#produto1-imagem1').attr("height", data.lista[0].Altura);
$('#produto1-imagem1').parent().show();
$('#produto1-imagem2').parent().hide();
$('#produto1-imagem3').parent().hide();
$('#fourth-slide').attr('produto1-ini', data.lista[0].IdImagem);
$('#fourth-slide').attr('produto1-fim', data.lista[0].IdImagem);
$('#fourth-slide').attr('produto1-seq', item);
$('#fourth-slide').attr('produto1-qtpagina', 1);
}
}
});
};
if (document.getElementById("fourth-slide").getAttribute("produto1-ini") == 0) {
frente = "S";
idEnvio = 0;
urlDestino = "/Produto/BuscaImagemFrente";
nrReg = 3;
idProduto = $('#IdProduto').val();
slide1();
}
$('#frente-produto1-slide').on('click', function () {
frente = "S";
var idFim = document.getElementById("fourth-slide").getAttribute("produto1-fim");
idEnvio = idFim;
urlDestino = "/Produto/BuscaImagemFrente";
nrReg = 3;
idProduto = $('#IdProduto').val();
slide1();
});
$('#tras-produto1-slide').on('click', function () {
frente = "N";
var idIni = document.getElementById("fourth-slide").getAttribute("produto1-ini");
idEnvio = idIni;
urlDestino = "/Produto/BuscaImagemTras";
nrReg = 3;
idProduto = $('#IdProduto').val();
slide1();
});
$('#fourth-slide').carousel({
interval: false
});
// slide 4 - imagens - galeria de imagens
var urlDestino = "";
var idProduto = 0;
function slide4() {
$.ajax({
url: urlDestino,
type: "POST",
data: { "idProduto": idProduto },
async: true,
dataType: "json",
success: function (data) {
if (data == "") {
return;
}
var i = data.length;
if (i > 0) {
i = i - 1;
}
var y = 0;
for (x = 0; x < data.length; x++) {
if (data[x].IdPostagemImagem == 3) {
y++;
if (y == 1) {
$('#slide5-legenda1').html(data[x].Descricao);
$('#slide5-imagem1').attr("src", data[x].EnderecoImagem);
$('#slide5-imagem1').attr("title", data[x].Descricao);
$('#slide5-imagem1').attr("alt", data[x].DescricaoAlternativa);
}
else {
$('#fith-slide .carousel-inner').append('<div class="item">' +
'<img alt="' + data[x].DescricaoAlternativa + '" title="' +
data[x].Descricao + '" src="' + data[x].EnderecoImagem + '" class="img-responsive center-block">' +
'<div class="carousel-caption"><div class="fith-slide-legenda">' +
data[x].Descricao + '</div></div></div>');
}
}
}
}
});
};
urlDestino = "/Produto/BuscaTodasImagens";
idProduto = $('#IdProduto').val();
slide4();
$('#fith-slide').carousel({
interval: false
});
});
4) Controller (with two calls from jquery):
[HttpPost]
public async Task<JsonResult> BuscaImagemFrente(int? id, int idProduto, int nrRegistro)
{
int qtdTot = await (from d in db.Imagem
join p in db.Produto on d.IdProduto equals p.IdProduto
where p.IdProduto == idProduto
&& d.IdPostagemImagem == 3
select d.IdProduto).CountAsync();
int dep = 0;
if (id == 0)
{
dep = int.Parse((from d in db.Imagem
join p in db.Produto on d.IdProduto equals p.IdProduto
where p.IdProduto == idProduto
&& d.IdPostagemImagem == 3
orderby d.IdImagem
select d.IdImagem).FirstOrDefault().ToString());
id = dep - 1;
}
if (id >= 0)
{
var frente = await (from d in db.Imagem
join p in db.Produto on d.IdProduto equals p.IdProduto
where d.IdImagem > id && p.IdProduto == idProduto
&& d.IdPostagemImagem == 3
orderby d.IdImagem
select new
{
d.IdImagem,
d.IdProduto,
d.EnderecoImagem,
d.CorFundoLegenda,
d.Descricao,
d.IdEmpresa,
d.Largura,
d.Altura,
d.IdPostagemImagem,
d.DescricaoAlternativa,
d.DescricaoLegenda,
d.PosicaoHorizontalLegenda,
d.Detalhamento
})
.Take(nrRegistro).ToListAsync();
return Json( new { lista = frente, qtd = qtdTot });
}
else
{
return Json(0);
}
}
[HttpPost]
public async Task<JsonResult> BuscaImagemTras(int? id, int idProduto, int nrRegistro)
{
int qtdTot = await (from d in db.Imagem
join p in db.Produto on d.IdProduto equals p.IdProduto
where p.IdProduto == idProduto
&& d.IdPostagemImagem == 3
select d.IdProduto).CountAsync();
if (id > 0)
{
var frente = await (from d in db.Imagem
join p in db.Produto on d.IdProduto equals p.IdProduto
where d.IdImagem < id && p.IdProduto == idProduto
&& d.IdPostagemImagem == 3
orderby d.IdImagem descending
select new
{
d.IdImagem,
d.IdProduto,
d.EnderecoImagem,
d.CorFundoLegenda,
d.Descricao,
d.IdEmpresa,
d.Largura,
d.Altura,
d.IdPostagemImagem,
d.DescricaoAlternativa,
d.DescricaoLegenda,
d.PosicaoHorizontalLegenda,
d.Detalhamento
})
.Take(nrRegistro).OrderBy(x => x.IdImagem).ToListAsync();
return Json(new { lista = frente, qtd = qtdTot });
}
else
{
return Json(0);
}
}
public async Task<JsonResult> BuscaTodasImagens(int idProduto)
{
var retorno = await (from d in db.Imagem
join p in db.Produto on d.IdProduto equals p.IdProduto
where p.IdProduto == idProduto
&& (d.IdPostagemImagem == 3 || d.IdPostagemImagem == 9)
orderby d.IdPostagemImagem, d.IdImagem
select new
{
d.IdPostagemImagem,
d.EnderecoImagem,
d.Descricao,
d.DescricaoAlternativa,
d.DescricaoLegenda
})
.ToListAsync();
return Json(retorno);
}
[HttpPost]
public async Task<JsonResult> BuscaDadosPlanta(int idProduto)
{
var frente = await (from d in db.Imagem
join p in db.Produto on d.IdProduto equals p.IdProduto
join e in db.EspecificacaoProduto on p.IdProduto equals e.IdProduto
where p.IdProduto == idProduto && d.IdPostagemImagem == 9 &&
e.IdEspecificacaoProduto == d.IdEspecificacaoProduto
//orderby d.IdEspecificacaoProduto
orderby d.IdPostagemImagem, d.IdImagem
select new
{
e.IdEspecificacaoProduto,
e.DescricaoEspecificacaoProduto,
e.DetalhamentoEspecificacaoProduto,
d.IdImagem,
d.IdProduto,
d.EnderecoImagem,
d.CorFundoLegenda,
d.Descricao,
d.IdEmpresa,
d.Largura,
d.Altura,
d.IdPostagemImagem,
d.DescricaoAlternativa,
d.DescricaoLegenda,
d.PosicaoHorizontalLegenda,
d.Detalhamento
}).ToListAsync();
return Json(frente);
}
Trying to Add and Remove class to click dynamic Buttons, means this button <button class="one"></button> get class dynamically like this: <button class="one text1">text1</button>
So if button one has class .text1 and by click this add class .hide to list item <li class="text1"> like <li class="text1 show">
Same for button two <button class="two"></button> and by click add class <li class="text2 show">
Note: when click button two, then should remove class .show and add new class .hideto button one.
Main HTML:
<div id="main-id">
<button class="one"></button>
<button class="two"></button>
<ul>
<li>
<!--List 1-->
<div class="label">
text1
</div>
</li>
<li>
<!--List 2 is Same-->
<div class="label">
text1
</div>
</li>
<li>
<!--List 3 is different-->
<div class="label">
text2
</div>
</li>
</ul>
</div>
Script:
$('.label a').each(function() {
var $this=$(this);
$this.closest('li').addClass($this.text());
});
// Combine This
$('button').each(function(){
var liInd = 0;
var cl = '';
var txt = '';
var clses = [];
var ind = $('button').index($(this)) + 1;
$('li').each(function(){
if(clses.indexOf($(this).attr('class')) === -1){
clses.push($(this).attr('class'));
liInd = liInd + 1;
}
if(ind === liInd){
cl = $(this).attr('class');
txt = $(this).find('a').text();
return false; //break
}
});
$('button:nth-child(' + ind + ')').addClass(cl);
$('button:nth-child(' + ind + ')').text(txt);
});
See Example on Fiddle
I have tried this by add/remove class by click function, but problem is Buttons get class dynamically from List items, so I'm not able to target button.
Any suggestion for other way to do this by JS/ Jquery?
Here is an alternative solution
$('button').each(function () {
var liInd = 0;
var cl = '';
var txt = '';
var clses = [];
var ind = $('button').index($(this)) + 1;
$('li').each(function () {
if (clses.indexOf($(this).attr('class')) === -1) {
clses.push($(this).attr('class'));
liInd = liInd + 1;
}
if (ind === liInd) {
cl = $(this).attr('class');
txt = $(this).find('a').text();
return false; //break
}
});
if (txt != '') {
$('button:nth-child(' + ind + ')').addClass(cl);
$('button:nth-child(' + ind + ')').text(txt);
}
});
$('button').click(function () {
if ($(this).attr('class')[0] == 'all') {
showAll();
return false; // end this function
}
var allCls = $(this).attr('class').split(' ');
$('li').each(function () {
if (allCls.indexOf($(this).find('a').text()) > -1) {
$(this).closest('li').removeClass('show').addClass('hide');
} else {
$(this).closest('li').removeClass('hide').addClass('show');
}
});
});
function showAll() {
$('li').removeClass('hide').addClass('show');
}
Fiddle: https://jsfiddle.net/taleebanwar/yaLm4euk/13/
DEMO
$('.label a').each(function () {
var $this = $(this);
$this.closest('li').addClass($this.text());
});
// Combine This
$('button').each(function () {
var liInd = 0;
var cl = '';
var txt = '';
var clses = [];
var ind = $('button').index($(this)) + 1;
$('li').each(function () {
if (clses.indexOf($(this).attr('class')) === -1) {
clses.push($(this).attr('class'));
liInd = liInd + 1;
}
if (ind === liInd) {
cl = $(this).attr('class');
txt = $(this).find('a').text();
return false; //break
}
});
$('button:nth-child(' + ind + ')').addClass(cl);
$('button:nth-child(' + ind + ')').text(txt);
});
$(document).on('click', 'button',function(e){
var textClass = $.grep(this.className.split(" "), function(v, i){
return v.indexOf('text') === 0;
}).join();
console.log(textClass);
$('li').removeClass('show').addClass('hide')
$('li').each(function(){
if($(this).hasClass($.trim(textClass))){
$(this).removeClass('hide').addClass('show');
} else {
$(this).removeClass('show').addClass('hide');
}
})
})
.show{display:list-item;}
.hide{display:none;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="main-id">
<button class="one"></button>
<button class="two"></button>
<ul>
<li>
<!--List 1-->
<div class="label">
text1
</div>
</li>
<li>
<!--List 2 is Same-->
<div class="label">
text1
</div>
</li>
<li>
<!--List 3 is different-->
<div class="label">
text2
</div>
</li>
</ul>
</div>