Create sliding Next / Previous content VIA Ajax / JSON - javascript

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

Related

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

Angular 4 shopping cart functionality onclick to render text

i am new to angular 4 i want to develop a shopping cart functionality with some different render functionality in html. i can't able to find any solution till now.
already tried with jquery append function but it wont work in edit functionality in feature.
Below gif image shows my requirement
if i click any catagory it will directly append to top of the list with selected catagory.
Then if i click another catagory for same person it will apply after i click apply button
component.html
<ul class="selected-friends" id="appendtext">
</ul>
<ul class="list-friends" id="listFriends">
<div *ngFor="let data of result" [attr.id]="'FriendList' + data.id" #item>
<li class="checkedCatagory">
<div class="sf-left">
<h3>{{data.fullName}}</h3>
<span id="appendCatagoryList"></span>
</div>
<div class="sf-right">
<div class="edit-con sf-icon" data-toggle="collapse" [attr.data-target]="'#list' + data.id">
<i class="fa fa-list" aria-hidden="true"></i>
</div>
<div class="del-con sf-icon" [attr.id]="'#list' + data.id" (click)="delete(data.id)">
<i class="fa fa-trash-o" aria-hidden="true"></i>
</div>
</div>
</li>
<!-- Main List started -->
<li class="mainlistname" data-toggle="collapse" [attr.data-target]="'#list' + data.id">
<label class="catagory_list" [attr.for]="data.id"><input type="checkbox" [attr.id]="data.id" [attr.value]="data.id">
{{data.fullName}}</label>
</li>
<ul class="sub-friends-list collapse" [attr.id]="'list'+data.id">
<p class="mainlistname">Assign Category to this participant</p>
<p class="checkedCatagory">Edit or Assign another category to this participant</p>
<li *ngFor="let catagoryDetail of catagoryList">
<label class="catagory_list">
<input type="checkbox" class="catagory_list_checkbox" (click)="resize(data.id, catagoryDetail.id);addToCart(data.id,catagoryDetail.id,data.fullName,catagoryDetail.title)" [value]="catagoryDetail.id" [attr.id]="'catagoryId'+catagoryDetail.id">
<span [attr.id]="'catagoryName'+catagoryDetail.id">{{catagoryDetail.title}}</span>
<span class="pull-right fnt-16">AED</span>
<span class="pull-right fnt-16" id="'fee'+catagoryDetail.id">{{catagoryDetail.fee}}</span>
<!-- <p>18-99 Years Male/Female</p> -->
<p *ngIf="catagoryDetail.gender === 1">{{catagoryDetail.ageMinMale}}-{{catagoryDetail.ageMaxMale}} Years Male</p>
<p *ngIf="catagoryDetail.gender === 2">{{catagoryDetail.ageMinFemale}}-{{catagoryDetail.ageMaxFemale}} Years Female</p>
<p *ngIf="catagoryDetail.gender === 3">{{catagoryDetail.ageMinFemale}}-{{catagoryDetail.ageMaxFemale}} Years Male/Female</p>
</label>
<span class="checkedCatagoryhidden">
<p *ngFor="let catagorySelected of catagoryList" [attr.id]="'catagorySelected'+catagorySelected.id">
{{catagorySelected.title}} :
<span *ngIf="catagorySelected.gender === 1">{{catagorySelected.ageMinMale}}-{{catagorySelected.ageMaxMale}} Years Male</span>
<span *ngIf="catagorySelected.gender === 2">{{catagorySelected.ageMinFemale}}-{{catagorySelected.ageMaxFemale}} Years Female</span>
<span *ngIf="catagorySelected.gender === 3">{{catagorySelected.ageMinFemale}}-{{catagorySelected.ageMaxFemale}} Years Male/Female</span>
<span class="pull-right fnt-16">AED {{catagorySelected.fee}}</span>
</p>
</span>
</li>
<li class="checkedCatagory" class="apply checkedCatagory quantity">
<span class="quantity_catagory">Qty: <span [attr.id]="'sectionquantity'+data.id"></span></span>
<span class="catagory_amount">Total: AED <span [attr.id]="'sectionprize'+data.id"></span></span>
<button class="btnapplyqnty">Apply</button>
</li>
</ul>
</div>
</ul>
component.ts
addToCart(id, catagoryId, fullName, catTitle){
var currentUserObj = <any>{};
var self = this;
var sum;
currentUserObj[id] = {};
currentUserObj[id].participantid = id;
currentUserObj[id].participantName = fullName;
// console.log(fullName)
this.cart.cartItems[id] = {};
if(jQuery("#catagoryId"+catagoryId).is(":checked")) {
currentUserObj[id]['categoryInfo'] = [];
currentUserObj[id]['categoryName'] = [];
currentUserObj[id]['categoryFee'] = [];
var totalPrize = 0;
jQuery('#list'+id).find('.catagory_list input:checked').each(function(){
var currentCategoryId = jQuery(this).val();
var currentCatagoryName = jQuery('.catagory_list input:checked+#catagoryName'+catagoryId).text();
currentUserObj[id]['categoryInfo'].push(currentCategoryId);
currentUserObj[id]['categoryName'].push(jQuery(this).next('').text());
currentUserObj[id]['categoryFee'].push(Number(jQuery(this).next().next().next().text()));
});
sum = currentUserObj[id]['categoryFee'].reduce(this.add, 0);
currentUserObj[id].quantity = currentUserObj[id]['categoryInfo'].length;
this.cart.cartItems[id] = currentUserObj[id];
currentUserObj[id].participantTotalPrize = sum;
console.log('sum',sum)
this.saveCart();
} else {
var currentCategoryId;
currentUserObj[id]['categoryInfo'] = [];
currentUserObj[id]['categoryName'] = [];
currentUserObj[id]['categoryFee'] = [];
jQuery('#list'+id).find('.catagory_list input:checked').each(function(){
currentCategoryId = jQuery(this).val();
currentUserObj[id]['categoryName'].push(jQuery(this).next().text());
currentUserObj[id]['categoryInfo'].push(currentCategoryId);
currentUserObj[id]['categoryFee'].push(Number(jQuery(this).next().next().next().text()));
});
sum = currentUserObj[id]['categoryFee'].reduce(this.add, 0);
currentUserObj[id].participantTotalPrize = sum;
currentUserObj[id].quantity = currentUserObj[id]['categoryInfo'].length;
this.cart.cartItems[id] = currentUserObj[id];
if(currentUserObj[id].quantity === 0) {
console.log("completed delete", this.cart.cartItems[id])
delete self.cart.cartItems[id];
}
this.saveCart();
}
}
add(a, b) {
return a + b;
}
saveCart() {
if (window.localStorage) {
console.log("tfgb",this.cart);
sessionStorage.setItem('cart',JSON.stringify(this.cart));
}
}
resize(id, catagoryId) {
let navObj = this;
var appendSelectedCatagory = document.getElementById('appendtext');
jQuery(appendSelectedCatagory).prepend(jQuery('#FriendList'+id));
if(jQuery("#catagoryId"+catagoryId).is(":checked")) {
this.displaySelectedList(id, catagoryId);
var totalPrize = 0;
navObj.quantity = 0;
jQuery('#list'+id).find('.catagory_list input:checked').each(function(){
var currentCategoryId = jQuery(this).val();
navObj.eventRegistrationService.getEventCatagoriesList(navObj.eventId)
.subscribe((res)=>{
for(let i in res.data){
var catList = res.data[i];
if(catList.id == currentCategoryId){
totalPrize += catList.fee
navObj.quantity += 1;
}
}
jQuery('#sectionprize'+id).html(totalPrize);
jQuery('#sectionquantity'+id).html(navObj.quantity);
})
})
} else {
this.eventChecked -= 1;
var totalPrize = 0;
navObj.quantity = 0;
jQuery('#list'+id).find('.catagory_list input:checked').each(function(){
var currentCategoryId = jQuery(this).val();
navObj.eventRegistrationService.getEventCatagoriesList(navObj.eventId)
.subscribe((res)=>{
for(let i in res.data){
var catList = res.data[i];
if(catList.id == currentCategoryId){
totalPrize += catList.fee
navObj.quantity += 1;
}
}
jQuery('#sectionprize'+id).html(totalPrize)
jQuery('#sectionquantity'+id).html(navObj.quantity)
})
})
this.checkedCatagory.pop(catagoryId);
let checkBoxList = '#appendtext #list'+id;
if(jQuery(checkBoxList+' :checkbox:checked').length == 0){
jQuery('#listFriends').append(jQuery('#FriendList'+id));
jQuery("#FriendList"+id+ " input[type='checkbox']").prop("checked", false);
sessionStorage.removeItem(id);
}
}
}
displaySelectedList(id, catagoryId){
this.eventChecked += 1;
let getselectList = sessionStorage.getItem('selectedFriends');
jQuery('#appendCatagoryList').append(jQuery('#catagorySelected'+catagoryId))
}
delete(id){
jQuery('#listFriends').append(jQuery('#FriendList'+id));
jQuery("#FriendList"+id+ " input[type='checkbox']").prop("checked", false);
console.log('asdasdsa',id);
//this.quantity = 0;
sessionStorage.removeItem(id);
}

