Flexbox carousel transition issue - javascript

I'm trying to build a simple carousel with flexbox for a mobile website.
I found some examples I used to build mine.
I have a last issue I cannot resolve.
When I swipe left, the transition does not work.
The current image disapears before the transition begins.
When I swipe right, it works fine.
Thanks for your help.
Here is my code :
<!DOCTYPE html>
<html lang="fr-FR">
<head>
<meta name="viewport" content="target-densitydpi=device-dpi; width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;"/>
<style>
.flex, .flex-c
{
display: box;
display: flexbox;
display: flex;
}
.flex-c
{
flex-direction: column;
}
.carousel-container
{
overflow: hidden;
}
.carousel-element
{
flex: 1 0 100%;
transform: translateX(0);
order: 2;
}
.carousel-swipeleft
{
transform: translateX(100%);
}
.carousel-swiperight
{
transform: translateX(-100%);
}
.carousel-transition
{
transform: none !important;
transition: transform 0.5s cubic-bezier(0.23, 1, 0.32, 1);
}
.carousel-ocontainer
{
margin: 10px 0;
justify-content: center;
}
.carousel-o
{
background: lightgray none repeat scroll 0 0;
-ms-border-radius: 5px;
border-radius: 5px;
height: 10px;
margin: 0 5px;
outline: 0 none;
text-indent: -9999px;
width: 10px;
padding-bottom: 10px;
}
.carousel-oactive
{
background: black none repeat scroll 0 0;
}
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.js"></script>
<script type="text/javascript">
$.mobile.pushStateEnabled = false;
Oog = function () {};
Oog.Carousel = function (containerClass, loop)
{
var self = this;
self.loop = loop;
self.elementClass = "carousel-element";
self.LazyClass = "carousel-lazy";
self.oContainerClass = containerClass + "-carousel-ocontainer";
self.oClass = "carousel-o";
self.oActiveClass = "carousel-oactive";
self.swipeleftClass = "carousel-swipeleft";
self.swiperightClass = "carousel-swiperight";
self.transitionClass = "carousel-transition";
self.containerSelector = "." + containerClass;
self.elementSelector = self.containerSelector + " ." + self.elementClass;
self.LazySelector = self.containerSelector + " ." + self.LazyClass;
self.findLazySelector = "." + self.LazyClass;
self.oContainerSelector = "." + self.oContainerClass;
self.oSelector = self.oContainerSelector + " ." + self.oClass;
};
Oog.Carousel.prototype =
{
initialize: function()
{
var self = this;
// Bullet points
var elements = $(self.elementSelector);
var html = "<div class='" + self.oContainerClass + " / carousel-ocontainer / flex'>";
for (var i = 0; i < elements.length; i++)
{
html = html + "<p class='" + self.oClass + "' data-id='" + $(elements[i]).data("id") + "'> O </p> ";
}
html = html + "</div>";
$(html).insertAfter(self.containerSelector);
// Affiche les bullets points si et seulement si le carousel est affiché
// -> nécessite que l'event existe (créé dans oog-mobile-script.js)
var oContainerSelector = self.oContainerSelector;
$(self.containerSelector).bind("displayChanged", function ()
{
if ($(this).css("display") === "none")
{
$(oContainerSelector).hide();
} else
{
$(oContainerSelector).show();
}
});
// Affichage du 1er élément du carousel
$(self.LazySelector).first().attr("src", $(self.LazySelector).first().data("src"));
$(self.oContainerSelector).hide();
$(self.oSelector).first().addClass(self.oActiveClass);
// Gestion des déplacements vers la gauche ou la droite
$(self.elementSelector).on("swipeleft", function ()
{
self.swipe(this, "swipeleft");
});
$(self.elementSelector).on("swiperight", function ()
{
self.swipe(this, "swiperight");
});
},
swipe: function(element, swipe)
{
var self = this;
var elements = $(self.elementSelector);
var nextElement;
if (swipe === "swipeleft")
{
elements.removeClass(self.swiperightClass);
elements.addClass(self.swipeleftClass);
nextElement = self.next(element, self.loop);
}
else
{
elements.removeClass(self.swipeleftClass);
elements.addClass(self.swiperightClass);
nextElement = self.prev(element, self.loop);
}
if (nextElement.length > 0)
{
$(self.oSelector).removeClass(self.oActiveClass);
$(self.oSelector + '[data-id="' + nextElement.data("id") + '"]').addClass(self.oActiveClass);
nextElement.find(self.findLazySelector).attr("src", nextElement.find(self.findLazySelector).data("src"));
for (var i = 0; i < elements.length; i++)
{
nextElement.css("order", (i + 1).toString());
nextElement = self.next(nextElement, true);
}
elements.removeClass(self.transitionClass);
setTimeout(function () { elements.addClass(self.transitionClass) }, 50);
}
},
next: function(element, loop)
{
var self = this;
return self.nextorprev(element, "swipeleft", loop);
},
prev: function (element, loop)
{
var self = this;
return self.nextorprev(element, "swiperight", loop);
},
nextorprev: function (element, swipe, loop) {
var self = this;
var elements = $(self.elementSelector);
var current = $(element);
var next;
if (swipe === "swipeleft") {
next = current.next();
if (next.length === 0 && loop) {
next = elements.first();
}
} else {
next = current.prev();
if (next.length === 0 && loop) {
next = elements.last();
}
}
return next;
}
};
$(document).ready(function()
{
var accessoryCarousel = new Oog.Carousel("product-tabAccessories", false);
accessoryCarousel.initialize();
});
</script>
</head>
<body class="body">
<div class="product-tabs / flex">
<div class="product-tab / product-tabAccessories / carousel-container / flex" data-tab="Accessories">
<a href="/prod-16768-Plaque-ONDUVILLA-217m2-rouge-ombre.html" title="Plaque ONDUVILLA rouge ombré, plusieurs surfaces disponibles" class="product-accessory / carousel-element / flex" data-id="16768">
<img class="carousel-lazy" alt="Plaque ONDUVILLA 2.17m² rouge ombré" data-src="http://media.oogarden.com/Product/0290/0290-0007-Thumb.jpg"/>
<div class="flex-c" style="justify-content: space-around; margin-left: 10px;">
<label>Plaque ONDUVILLA rouge ombré, plusieurs surfaces disponibles</label>
</div>
</a>
<a href="/prod-16769-Pointes-pour-feutre-bitumeux-x1200.html" title="Pointes pour bardeaux et feutres bitumeux " class="product-accessory / carousel-element / flex" data-id="16769">
<img class="carousel-lazy" alt="Pointes pour bardeaux et feutres bitumeux " data-src="http://media.oogarden.com/Product/0290/0290-0008-Thumb.jpg"/>
<div class="flex-c" style="justify-content: space-around; margin-left: 10px;">
<label>Pointes pour bardeaux et feutres bitumeux </label>
</div>
</a>
<a href="/prod-16782-Bardoline-100-3m2-bleu-ardoise.html" title="Bardoline couleur ardoise surface 3 m²" class="product-accessory / carousel-element / flex" data-id="16782">
<img class="carousel-lazy" alt="Bardoline couleur ardoise surface 3 m²" data-src="http://media.oogarden.com/Product/0290/0290-0004-Thumb.jpg"/>
<div class="flex-c" style="justify-content: space-around; margin-left: 10px;">
<label>Bardoline couleur ardoise surface 3 m²</label>
</div>
</a>
</div>
</div>
</body>
</html>

