Model Window Shows Same Content - javascript

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);
}

Related

Advanced product filtering based on user's values

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?

Assigning a class to an element once it's appended

So I currently have slider that the user can dynamically fill upon uploading images. I'm using bootstrap for the slider which requires the first slide to have the class "active" in order to work, however when I try to assign that class to the first slide using
"if ($("#carousel-inner").find('li')) {
var slide1 = document.getElementById("slide-0");
slide1.setAttribute ("class", "active");
}
it doesn't recognize the slide id and assigns null to the value, returning "cannot setAttribute of null".
Any advice?
HTML
<div id="slideshow-container">
<div id="carouselExampleControls" class="carousel slide" data-ride="carousel">
<ul class="carousel-inner" id ="carousel-inner">
</ul>
<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>
</div>
JS
window.onload = function() {
$('#_uploadImages').click(function () {
$('#_imagesInput').click();
setTimeout(activeness(), 5000)
});
$('#_imagesInput').on('change', function () {
handleFileSelect();
});
}
function handleFileSelect() {
//Check File API support
if (window.File && window.FileList && window.FileReader) {
var files = event.target.files; //FileList object
var output = document.getElementById("carousel-inner");
var arrFilesCount = [];
var start = $(output).find('li').length;
var end = start+ files.length;
var nonImgCount = 0;
var slide1 = document.getElementById("slide1")
var display = document.getElementById("displayImg")
for (var i = start; i < end; i++) {
arrFilesCount.push(i); // push to array
}
if(start !== 0){
$(output).find('li > nav > a.prev').first().attr('href','#slide-' + (end-1));
$(output).find('li > nav > a.next').last().attr('href','#slide-'+start);
}
for (var i = 0; i < files.length; i++) {
var file = files[i];
//Only pics
if (!file.type.match('image')) {nonImgCount++; continue;}
var picReader = new FileReader();
picReader.addEventListener("load", function (event) {
var picFile = event.target;
current_i = arrFilesCount.shift();
if (current_i === 0) {
prev_i = files.length - 1; //This is for the first element. The previous slide will be the last image. (i=length-1)
} else {
prev_i = current_i - 1;
}
if (arrFilesCount.length - nonImgCount === 0) {
next_i = 0;
} else {
next_i = current_i + 1; //This is for the last element. The next slide will be the first image (i=0)
}
display.src = picFile.result
output.innerHTML = output.innerHTML + '<li id="slide-' + current_i + '" class="carousel-item">' + "<img class='d-block w-100' src='" + picFile.result + "'" + "title=''/>" + '</li>'; // TODO: Enter Title
});
//Read the image
picReader.readAsDataURL(file);
}
if ($("#carousel-inner").find('li')) {
var slide1 = document.getElementById("slide-0");
slide1.setAttribute ("class", "active");
}
} else {
console.log("Your browser does not support File API");
}
}

PhotoSwipe Navigation Does Not Respond to Input

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>

Add and Remove class to click a dynamic Button

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>

Create sliding Next / Previous content VIA Ajax / JSON