Model Window Shows Same Content

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

How to find span with biggest data-item using jQuery

I have a div with spans inside. They have data-item attr. How to find div with the biggest data-item attr. They are numbers starting from 0. For example I have:
<div class="wrapper">
<span data-num="0">text</span>
<span data-num="1">text</span>
<span data-num="2">text</span>
<span data-num="3">text</span>
</div>
Updated: This is part of my code, it's about uploading files and one of the input fields is multiple. And I show in a div with separate spans image names of the files. Use should add multiple files so I need to find the biggest data-num and increment it for the next file.
function getFiles(document, window, index) {
var inputs = document.querySelectorAll( '.app-file' );
input.addEventListener( 'change', function( e )
{
var fileName = '';
var num = 0;
if( this.files && this.files.length > 1 || $(this).next().next().html()) {
var fileName = [];
for (var i = 0; i < this.files.length; ++i) {
fileName.push(this.files.item(i).name);
var comma = '';
if($(this).next().next().html()) {
comma = ',';
}
divName.innerHTML = divName.innerHTML + comma + '<span class="image_name" data-num="'+num+'">' + this.files.item(i).name + '</span><span class="glyphicon glyphicon-remove remove-file" data-toggle="tooltip" data-placement="top" title="Remove"></span>';
num++;
}
} else {
fileName = e.target.value.split('\\').pop();
divName.innerHTML = '<span class="image_wrapper"><span class="image_name" data-num="'+num+'">' +fileName + '</span><span class="glyphicon glyphicon-remove remove-file" data-toggle="tooltip" data-placement="top" title="Remove"></span></span>';
var maxIndexItem = $.makeArray($('#wrapper [data-num]')).reduce(function(result, item) {
return $(item).data('num') > $(result).data('num') ? $(item) : result;
});
alert(maxIndexItem.text());
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="file-name" data-input="corporate_document" id="corporates"></div>
HTML
<div class="wrapper">
<span data-num="0">text1</span>
<span data-num="1">text2</span>
<span data-num="2">text3</span>
<span data-num="3">text4</span>
<span>text5</span>
<span data-num="">text6</span>
</div>
JS
$(document).ready(function(){
var arr = [];
$(".wrapper span").each(function(){
var dataNum = $(this).data("num");
if (dataNum != null) {
arr.push(dataNum);
}
}).promise().done( function(){
var max = Math.max.apply(Math, arr);
alert( $(".wrapper").find("[data-num=" + max + "]").text());
} );
});
Refer Fiddle
I think this code can helps you:
var maxIndexItem = $.makeArray($('.wrapper [data-num]')).reduce(function(result, item) {
return $(item).data('num') > $(result).data('num') ? $(item) : result;
});
alert(maxIndexItem.text());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="wrapper">
<span data-num="0">text 0</span>
<span data-num="1">text 1</span>
<span data-num="2">text 2</span>
<span data-num="3">text 3</span>
</div>

Can update page with ajax

I have a div element which is populated by the query result(in index.php). I have also another file widget.php which has same query to update page. I have variable in widget.php "page" which navigates through the pages. If I use widget.php?page=2 it will load next page with results. I want to update a div element in index.php on click.(Click "next" and show another 8 news without reloading page).
in index.php :
<button type="button" id="prevbutton">Previous</button>
<button type="button" id="nextbutton">Next</button>
<div id="list"></div>
in script.js:
$("#prevbutton, #nextbutton").click(function () {
var id_name = $(this).attr('id');
var page = 0;
if (id_name == '#prevbutton' || id_name == '#nextbutton') {
if (id_name == '#prevbutton') {
page -= 1;
}
if (id_name == '#nextbutton') {
page +=1;
}
}
$.ajax({
url: 'widget.php',
type: 'GET',
data: "page=" + page,
success: function (data) {
//called when successful
$("#list").html(data);
},
error: function (e) {
//called when there is an error
//console.log(e.message);
}
});
});
in widget.php :
<?php
header("Cache-Control: public, max-age=60");
include("logindb.php");
$page = $_GET['page'];
$page = $page*9;
?>
<div id="list">
<?php
$abfrage59 = "SELECT n.news_title,n.news_id,FLOOR(TIMESTAMPDIFF(HOUR, n.timestamp, NOW())) as diff
FROM news n
WHERE n.domain_id = '2' AND n.timestamp < NOW()
ORDER BY timestamp DESC
LIMIT $page,9";
$ergebnis59 = mysql_query($abfrage59);
while ($row59 = mysql_fetch_object($ergebnis59)) {
$newstitleslug = $row59->news_title;
$newstitleslug = str_replace(' ', '-', $newstitleslug);
$newstitleslug = strtolower($newstitleslug);
echo "<div class=\"col-sm-6 col-md-4\" style=\"padding-bottom: 15px;\">
<div class=\"item\">
<img class=\"main\" src=\"http://www.example.com/news/$row59->news_id.png\" />
<div class=\"text\">
<div class=\"inner\">
<a href=\"http://www.example.com/$newstitleslug/$row59->news_id/\" style=\"color:white;\">$row59->news_title<br />
<span class=\"date\">$row59->diff hours ago</span>
</div>
</div>
</div>
</div>";
}
?>
<?php
include("close_connect.php");
?>
So I want to update value $page on click and refresh content of DIV with new data. Thanks in advance.
Edit: removed script from script.js and put in the end of the index.php body:
<script>
$("#prevbutton, #nextbutton").click(function () {
var id_name = $(this).attr('id');
var temppage = 1;
if (id_name == 'prevbutton' || id_name == 'nextbutton') {
if (id_name == 'prevbutton') {
temppage -= 1;
}
if (id_name == 'nextbutton') {
temppage +=1;
}
var page = temppage;
}
$.ajax({
url: 'widgets/news_archive_widget.php',
type: 'GET',
data: "page=" + page,
success: function (data) {
//called when successful
$("#list").html(data);
},
error: function (e) {
//called when there is an error
//console.log(e.message);
}
});
});
</script>
Remove the # you're prefixing to prevButton and nextButton as $(this).attr('id') will return the id without the #. The value of id_name will either be prevButton or nextButton.
UPDATE:
Your final js script should look like this:
$("#prevbutton, #nextbutton").click(function () {
var id_name = $(this).attr('id');
var page = $("#currPageNumber").val();
if (id_name == 'prevbutton' || id_name == 'nextbutton') {
if (id_name == 'prevbutton') {
page -= 1;
}
if (id_name == 'nextbutton') {
page +=1;
}
}
$.ajax({
url: 'widget.php',
type: 'GET',
data: "page=" + page,
success: function (data) {
//called when successful
$("#list").html(data);
},
error: function (e) {
//called when there is an error
//console.log(e.message);
}
});
});
PHP script:
<?php
header("Cache-Control: public, max-age=60");
include("logindb.php");
$page = $_GET['page'];
$page = $page*9;
?>
<div id="list">
<?php
$abfrage59 = "SELECT n.news_title,n.news_id,FLOOR(TIMESTAMPDIFF(HOUR, n.timestamp, NOW())) as diff
FROM news n
WHERE n.domain_id = '2' AND n.timestamp < NOW()
ORDER BY timestamp DESC
LIMIT $page,9";
$ergebnis59 = mysql_query($abfrage59);
while ($row59 = mysql_fetch_object($ergebnis59)) {
$newstitleslug = $row59->news_title;
$newstitleslug = str_replace(' ', '-', $newstitleslug);
$newstitleslug = strtolower($newstitleslug);
echo "<div class=\"col-sm-6 col-md-4\" style=\"padding-bottom: 15px;\">
<div class=\"item\">
<img class=\"main\" src=\"http://www.example.com/news/$row59->news_id.png\" />
<div class=\"text\">
<div class=\"inner\">
<a href=\"http://www.example.com/$newstitleslug/$row59->news_id/\" style=\"color:white;\">$row59->news_title<br />
<span class=\"date\">$row59->diff hours ago</span>
</div>
</div>
<input type='hidden' value='".$_GET['page']."' id='currPageNumber'>
</div>
</div>";
}
?>
<?php
include("close_connect.php");
?>

Categories

Resources