Related

programming for js arcgis map

`I'm able to create my own basemap that already build with extent map, maptoggle & basemap gallery and some other widgets(refer image 1).
However, I'm still as a problem to integrate the widget for the timeslidder with the basemap (the given source code) no matter how i tries.
i also attach the link for the source of the timeslidder widget (for your reference) that i want to intergrate with the code i paste here.
[
<html>
<meta name="viewport" content="initial-scale=1, maximum-scale=1,user-scalable=no">
<title>Well completion dates for the Hugoton Gas Field Over Time</title>
<link rel="stylesheet" href="https://js.arcgis.com/3.30/dijit/themes/claro/claro.css">
<link rel="stylesheet" href="https://js.arcgis.com/3.30/esri/css/esri.css">
<style>
html, body,
#mapDiv {
padding:0;
margin:0;
height:100%;
}
#mapDiv {
position: relative;
}
#bottomPanel {
left: 50%;
margin: 0 auto;
margin-left: -500px;
position: absolute;
bottom: 2.5em;
}
#timeInfo{
border-radius: 4px;
border: solid 2px #ccc;
background-color: #fff;
display: block;
padding: 5px;
position: relative;
text-align: center;
width: 1000px;
z-index: 99;
}
#bottomPanel2 {
left: 50%;
margin: 0 auto;
margin-left: -500px;
position: absolute;
bottom: 8.5em;
}
#timeInfo2{
border-radius: 4px;
border: solid 2px #ccc;
background-color: #fff;
display: block;
padding: 5px;
position: relative;
text-align: center;
width: 1000px;
z-index: 99;
}
</style>
<script src="https://js.arcgis.com/3.30/"></script>
<script>
var map;
require([
"esri/map",
"esri/layers/ArcGISDynamicMapServiceLayer",
"esri/geometry/Extent",
"esri/SpatialReference",
"esri/TimeExtent",
"esri/dijit/TimeSlider",
"dojo/_base/array",
"dojo/dom",
"dojo/domReady!",
"dojo/on",
"esri/tasks/query", "esri/tasks/QueryTask"
], function(
Map,
ArcGISDynamicMapServiceLayer,
Extent,
SpatialReference,
TimeExtent,
TimeSlider,
arrayUtils,
dom,on, Query, QueryTask
)
{
var myextent = new Extent(92.14339937585252, -4.921857675800532, 125.89339937584356,11.56021935381215, new SpatialReference({ wkid:4326 }));
map = new Map("mapDiv",
{
basemap: "topo",
extent: myextent, // funct:variable
//center; [103.8999, 1.7381] // longitude, latitude Mas
zoom: 6
});
var opLayer = new ArcGISDynamicMapServiceLayer("http://175.136.253.77/arcgis/rest/services/CAQM/CAQM_Current_Reading/MapServer");
opLayer.setVisibleLayers([0]);
//apply a definition expression so only some features are shown
var layerDefinitions = [];
layerDefinitions[0] = "FIELD_KID=1000148164";
opLayer.setLayerDefinitions(layerDefinitions);
//add the gas fields layer to the map
map.addLayers([opLayer]);
map.on("layers-add-result", initSlider);
map.on("layers-add-result", initSlider2);
function initSlider()
{
var timeSlider = new TimeSlider({
style: "width: 100%;"
}, dom.byId("timeSliderDiv"));
map.setTimeSlider(timeSlider);
var timeExtent = new TimeExtent();
timeExtent.startTime = new Date("01/01/1927 UTC");
timeExtent.endTime = new Date("12/01/1927 UTC");
timeSlider.setThumbCount(1);// Assuming slider has only one thumb:
timeSlider.createTimeStopsByTimeInterval(timeExtent, 1, "esriTimeUnitsMonths");
timeSlider.setThumbIndexes([0,1]);
timeSlider.setThumbMovingRate(1000);//for 2 sec
timeSlider.startup();
//add labels for every other time stop
var labels = arrayUtils.map(timeSlider.timeStops, function(timeStop,i)
{
if ( i % 1 === 0 ) {
return timeStop.getUTCMonth()+1; //to get the sliding timeline bcz getUTCMonth start from zero array
} else {
return "";
}
});
timeSlider.setLabels(labels);
timeSlider.on("time-extent-change", function(evt) {
console.log(startTime.getUTCMonth());
var startValString = evt.startTime.getUTCMonth();
var endValString = evt.endTime.getUTCMonth();
dom.byId("daterange").innerHTML = "<i>" + startValString + " and " + endValString + "<\/i>";
console.log(startValString);
});
}
function initSlider2()
{ var timeSlider = new TimeSlider({
style: "width: 100%;"
}, dom.byId("timeSliderDiv2"));
map.setTimeSlider(timeSlider);
var timeExtent = new TimeExtent();
timeExtent.startTime = new Date("1/1/1927 UTC");
timeExtent.endTime = new Date("1/31/1927 UTC");
timeSlider.setThumbCount(1);// Assuming slider has only one thumb:
timeSlider.createTimeStopsByTimeInterval(timeExtent, 1, "esriTimeUnitsDays");
timeSlider.setThumbIndexes([0,1]);
timeSlider.setThumbMovingRate(2000);//for 2 sec
timeSlider.startup();
//add labels for every other time stop
var labels2 = arrayUtils.map(timeSlider.timeStops, function(timeStop, i)
{ let ii = i+1;
//console.log(timeStop);console.log(ii);
if ( i % 1 === 0 ) {
//return timeStop.getUTCDay();
return ii;
} else {
return "";
}
});
timeSlider.setLabels(labels2);
timeSlider.on("time-extent-change", function(evt) {
var startValString = evt.startTime.getUTCDay();
var endValString = evt.endTime.getUTCDay();
dom.byId("daterange2").innerHTML //= "<i>" + startValString + " and " + endValString + "<\/i>";
});
}
var queryTask = new QueryTask
("http://175.136.253.77/arcgis/rest/services/CAQM/CAQM_CO/MapServer/0");
var query = new Query();
query.where = '1=1';
query.where = dom.byId("state").value;
query.returnGeometry = false;
query.outFields = //["*"];
[ //from the choosen data
"ID", "STATION_ID", "STATION_LOCATION", "PLACE",
"LONGITUDE", "LATITUDE"
];
//on(dom.byId("execute"), "click", execute);
document.getElementById("execute_bttn").onclick = function() {execute_result()};
function execute_result ()
{
<!-- query.text = dom.byId("state").value; -->
query.text = document.getElementById("state").value;
queryTask.execute(query, showResults);
function showResults (results)
{
var resultItems = [];
var resultCount = results.features.length;
for (var i = 0; i < resultCount; i++)
{
var featureAttributes = results.features[i].attributes;
for (var attr in featureAttributes)
{
resultItems.push("<b>" + attr + ":</b> " + featureAttributes[attr] + "<br>");
}
resultItems.push("<br>");
}
//dom.byId("info").innerHTML = resultItems.join("");
document.getElementById("info").innerHTML = resultItems.join("");
}
}
});
</script>
<!-- <div> <input type = "button" id = "MonthButton" value= "MONTH"></div> -->
<div id="mapDiv">
<div id = "slist">STATION LIST :
<input type="text" id="state" placeholder="State">
<input id="execute_bttn" type="button" value="FIND">
<br />
<br />
<div id="info" style="padding:5px; margin:5px; background-color:#eee;">
<br />
<br /></div>
</div>
<div id="bottomPanel">
<div id="timeInfo">
<div>Month in 1927 <span id="daterange">From Jan - Dec</span> (Completion date)</div>
<div id="timeSliderDiv"></div>
</div>
</div>
<div id="bottomPanel2">
<div id="timeInfo2">
<div>Dates For <span id="daterange2">January 1927</span> (Completion date)</div>
<div id="timeSliderDiv2"></div>
</div>
</div>
</div>
I got it already.
Here is the code when I integrate the gis js timeslidder with my api data.
Hopefully this would help other fresh grads like me, who work as gis programmer.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1,user-scalable=no">
<title>Well completion dates for the Hugoton Gas Field Over Time</title>
<link rel="stylesheet" href="https://js.arcgis.com/3.30/dijit/themes/claro/claro.css">
<link rel="stylesheet" href="https://js.arcgis.com/3.30/esri/css/esri.css">
<style>
html, body,
#mapDiv {
padding:0;
margin:0;
height:100%;
}
#mapDiv {
position: relative;
}
#bottomPanel {
left: 50%;
margin: 0 auto;
margin-left: -500px;
position: absolute;
bottom: 2.5em;
}
#timeInfo{
border-radius: 4px;
border: solid 2px #ccc;
background-color: #fff;
display: block;
padding: 5px;
position: relative;
text-align: center;
width: 1000px;
z-index: 99;
}
#bottomPanel2 {
left: 50%;
margin: 0 auto;
margin-left: -500px;
position: absolute;
bottom: 8.5em;
}
#timeInfo2{
border-radius: 4px;
border: solid 2px #ccc;
background-color: #fff;
display: block;
padding: 5px;
position: relative;
text-align: center;
width: 1000px;
z-index: 99;
}
</style>
<script src="https://js.arcgis.com/3.30/"></script>
<script>
var map;
require([
"esri/map",
"esri/layers/ArcGISDynamicMapServiceLayer",
"esri/geometry/Extent",
"esri/SpatialReference",
"esri/TimeExtent",
"esri/dijit/TimeSlider",
"dojo/_base/array",
"esri/tasks/query", "esri/tasks/QueryTask"
], function(
Map,
ArcGISDynamicMapServiceLayer,
Extent,
SpatialReference,
TimeExtent,
TimeSlider,
arrayUtils, Query, QueryTask
)
{
var myextent = new Extent(92.14339937585252, -4.921857675800532, 125.89339937584356,11.56021935381215, new SpatialReference({ wkid:4326 }));
map = new Map("mapDiv",
{
basemap: "topo",
extent: myextent, // funct:variable
//center; [103.8999, 1.7381] // longitude, latitude Mas
zoom: 6
});
var opLayer = new ArcGISDynamicMapServiceLayer("http://175.136.253.77/arcgis/rest/services/CAQM/CAQM_Current_Reading/MapServer");
opLayer.setVisibleLayers([0]);
//apply a definition expression so only some features are shown
var layerDefinitions = [];
layerDefinitions[0] = "FIELD_KID=1000148164";
opLayer.setLayerDefinitions(layerDefinitions);
//add the gas fields layer to the map
map.addLayers([opLayer]);
map.on("layers-add-result", initSlider);
map.on("layers-add-result", initSlider2);
function initSlider()
{
var timeSlider = new TimeSlider({
style: "width: 100%;"
}, document.getElementById("timeSliderDiv"));
map.setTimeSlider(timeSlider);
var timeExtent = new TimeExtent();
timeExtent.startTime = new Date("01/01/1927 UTC");
timeExtent.endTime = new Date("12/01/1927 UTC");
timeSlider.setThumbCount(1);// Assuming slider has only one thumb:
timeSlider.createTimeStopsByTimeInterval(timeExtent, 1, "esriTimeUnitsMonths");
timeSlider.setThumbIndexes([0,1]);
timeSlider.setThumbMovingRate(1000);//for 2 sec
timeSlider.startup();
//add labels for every other time stop
var labels = arrayUtils.map(timeSlider.timeStops, function(timeStop,i)
{
if ( i % 1 === 0 ) {
return timeStop.getUTCMonth()+1; //to get the sliding timeline bcz getUTCMonth start from zero array
} else {
return "";
}
});
timeSlider.setLabels(labels);
timeSlider.on("time-extent-change", function(evt) {
console.log(startTime.getUTCMonth());
var startValString = evt.startTime.getUTCMonth();
var endValString = evt.endTime.getUTCMonth();
dom.byId("daterange").innerHTML = "<i>" + startValString + " and " + endValString + "<\/i>";
console.log(startValString);
});
}
function initSlider2()
{ var timeSlider = new TimeSlider({
style: "width: 100%;"
}, document.getElementById("timeSliderDiv2"));
map.setTimeSlider(timeSlider);
var timeExtent = new TimeExtent();
timeExtent.startTime = new Date("1/1/1927 UTC");
timeExtent.endTime = new Date("1/31/1927 UTC");
timeSlider.setThumbCount(1);// Assuming slider has only one thumb:
timeSlider.createTimeStopsByTimeInterval(timeExtent, 1, "esriTimeUnitsDays");
timeSlider.setThumbIndexes([0,1]);
timeSlider.setThumbMovingRate(2000);//for 2 sec
timeSlider.startup();
//add labels for every other time stop
var labels2 = arrayUtils.map(timeSlider.timeStops, function(timeStop, i)
{ let ii = i+1;
//console.log(timeStop);console.log(ii);
if ( i % 1 === 0 ) {
//return timeStop.getUTCDay();
return ii;
} else {
return "";
}
});
timeSlider.setLabels(labels2);
timeSlider.on("time-extent-change", function(evt) {
var startValString = evt.startTime.getUTCDay();
var endValString = evt.endTime.getUTCDay();
dom.byId("daterange2").innerHTML //= "<i>" + startValString + " and " + endValString + "<\/i>";
});
}
var queryTask = new QueryTask
("http://175.136.253.77/arcgis/rest/services/CAQM/CAQM_CO/MapServer/0");
var query = new Query();
//query.where = '1=1'; //get all data
query.where = document.getElementById("STATE_NAME")//get from the api data
query.returnGeometry = false;
query.outFields = //["*"]; //to get all data column
[ //choosen the data itself tht want to be display
"ID", "STATION_ID", "STATION_LOCATION", "PLACE",
"LONGITUDE", "LATITUDE"
];
//conflict during implementation so need to change n dont used dojo on
//on(dom.byId("execute"), "click", execute);
document.getElementById("execute_bttn").onclick = function() {execute_result()};
function execute_result ()
{
<!-- query.text = dom.byId("state").value; -->
query.text = document.getElementById("state").value; //get value
queryTask.execute(query, showResults);
function showResults (results)
{
var resultItems = [];
var resultCount = results.features.length;
for (var i = 0; i < resultCount; i++)
{
var featureAttributes = results.features[i].attributes;
for (var attr in featureAttributes)
{
resultItems.push("<b>" + attr + ":</b> " + featureAttributes[attr] + "<br>");
}
resultItems.push("<br>");
}
//dom.byId("info").innerHTML = resultItems.join("");
document.getElementById("info").innerHTML = resultItems.join("");
}
}
});
</script>
</head>
<body class="claro">
<div id="mapDiv">
<div id = "slist"><br />STATION LIST :
<input type="text" id="state" placeholder="State">
<input id="execute_bttn" type="button" value="FIND">
<br />
<br />
<div id="info" style="padding:5px; margin:5px; background-color:#eee;">
<br />
<br /></div>
</div>
<div id="bottomPanel">
<div id="timeInfo">
<div>Month in 1927 <span id="daterange">From Jan - Dec</span> (Completion date)</div>
<div id="timeSliderDiv"></div>
</div>
</div>
<div id="bottomPanel2">
<div id="timeInfo2">
<div>Dates For <span id="daterange2">January 1927</span> (Completion date)</div>
<div id="timeSliderDiv2"></div>
</div>
</div>
</div>
</body>
</html>
`