This is quite an in depth question so I will try my best to explain in as much detail as possible.
I am creating a Wordpress game information website, there are rows of gamelistings which when clicked create a content box, the data within this element is loaded with Ajax from a pages JSON array.
In my current set up when an element is clicked the contentbox data is simply updated, and the previous and next arrows simulate a click on the prev / next element to the currently active one.
The JSON data that is loaded includes 2 useful fields:
(data.previous_url)
(data.next)
I would like to use this data to create separate ajax functions that create previous and next content boxes to the active one. I would then like the prev / next arrows to slide to the appropriate content box.
THE MARKUP / WORDPRESS LOOP
<?php
$counter = 0;
if ( have_posts() ) :
while ( have_posts() ) : the_post(); $counter++;
$gameName = get_field('game_name');
$gameLogo = str_replace(" ", "", $gameName);
$gameLink = str_replace(" ", "-", $gameName);
$gameReels = get_field('reels');
$gamePaylines = get_field('paylines');
$gameInfo = get_field('game_info');
?>
<div class="four columns gameListing" id="<?php echo $gameName ?>" data-count="<?php echo $counter; ?>" data-id="<?php echo $gameLink ?>">
<img class="gameLogo" src="<?php bloginfo('template_directory'); ?>/images/games/logos/<?php echo $gameLogo ?>.png" >
<div class="gameInfo">
<h2 class="gameTitle"> <?php if($gameName): echo $gameName; endif; ?></h2>
<div class="gameRating">
<i class="fa plusone fa-star"></i><i class="fa plusone fa-star"></i><i class="fa plusone fa-star"></i><i class="fa plusone fa-star"></i><i class="fa fa-star"></i> (5.0)
</div>
</div>
<a class="gameCta" rel="" data-post-id="<?echo $post->ID ?>" ><span class="title">Click to Play</span></a>
</div>
<?php endwhile; endif; ?>
<div class="clear"></div>
<div class="sixteen columns gameBox" id="gameBox" data-id="">
<div id="gameBoxNav">
<a class="prev controls"><i class="fa fa-chevron-left"></i></a>
<a class="next controls"><i class="fa fa-chevron-right"></i></a>
</div>
<div class="gameBoxContent">
<div class="gameBox-L">
<h3 class="gameBox-Header-Left heading"><span class='game-name'></span></h3>
<div class="gameBox-Screenshots">
<div class="gameBox-L-Side" id='gameBoxGallery'></div>
<div class="gameBox-L-Main" id="gameBox-Screenshot"></div>
<div class="clear"></div>
</div>
</div>
<div class="gameBox-R">
<h3 class="gameBox-Header-Right heading">Play on any of these sites:</h3>
<div id="close" class="controls">X</div>
<div class="clear"></div>
<div id="game_provs"></div>
</div>
<div class="clear"></div>
<div class="gameBox-Details">
<h3 class="gameBox-Header heading">All about <span class='game-name'></span></h3>
<ul class="gameDetailsBar">
<li class="gameDetails">
<span class="gameInfo-cellData" id="game-reels"></span>
<span class="gameInfo-cellTitle">Reels</span>
</li>
<li class="gameDetails">
<span class="gameInfo-cellData" id="game-paylines"></span>
<span class="gameInfo-cellTitle">Paylines</span>
</li>
<li class="gameDetails">
<span class="gameInfo-cellData" id="game-minBet"></span>
<span class="gameInfo-cellTitle">Min Bet</span>
</li>
<li class="gameDetails">
<span class="gameInfo-cellData" id="game-maxBet"></span>
<span class="gameInfo-cellTitle">Max Bet</span>
</li>
<li class="gameDetails">
<span class="gameInfo-cellData" id="game-jackpot"></span>
<span class="gameInfo-cellTitle">Jackpot</span>
</li>
<li class="gameDev">
<span gameDev-cellTitle>Developed By:</span>
<span gameDev-cellData><img src="<?php bloginfo('template_directory'); ?>/images/devlogos/netent.png" alt=""></span>
</li>
</ul>
<div class="clear"></div>
<div class="gameInfo-Excerpt" id="game-info"></div>
</div>
</div>
</div>
The JS
// -------------- MAIN CLICK FUNCTION --------------
$('.gameListing').click(function () {
$('.gameListing').removeClass('active');
$(this).addClass('active');
var id = $(this).attr('data-id');
var url = "http://localhost:8888/projects/superfreerespo/" + id + "?json=get_category_posts&slug=games";
// Pass the url and the clicked element
call_ajax(url, this);
});
// -------------- GET PREV / NEXT ITEMS --------------
$('.prev').click(function () {
var $current = $('.gameListing.active');
var postNumber = parseInt($current.attr('data-count'));
var nextPost = (postNumber - 1);
if (nextPost != 0) {
$current.removeClass('active')
$("[data-count='" + nextPost + "']").trigger("click");
}
});
$('.next').click(function () {
var $current = $('.gameListing.active');
var postNumber = parseInt($current.attr('data-count'));
var nextPost = (postNumber + 1);
var postCount = $('.gameListing').length;
if (nextPost != postCount + 1) {
$current.removeClass('active')
$("[data-count='" + nextPost + "']").trigger("click");
}
});
// -------------- AJAX CALL FUNCTION --------------
function call_ajax(url, elem) {
$.ajax({
url: url,
method: "GET",
data: {json: 1},
dataType: "JSON"
})
// -------------- FUNCTIONS FOR AFTER AJAX DONE --------------
.done(function (data) {
// Append the box
appendBox(elem);
// LOAD GAMEBOX JSON DATA
$("#game-name").html(data.post.title);
$("#game-reels").html(data.post.custom_fields.reels);
$("#game-paylines").html(data.post.custom_fields.paylines);
$("#game-minBet").html(data.post.custom_fields.min_bet);
$("#game-maxBet").html(data.post.custom_fields.max_bet);
$("#game-jackpot").html(data.post.custom_fields.jackpot);
$("#game-info").html(data.post.custom_fields.game_info);
// -------------------------- YOU CAN SEE HERE THE NEXT / PREV DATA LOADED VIA THE ABOVE AJAX CALL
var nextURL = (data.previous_url) + "?json=1";
var prevURL = (data.next_url) + "?json=1";
// -------------------------- LOAD GAME PROVIDERS VIA NEW AJAX LOAD
var provSource = new String(data.post.custom_fields.game_name);
provSource = provSource.replace(/ /g, "-");
$("#game_provs").load("http://localhost:8888/projects/superfreerespo/" + provSource + "/ .gameBox-Ops");
// -------------------------- LOAD GAME THUMBNALS
var gameThumbSrc = new String(data.post.custom_fields.game_name);
gameThumbSrc = gameThumbSrc.replace(/ /g, '');
$('#gameBoxGallery').html('');
for (i = 0; i <= 2; i++) {
image = '<img src="' + templateDir +'/images/games/screenshots/' + gameThumbSrc + '-' + i + '.jpg" class="gameThumb">'
$('#gameBoxGallery').append(image);
};
// -------------------------- ZOOM FIRST THUMBNAIL
$('#gameBox-Screenshot').html('');
image = '<img src="'+ templateDir +'/images/games/screenshots/' + gameThumbSrc + '-0' + '.jpg" id="gameScreenshot">'
$('#gameBox-Screenshot').append(image);
});
// -------------------------- CREATE GAMEBOX
function appendBox(elem) {
var $chosen = $(elem),
$gameBox = $('#gameBox'),
top = $chosen.offset().top,
$blocks = $chosen.nextAll('.gameListing');
// -------------------------- TOGGLE GAMEBOX OPEN
if($chosen.attr('data-id') === $gameBox.attr('data-id')) {
$gameBox.stop().slideUp(500, function () {
$(this).css('display', 'none');
});
$gameBox.attr('data-id', '');
}
// -------------------------- TOGGLE GAMEBOX CLOSE
else {
$gameBox.slideDown(500, function () {
$(this).css('display', 'inline-block');
});
$gameBox.attr('data-id', $chosen.attr('data-id'));
}
function placeAfter($block) {
$block.after($gameBox);
}
if ($blocks.length == 0) {
placeAfter($chosen);
return false;
}
$blocks.each(function (i, j) {
if ($(this).offset().top != top) {
placeAfter($(this).prev('.gameListing'));
return false;
} else if ((i + 1) == $blocks.length) {
placeAfter($(this));
return false;
}
});
}
$('html, body').animate({
scrollTop: $('.active').offset().top - 40
}, 600);
}
So after a little thought I decided a simpler option was available, rather than create multiple game boxes that slide I have just set the one gamebox to slide out of view back in again after the data has loaded.
$('.prev').click(function () {
var $current = $('.gameListing.active');
var postNumber = parseInt($current.attr('data-count'));
var nextPost = (postNumber - 1);
var postCount = $('.gameListing').length;
if (nextPost != 0) {
$("[data-count='" + nextPost + "']").trigger("click");
//THIS IS THE FIX
var settings = [
[{"left": "-950px"}, {duration: 450,complete: function() {$(this).css("left", window.innerWidth + $(this).width())}}],
[{"left": "0px"}, {duration: 450}]];
$(".gameBox").queue("_fx", $.map(settings, function(options, i) {
return function(next) {
return $(this).animate.apply($(this), options).promise().then(next)
}
})).dequeue("_fx");
}
else {
$("[data-count='" + postCount + "']").trigger("click");
}
});

Categories

Resources