jQuery - pre-set array values for add-to-cart

I have a basic add-to-cart that allows for adding and removing cart items using checkboxes.
I want to be able to pre-set some of the items to be in the cart by getting the item's id or data-wish attribute and adding it to the array for the items.
var wish = {
items: ["handbag", "backpack"]
};
How do I allow for items to be pre-selected so that they appear in the cart and the .my-wish-add button is :checked (for the icon's checked state animation).
// Wish Function
var wish = {
items: []
};
var update_product = function(product) {};
$(function() {
//Add to wish
var addToWish = function(product, qty) {
qty = qty || 1;
var wish = getWish();
var indexOfId = wish.items.findIndex(x => x.id == product.id);
if (indexOfId === -1) {
wish.items.push({
id: product.id,
img: product.img,
name: product.name,
location: product.location,
price: product.price
});
$parent = $("#" + product.id).closest(".items__cart");
$parent
.find(".wish-icon")
.addClass("active")
.attr("data-prefix", "fas");
} else {
wish.items[indexOfId].stock = Number(product.stock);
}
//Update popup wish
updateWish(wish);
};
//Remove from wish on id
var removeFromWish = function(id) {
var wish = getWish();
var wishIndex = wish.items.findIndex(x => x.id == id);
wish.items.splice(wishIndex, 1);
$parent = $("#" + id).closest(".items__cart");
$parent
.find(".wish-icon")
.first()
.removeClass("active")
.attr("data-prefix", "far");
//Update popup wish
updateWish(wish);
};
var getProductValues = function(element) {
var productId = $(element)
.closest(".items__cart")
.find(".item__tile")
.attr("id");
var productImg = $(element)
.closest(".items__cart")
.find(".item__img")
.attr("src");
var productName = $(element)
.closest(".items__cart")
.find(".item__title")
.html();
var productPrice = $(element)
.closest(".items__cart")
.find(".cost")
.html();
var productLocation = $(element)
.closest(".items__cart")
.find(".item__location")
.html();
var productTax = $(element)
.closest(".items__cart")
.find(".circle")
.html();
return {
id: productId,
img: productImg,
name: productName,
location: productLocation,
price: productPrice,
tax: productTax
};
};
$(".my-wish-add").on("change", function() {
var product = getProductValues(this);
if ($(this).is(":checked")) {
addToWish({
id: product.id,
img: product.img,
name: product.name,
location: product.location,
price: product.price,
tax: product.tax
});
} else {
removeFromWish(product.id);
}
});
//Update wish html to reflect changes
var updateWish = function(wish) {
$(".wishlist__items").html("");
for (var i = 0; i < wish.items.length; i++) {
$(".wishlist__items").append(
"<li class='wish__item'>" +
'<div class="wish__thumb">' +
"<img src='" +
wish.items[i].img +
"' />" +
"</div>" +
'<div class="wish__info">' +
'<div class="wish__header">' +
'<div class="wish-name">' +
wish.items[i].name +
"</div>" +
"</div>" +
' <div class="wish__value">' +
"<span>Price: </span> $ " +
wish.items[i].price +
"</div>" +
"</div>" +
'<div class="wish__remove">' +
'<label class="wish__label">' +
'<input type="checkbox" id="my-wish-remove' +
i +
'" class="my-wish-remove" aria-hidden="true">' +
"<i class='fas fa-heart'></i>" +
"</div>" +
"</div>"
);
(function() {
var currentIndex = i;
$("#my-wish-remove" + currentIndex).on("change", function() {
$(this)
.closest("li")
.hide(400);
setTimeout(function() {
wish.items[currentIndex].stock = "";
update_product(wish.items[currentIndex]);
$("#" + wish.items[currentIndex].id)
.parents()
.find($(".wish-btn > input"))
.prop("checked", false);
removeFromWish(wish.items[currentIndex].id);
}, 400);
});
})();
}
};
//Get Wish
var getWish = function() {
var myWish = wish;
return myWish;
};
});
.wish__item {
display: flex;
}
.my-wish-add {
font-family: "Font Awesome\ 5 Pro";
font-weight: 900;
color: #6394f8;
}
.wish-btn {
position: relative;
cursor: pointer;
}
.wish-btn input {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
}
.wish-icon.active {
color: green;
}
.active i.fa.fa-wishlist__list {
color: #6394f8;
}
.my-wish-remove {
font-size: 20px;
cursor: pointer;
color: rgb(109, 109, 109);
}
.my-wish-remove:hover {
color: #464646;
}
.items__wish {
border: 1px solid;
width: 150px;
}
.wish__info {
flex: 1;
border: 2px solid;
}
.wish__thumb {
display: flex;
}
.wish__thumb img {
height: 30px;
}
.wish-main {
flex: 1;
}
img {
width: 50px;
}
.wishlist__list {
margin: 20px 0;
float: right;
background: #fff;
width: 320px;
position: absolute;
border: 2px solid;
border-radius: 3px;
padding: 20px;
right: 7.5%;
}
.wishlist__items li {
list-style: none;
}
.wishlist__list-empty img {
width: 100px;
}
<script src="https://pro.fontawesome.com/releases/v5.3.1/js/all.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div data-id="wishlist">
<div class="wishlist__list">
<ul class="wishlist__items">
</ul>
</div>
</div>
<div class='products'>
<div class="items__cart">
<div id='headphones' class='item__title item__tile' data-wish="headphones">Product 1</div>
<img class="item__img" src="https://www.iconasys.com/wp-content/uploads/2017/06/360-Product-Photography-White-Background-Acrylic-Riser-08.jpg">
<div>
<span>$</span>
<span class='cost'>500</span>
</div>
<label class="wish-btn">
<input type="checkbox" name="wish-check" class='my-wish-add'><i class="wish-icon far fa-heart"></i></input></label>
</div>
<div class="items__cart">
<div id='backpack' class='item__title item__tile' data-wish="backpack">Product 2</div>
<div>
<h4 class="count">200</h4>
</div>
<img class="item__img" src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQoqpSgkG4AQDQOe33jI1NiW3GW2JSB-_v36aREsVyFQH55JFOJ">
<div>
<span>$</span>
<span class='cost'>460</span>
</div>
<label class="wish-btn">
<input type="checkbox" name="wish-check" class='my-wish-add'><i class="wish-icon far fa-heart"></i></label>
</div>
<div class="items__cart">
<div id='handbag' class='item__title item__tile' data-wish="handbag">Product 3</div>
<h4 class="count">400</h4>
<img class="item__img" src="https://qph.fs.quoracdn.net/main-qimg-de7d9680c4460296e461af9720a77d64">
<div>
<span>$</span>
<span class='cost'>212</span>
</div>
<label class="wish-btn">
<input type="checkbox" name="wish-check" class='my-wish-add'><i class="wish-icon far fa-heart"></i></label>
</div>

How to delete an item from a drag and drop menu

I'm trying to add an Delete button function to a drag and drop shopping cart. I have the button in place but I can not call a function that seems to work. I'm very novice.
Im not sure if were the function should appear because the list is created from a drag and drop menu
Below is the code so far - any help would be greatly appreciated
thanks
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>HTML 5 Drag and Drop Shopping Cart</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
.products1 { grid-area: products1; }
.menu1 { grid-area: menu1; }
.menu2 { grid-area: menu2; }
.menu3 { grid-area: menu3; }
.menu4 { grid-area: menu4; }
.grid-container {
display: grid;
grid-template-areas:
'products1 menu1 menu2 menu3 menu4'
;
grid-gap: 5px;
background-color: #2196F3;
padding: 5px;
}
.grid-container > div {
background-color: rgba(255, 255, 255, 0.8);
text-align: center;
padding: 20px 0;
font-size: 20px;
}
#item-container{
width: 280px;
padding: 10px;
border: 5px solid gray;
margin:20px auto;
text-align: center;
font-size: 20px;
}
ul, li{
list-style: none;
margin: 2px;
padding: 0px;
cursor: grabbing;
}
section#cart ul{
height: 600px;
overflow: auto;
background-color: #cccccc;
}
</style>
<script src="jquery-3.3.1.min.js"></script>
<script>
function addEvent(element, event, delegate ) {
if (typeof (window.event) != 'undefined' && element.attachEvent)
element.attachEvent('on' + event, delegate);
else
element.addEventListener(event, delegate, false);
}
addEvent(document, 'readystatechange', function() {
if ( document.readyState !== "complete" )
return true;
var items = document.querySelectorAll("section.products ul li");
var cart = document.querySelectorAll("#cart ul")[0];
function updateCart(){
var total = 0;
var term = 48;
var rate = 7;
var amount = 15090;
var cart_items = document.querySelectorAll("#cart ul li")
for (var i = 0; i < cart_items.length; i++) {
var cart_item = cart_items[i];
var quantity = cart_item.getAttribute('data-quantity');
var price = cart_item.getAttribute('data-price');
var payment = amount*((((rate/12)/100)*((1+((rate/12)/100))**term))/(((1+((rate/12)/100))**term)-1));
var sub_total = parseFloat(quantity * parseFloat(price));
cart_item.querySelectorAll("span.sub-total")[0].innerHTML = + sub_total.toFixed(2);
total += sub_total*((((rate/12)/100)*((1+((rate/12)/100))**term))/(((1+((rate/12)/100))**term)-1));
newpayment=total+payment
}
document.querySelectorAll("#cart span.total")[0].innerHTML = total.toFixed(2);
document.querySelectorAll("#cart span.newpayment")[0].innerHTML = newpayment.toFixed(2);
}
function addCartItem(item, id) {
var clone = item.cloneNode(true);
clone.setAttribute('data-id', id);
clone.setAttribute('data-quantity', 1);
clone.removeAttribute('id');
var fragment = document.createElement('span');
fragment.setAttribute('class', 'quantity');
fragment.innerHTML = '<button id="butt" onclick="one(this);">delete item</button> $';
clone.appendChild(fragment);
fragment = document.createElement('span');
fragment.setAttribute('class', 'sub-total');
clone.appendChild(fragment);
cart.appendChild(clone);
}
function updateCartItem(item){
var quantity = item.getAttribute('data-quantity');
quantity = parseInt(quantity) + 1
item.setAttribute('data-quantity', quantity);
var span = item.querySelectorAll('span.quantity');
span[0].innerHTML = ' x ' + quantity;
}
function onDrop(event){
if(event.preventDefault) event.preventDefault();
if (event.stopPropagation) event.stopPropagation();
else event.cancelBubble = true;
var id = event.dataTransfer.getData("Text");
var item = document.getElementById(id);
var exists = document.querySelectorAll("#cart ul li[data-id='" + id + "']");
{
addCartItem(item, id);
}
updateCart();
return false;
}
function onDragOver(event){
if(event.preventDefault) event.preventDefault();
if (event.stopPropagation) event.stopPropagation();
else event.cancelBubble = true;
return false;
}
addEvent(cart, 'drop', onDrop);
addEvent(cart, 'dragover', onDragOver);
function onDrag(event){
event.dataTransfer.effectAllowed = "move";
event.dataTransfer.dropEffect = "move";
var target = event.target || event.srcElement;
var success = event.dataTransfer.setData('Text', target.id);
}
for (var i = 0; i < items.length; i++) {
var item = items[i];
item.setAttribute("draggable", "true");
addEvent(item, 'dragstart', onDrag);
};
});
</script>
</head>
<body>
<div id="page">
<div class="grid-container">
<div class="products1">
<section id="products" class="products">
<h1></h1>
<ul>
<li id="product-1" data-price="3999.00"><div id="item-container">Product 1<br> descr<br>descr </div></li>
<li id="product-2" data-price="1895"><div id="item-container">Product 2<br> descr<br>descrip</div></li>
<li id="product-3" data-price="2.99"><span>Product 3</span></li>
<li id="product-4" data-price="3.50"><span>Product 4</span></li>
<li id="product-5" data-price="4.25"><span>Product 5</span></li>
<li id="product-6" data-price="6.75"><span>Product 6</span></li>
<li id="product-7" data-price="1.99"><span>Product 7</span></li>
</ul>
</section>
</div>
<div class="menu1">
<section id="cart" class="shopping-cart">
<h1>Preferred</h1>
<ul>
</ul>
<p> $<span class="total">0.00</span></p>
<p> $<span class="newpayment">0.00</span></p>
</section>
</div>
<div class="menu2">
<section id="cart" class="shopping-cart">
<h1>Value</h1>
<ul>
</ul>
<p> $<span class="total">0.00</span></p>
</section>
</div>
<div class="menu3">
<section id="cart" class="shopping-cart">
<h1>Basic</h1>
<ul>
</ul>
<p> $<span class="total">0.00</span></p>
</section>
</div>
<div class="menu4">
<section id="cart" class="shopping-cart">
<h1>Economy</h1>
<ul>
</ul>
<p> $<span class="total">0.00</span></p>
</section>
</div>
</div>
</div>
</body>
</html>

Auto record and allow to play once using JQuery

Hiii Everyone,
Below is the sample code for record.
<html>
<body>
<audio controls autoplay></audio>
<input onclick="startRecording()" type="button" value="start recording" />
<input onclick="stopRecording()" type="button" value="stop recording and play" />
<script>
var onFail = function(e) {
console.log('Rejected!', e);
};
var onSuccess = function(s) {
stream = s;
}
window.URL = window.URL || window.webkitURL;
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
var stream;
var audio = document.querySelector('audio');
function startRecording() {
if (navigator.getUserMedia) {
navigator.getUserMedia({audio: true}, onSuccess, onFail);
} else {
console.log('navigator.getUserMedia not present');
}
}
function stopRecording() {
audio.src = window.URL.createObjectURL(stream);
}
</script>
</body>
</html>
What I want to do is setInterval for 40 secs it will buffer for 40 secs like recording will start in 40secs timer will run after 40 secs it will show the play button to check audio recorded.Below I had added sample screenshots
Progress bar will show the recording..Similarly there will be some question with audio there I need to start recording once audio complete play.If anybody knows solution for this issue Please help me.Thanks for ur support
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<style>
.center_div {
width: 500px;
height: 100px;
background-color: #f5f5f5;
border: 1px solid #808080;
position: absolute;
top: 50%;
left: 50%;
margin-left: -250px;
/* half width*/
margin-top: -50px;
/* half height*/
padding: 25px;
}
.recording_label {
display: block;
text-align: center;
padding: 10px;
font-family: sans-serif;
font-size: 1.1em;
margin-bottom: 25px;
}
.loader_bg {
min-width: 100%;
background: #c5c5c5;
min-height: 20px;
display: block;
}
.loader_bg1 {
min-width: 90%;
background: grey;
min-height: 20px;
display: inline-block;
position: relative;
top: -20px;
}
</style>
</head>
<body>
<audio controls autoplay></audio>
<input onclick="startRecording();" type="button" value="start recording" />
<input onclick="stopRecording();" type="button" value="stop recording and play" />
<div class="center_div">
<span class="recording_label">Please wait...</span>
<span class="loader_bg"></span>
<span class="loader_bg1"></span>
</div>
<script>
var onFail = function(e) {
console.log('Rejected!', e);
};
var onSuccess = function(s) {
stream = s;
}
window.URL = window.URL || window.webkitURL;
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
var stream;
var audio = document.querySelector('audio');
function startRecording() {
if (navigator.getUserMedia) {
navigator.getUserMedia({
audio: true
}, onSuccess, onFail);
} else {
console.log('navigator.getUserMedia not present');
}
}
function stopRecording() {
audio.src = window.URL.createObjectURL(stream);
}
$(function() {
var max = 40;
var count = max + 1;
var counter = setInterval(timer, 1000);
function timer() {
count = count - 1;
if (count <= 0) {
clearInterval(counter);
$(".recording_label").html("Recording...");
$('.loader_bg1').css({
'min-width': '' + (100) + '%'
})
startRecording();
recordingSec(40);
return;
}
$(".recording_label").html("Recording will begin in " + count + " sec.");
var percent = (count / max) * 100;
$('.loader_bg1').css({
'min-width': '' + (100 - percent) + '%'
})
}
});
function recordingSec(sec) {
var count = sec + 1;
var counter = setInterval(timer, 1000);
function timer() {
count = count - 1;
if (count <= 0) {
clearInterval(counter);
$(".recording_label").html("Recording stopped...Playing");
$('.loader_bg1').css({
'min-width': '' + (100) + '%'
})
stopRecording();
return;
}
$(".recording_label").html("Recording started [ " + (sec - count) + " / " + sec + " ] sec.");
var percent = (count / sec) * 100;
$('.loader_bg1').css({
'min-width': '' + (100 - percent) + '%'
})
}
}
</script>
</body>
</html>
Try To Use:
.btn-primary-success {
color: #fff;
background-color: #04b5e0;
border-color: #04b5e0;
}
.btn-primary-success:hover, .btn-primary-success:focus, .btn-primary-success:active, .btn-primary-success.active, .open .dropdown-toggle.btn-primary-success {
color: #fff;
background-color: #09a0c5;
border-color: #09a0c5;
}
Using Html Code:
<div style="text-align: left; padding: 10px;">
<label style="margin-right: 10px; font-size: 14px !important;">Dictate Status</label>
<a class="btn btn-primary-success pauseAudioDocWS pause" title="Pause" style="display: none; margin-right: 5px;"
data-value="">
<i class="imgpauseWS fa fa-lg fa-pause" style="cursor: pointer; margin: 2px 5px;"></i>
<b class="ppauseWS btn-primary-success">Pause</b></a>
<a class="btn btn-primary-success recordAudioDocWS inActiveWS" title="Start" style="margin-right: 20px;"
data-value="">
<b class="pplayWS">Click here to Start</b>
<i class="imgplayWS fa fa-lg fa-microphone" style="cursor: pointer; margin: 2px 5px;"></i>
</a>
<span class="stopwatchWS" style="display: none; margin-right: 10px;">00:00:00</span>
</div>
Download Audio and Timer File in github links:
https://github.com/fezalhalai/AudioRecorder.js
Using Jquery Code:
<script src="../js/StopTimer.js"></script>
<script src="../js/jquery.timer.js"></script>
<script src="../js/AudioRecorder.js"></script>
<script src="https://cdn.webrtc-experiment.com/RecordRTC.js" type="text/javascript"></script>
<script src="https://cdn.webrtc-experiment.com/gif-recorder.js" type="text/javascript"></script>
<script src="https://cdn.webrtc-experiment.com/gumadapter.js" type="text/javascript"></script>
<script src="https://cdn.webrtc-experiment.com/DetectRTC.js" type="text/javascript"> </script>
<script type="text/javascript">
$(document).ready(function () {
var oldRecorderWS;
$('.recordAudioDocWS').click(function () {
var $this = $(this);
if (oldRecorderWS != undefined) {
if (oldRecorderWS != document.tmId) {
alert('Dictating Already In Progress, Please Stop Previous Dictating To Continue');
return;
}
}
var checkin_id = document.tmId;
localStorage.setItem('checkin_id', checkin_id);
localStorage.setItem('Tran_Type', 'W');
oldRecorderWS = document.tmId;
var roomId = document.tmId;
localStorage.setItem('roomId', roomId);
var isRecording = false;
$(".isActiveWS").each(function () {
if ($(this).hasClass('isActiveWS')) {
isRecording = true;
}
});
if (isRecording == true) {
document.isRecordActivityPerforms = true;
if (confirm('Dictating in progress do you want to stop and save?')) {
oldRecorderWS = undefined;
$this.next('span').css('display', 'none');
Example1.resetStopwatch();
$('.stoprecmessage').css('display', 'block');
$(".isActiveWS").each(function () {
$(this).addClass('inActiveWS');
$(this).removeClass('isActiveWS');
$(this).find('.pplayWS').text('Click here to Start');
//$(this).find('.imgplay').attr('src', 'img/play.png');
$(this).find('.imgplayWS').addClass('fa-stop');
$(this).find('.imgplayWS').addClass('fa-microphone');
$(this).attr('title', 'Start');
});
//$('.tbothers').css('pointer-events', 'auto');
$('.btn-ws-next').removeAttr('disabled', '');
$('.btn-ws-prv').removeAttr('disabled', '');
$this.prev('a').css('display', 'none');
$this.prev('a').addClass('pause');
StartRecording();
document.isRecordActivityPerform = false;
//$this.next().next('img').removeClass('hidden');
if ($(CurruntAudioRecRow).parent().parent().find('.hdtmvid').val() == document.tmId) {
$(CurruntAudioRecRow).parent().parent().find('td .audioList').removeClass();
$(CurruntAudioRecRow).parent().parent().find('td .REC').removeClass('hidden');
$(CurruntAudioRecRow).parent().parent().find('td .PEN').addClass('hidden');
}
}
}
else {
$('.btn-ws-next').attr('disabled', 'disabled');
$('.btn-ws-prv').attr('disabled', 'disabled');
document.isRecordActivityPerform = true;
$this.next('span').css('display', 'inline');
$this.next().next('img').addClass('hidden');
Example1.init($this.next('span'));
Example1.resetStopwatch();
Example1.Timer.toggle();
$this.removeClass('inActiveWS');
$this.addClass('isActiveWS');
$this.find('.pplayWS').text('Stop');
//$this.find('.imgplay').attr('src', 'img/stop.png');
$this.find('.imgplayWS').removeClass('fa-microphone');
$this.find('.imgplayWS').addClass('fa-stop');
$this.attr('title', 'Stop');
$this.prev('a').css('display', 'inline-table');
StartRecording();
}
});
$('.pauseAudioDocWS').click(function () {
document.isRecordActivityPerform = true;
var $this = $(this);
Example1.Timer.toggle();
var btnStartRecording = document.querySelector('#btn-start-recording');
if ($(this).hasClass('pause')) {
btnStartRecording.recordRTC.pauseRecording();
recordingPlayer.pause();
$(this).addClass('resume');
$(this).removeClass('pause');
$(this).find('.ppauseWS').text('Resume');
//$(this).find('.imgpause').attr('src', 'img/play.png');
$(this).find('.imgpauseWS').removeClass('fa-pause');
$(this).find('.imgpauseWS').addClass('fa-microphone');
$(this).attr('title', 'Resume');
$(this).next('a').css('pointer-events', 'none');
$(this).next('a').attr('disabled', 'disabled');
}
else if ($(this).hasClass('resume')) {
btnStartRecording.recordRTC.resumeRecording();
recordingPlayer.play();
$(this).addClass('pause');
$(this).removeClass('resume');
$(this).find('.ppauseWS').text('Pause');
//$(this).find('.imgpause').attr('src', 'img/pause.png');
$(this).find('.imgpauseWS').removeClass('fa-microphone');
$(this).find('.imgpauseWS').addClass('fa-pause');
$(this).attr('title', 'Pause');
$(this).next('a').css('pointer-events', 'auto');
$(this).next('a').removeAttr('disabled');
}
});
});
</script>

Complete function not forcing jquery to wait for end of animation

I am trying to use a counter in my complete function to make sure the animation of margin-top is completed before moving on. Right now, I have the counter in my MakeList(), and in my Spin() function, I console.log the counter and it doesn't recognize the counter++ because it fires before the animation finishes. Nobody I ask can figure out why.
** Note: I can't use timeOut's because the time is set to random (supposed to look like a slot machine ** Also, I can't find what this test platform is saying is an error, but the code runs on my machine. really the script-2.js is all i need to show to get point across though :)
// ********************************************************
// SLOT MACHINE ICONS. Each array has 3 icons for each slot
// ********************************************************
var array1 = [
'<div data-id="0" style="width:100%; background:#fff; height:150px;"></div>',
'<div data-id="1" style="width:100%; background:#ccc; height:150px;"></div>',
'<div data-id="0" style="width:100%; background:#666; height:150px;"></div>'
]
var array2 = [
'<div data-id="0" style="width:100%; background:#fff; height:150px;"></div>',
'<div data-id="1" style="width:100%; background:#ccc; height:150px;"></div>',
'<div data-id="0" style="width:100%; background:#666; height:150px;"></div>'
]
var array3 = [
'<div data-id="0" style="width:100%; background:#fff; height:150px;"></div>',
'<div data-id="1" style="width:100%; background:#ccc; height:150px;"></div>',
'<div data-id="0" style="width:100%; background:#666; height:150px;"></div>'
]
// Generates random # between 0 and 2. Used for choosing winner and creating random slots
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
// Generates winning array item between coffee, tea and espresso
function win(whatArray){
var arrayItem = getRandomInt(0,2);
var winItem = whatArray[arrayItem];
return winItem;
}
// Populates each slot with random icons to spin through
var makeList = function(whatArray, whatSlot){
var slotArray = [];
for(i=0; i < 100; i++){
var randNum = getRandomInt(0,2); // Generate random number
var findItem = whatArray[randNum]; // Use random number to find associated array item
var slot = whatSlot; // Set which slot to append array item to (first, second or third)
$('#' + slot).append('<div>'+findItem+'</div>'); // Append icon to HTML
}
var winItem = win(whatArray); // Generate winning icon for slot
console.log("winner " + winItem);
$('#' + slot).append('<div>'+winItem+'</div>'); // Append winning icon to end of list
}
// Spin the slot and win some caffeine!
function Spin(){
window.counter = 0;
// Generate lists for each slot
makeList(array1, 'slot-1');
makeList(array2, 'slot-2');
makeList(array3, 'slot-3');
MoveSlots($('#slot1-wrapper'), 2500);
MoveSlots($('#slot2-wrapper'), 5200);
MoveSlots($('#slot3-wrapper'), 500);
//var running = true;
// console.log(running);
var slot1attr = $('#slot1-wrapper div').children().last().attr('data-id');
var slot2attr = $('#slot2-wrapper div').children().last().attr('data-id');
var slot3attr = $('#slot3-wrapper div').children().last().attr('data-id');
console.log('counter = ' + counter);
if(counter > 0){
if(slot1attr == slot2attr && slot1attr == slot3attr ){
console.log("WIN");
} else {
console.log("LOSE");
}
}
function MoveSlots(el, speed){
var time = speed;
time += Math.round(Math.random()*10000);
el.stop(true,true);
var marginTop = -(100 * 150 ); //change 100 to height placeholder
var running = true;
el.animate({
'margin-top':'+='+marginTop+'px'
}, {
'duration' : time,
'easing' : 'easeInOutQuint',
complete: function(){
console.log('yolo');
//$(this).on('animationend webkitAnimationEnd oAnimationEnd MSAnimationEnd', function(){
counter++;
console.log(counter);
//})
}
});
} // end MoveSlots
} // end Spin
body{
/*background-color:white;*/
padding:50px;
margin:50px;
background: #505f77 !important;
}
#slotWrapper {
width:410px;
height:150px;
margin:50px auto;
overflow: hidden;
position:relative;
border:1px solid #f00;
}
#slot1-wrapper, #slot2-wrapper, #slot3-wrapper {
margin-top:0;
position: relative;
}
.slot {
width:120px;
height:150px;
margin-right:25px;
text-align:center;
float:left;
position: absolute;
}
#slot-3 {
margin-right:0;
}
#slot-1 {
top:0;
left:0;
}
#slot-2 {
top:0;
left:145px;
}
#slot-3 {
top:0;
left:290px;
}
.slot div {
width:120px;
height:150px;
}
.slot div img {
width:100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<link rel="stylesheet" type="text/css" href="css/style.css" />
<!-- <link rel="stylesheet" type="text/css" href="css/default.css" />
<link rel="stylesheet" type="text/css" href="css/component.css" /> -->
<div style="text-align:center">
<input type="button" value="spin!" onClick="Spin();" style="margin-top:4px;">
</div>
<div id="slotWrapper">
<div id="slot1-wrapper">
<div id="slot-1" class="slot"></div>
</div>
<div id="slot2-wrapper">
<div id="slot-2" class="slot"></div>
</div>
<div id="slot3-wrapper">
<div id="slot-3" class="slot"></div>
</div>
</div>
</body>
</html>
The problem is complete is executed asynchronously, ie the counter condition is executed is before the animations are completed.
You can use the animation promise to solve it
// ********************************************************
// SLOT MACHINE ICONS. Each array has 3 icons for each slot
// ********************************************************
var array1 = [
'<div data-id="0" style="width:100%; background:#fff; height:150px;"></div>',
'<div data-id="1" style="width:100%; background:#ccc; height:150px;"></div>',
'<div data-id="0" style="width:100%; background:#666; height:150px;"></div>'
]
var array2 = [
'<div data-id="0" style="width:100%; background:#fff; height:150px;"></div>',
'<div data-id="1" style="width:100%; background:#ccc; height:150px;"></div>',
'<div data-id="0" style="width:100%; background:#666; height:150px;"></div>'
]
var array3 = [
'<div data-id="0" style="width:100%; background:#fff; height:150px;"></div>',
'<div data-id="1" style="width:100%; background:#ccc; height:150px;"></div>',
'<div data-id="0" style="width:100%; background:#666; height:150px;"></div>'
]
// Generates random # between 0 and 2. Used for choosing winner and creating random slots
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
// Generates winning array item between coffee, tea and espresso
function win(whatArray) {
var arrayItem = getRandomInt(0, 2);
var winItem = whatArray[arrayItem];
return winItem;
}
// Populates each slot with random icons to spin through
var makeList = function(whatArray, whatSlot) {
var slotArray = [];
for (i = 0; i < 100; i++) {
var randNum = getRandomInt(0, 2); // Generate random number
var findItem = whatArray[randNum]; // Use random number to find associated array item
var slot = whatSlot; // Set which slot to append array item to (first, second or third)
$('#' + slot).append('<div>' + findItem + '</div>'); // Append icon to HTML
}
var winItem = win(whatArray); // Generate winning icon for slot
console.log("winner " + winItem);
$('#' + slot).append('<div>' + winItem + '</div>'); // Append winning icon to end of list
}
// Spin the slot and win some caffeine!
function Spin() {
var counter = 0;
// Generate lists for each slot
makeList(array1, 'slot-1');
makeList(array2, 'slot-2');
makeList(array3, 'slot-3');
var p1 = MoveSlots($('#slot1-wrapper'), 2500);
var p2 = MoveSlots($('#slot2-wrapper'), 5200);
var p3 = MoveSlots($('#slot3-wrapper'), 500);
$.when(p1, p2, p3).then(function() {
//var running = true;
// console.log(running);
var slot1attr = $('#slot1-wrapper div').children().last().attr('data-id');
var slot2attr = $('#slot2-wrapper div').children().last().attr('data-id');
var slot3attr = $('#slot3-wrapper div').children().last().attr('data-id');
console.log('counter = ' + counter);
if (counter > 0) {
if (slot1attr == slot2attr && slot1attr == slot3attr) {
console.log("WIN");
} else {
console.log("LOSE");
}
}
});
function MoveSlots(el, speed) {
var time = speed;
time += Math.round(Math.random() * 10000);
el.stop(true, true);
var marginTop = -(100 * 150); //change 100 to height placeholder
var running = true;
el.animate({
'margin-top': '+=' + marginTop + 'px'
}, {
'duration': time,
'easing': 'easeInOutQuint',
complete: function() {
console.log('yolo');
counter++;
console.log(counter);
}
});
return el.promise();
} // end MoveSlots
} // end Spin
body {
/*background-color:white;*/
padding: 50px;
margin: 50px;
background: #505f77 !important;
}
#slotWrapper {
width: 410px;
height: 150px;
margin: 50px auto;
overflow: hidden;
position: relative;
border: 1px solid #f00;
}
#slot1-wrapper,
#slot2-wrapper,
#slot3-wrapper {
margin-top: 0;
position: relative;
}
.slot {
width: 120px;
height: 150px;
margin-right: 25px;
text-align: center;
float: left;
position: absolute;
}
#slot-3 {
margin-right: 0;
}
#slot-1 {
top: 0;
left: 0;
}
#slot-2 {
top: 0;
left: 145px;
}
#slot-3 {
top: 0;
left: 290px;
}
.slot div {
width: 120px;
height: 150px;
}
.slot div img {
width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.js"></script>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/redmond/jquery-ui.css" rel="stylesheet" />
<div style="text-align:center">
<input type="button" value="spin!" onClick="Spin();" style="margin-top:4px;">
</div>
<div id="slotWrapper">
<div id="slot1-wrapper">
<div id="slot-1" class="slot"></div>
</div>
<div id="slot2-wrapper">
<div id="slot-2" class="slot"></div>
</div>
<div id="slot3-wrapper">
<div id="slot-3" class="slot"></div>
</div>
</div>

Categories