How to fix "Cannot read property 'setAttribute' of undefined" - javascript

I'm trying to create a code to show 5 buttons categories and the slider of the last products below. On mouseover effect on any category I'm expecting to see the relevant products of woocommerce. But it doesn't work: neither the buttons nor the product slider. I have an error in console "Cannot read property 'setAttribute' of undefined". How can it possible to solve the problem?
var carouseltopHtml = [];
jQuery(function($) {
var touchtimea = 0;
var touchtimeb = 0;
var touchtimec = 0;
var touchtimed = 0;
var touchtimee = 0;
$("#top_a_category_0").on("click", function() {
if (touchtimea == 0) {
onmuseoverslider(0);
touchtimea = new Date().getTime();
touchtimeb = 0;
touchtimec = 0;
touchtimed = 0;
touchtimee = 0;
if (window.innerWidth < 1024) {
return false;
}
} else {
// compare first click to this click and see if they occurred within double click threshold
if (((new Date().getTime()) - touchtimea) < 3000) {
window.location = this.href;
touchtimea = 0;
} else {
// not a double click so set as a new first click
touchtimea = new Date().getTime();
return false;
}
}
});
$("#top_a_category_1").on("click", function() {
if (touchtimeb == 0) {
onmuseoverslider(1);
touchtimeb = new Date().getTime();
touchtimea = 0;
touchtimec = 0;
touchtimed = 0;
touchtimee = 0;
if (window.innerWidth < 1024) {
return false;
}
} else {
// compare first click to this click and see if they occurred within double click threshold
if (((new Date().getTime()) - touchtimeb) < 3000) {
window.location = this.href;
touchtimeb = 0;
} else {
// not a double click so set as a new first click
touchtimeb = new Date().getTime();
return false;
}
}
});
$("#top_a_category_2").on("click", function() {
if (touchtimec == 0) {
onmuseoverslider(2);
touchtimea = 0;
touchtimeb = 0;
touchtimed = 0;
touchtimee = 0;
touchtimec = new Date().getTime();
if (window.innerWidth < 1024) {
return false;
}
} else {
// compare first click to this click and see if they occurred within double click threshold
if (((new Date().getTime()) - touchtimec) < 3000) {
window.location = this.href;
touchtimec = 0;
} else {
// not a double click so set as a new first click
touchtimec = new Date().getTime();
return false;
}
}
});
$("#top_a_category_3").on("click", function() {
if (touchtimed == 0) {
onmuseoverslider(3);
touchtimed = new Date().getTime();
touchtimea = 0;
touchtimeb = 0;
touchtimec = 0;
touchtimee = 0;
if (window.innerWidth < 1024) {
return false;
}
} else {
// compare first click to this click and see if they occurred within double click threshold
if (((new Date().getTime()) - touchtimed) < 3000) {
window.location = this.href;
touchtimed = 0;
} else {
// not a double click so set as a new first click
touchtimed = new Date().getTime();
return false;
}
}
});
$("#top_a_category_4").on("click", function() {
if (touchtimee == 0) {
onmuseoverslider(4);
touchtimee = new Date().getTime();
touchtimea = 0;
touchtimeb = 0;
touchtimec = 0;
touchtimed = 0;
if (window.innerWidth < 1024) {
return false;
}
} else {
// compare first click to this click and see if they occurred within double click threshold
if (((new Date().getTime()) - touchtimee) < 800) {
window.location = this.href;
touchtimee = 0;
} else {
// not a double click so set as a new first click
touchtimee = new Date().getTime();
return false;
}
}
});
});
jQuery(document).ready(function($) {
for (var i = 0; i < 5; i++) {
carouseltopHtml[i] = jQuery("#carrou0" + i).html();
if (i > 0) {
jQuery("#carrou0" + i).html('');
}
//jQuery("#carrou_bottom_" + i ).css('display','none');
}
});
for (var j = 0; j < 5; j++) {
if (window.innerWidth < 1024) {
if (j == 2)
document.getElementById('top_nav_category_' + j).setAttribute("style", "width:100%; height: 50px; min-height: 50px; background-image: url(); margin-bottom:0px");
else
document.getElementById('top_nav_category_' + j).setAttribute("style", "width:80%; height: fit-content; min-height: 50px; background-image: url(); margin-bottom:0px");
document.getElementById('top_a_category_' + j).setAttribute("style", "display: contents; margin-top: 0px; text-align: center;");
}
}
function onmuseoverslider(id) {
for (var i = 0; i < 5; i++) {
if (id == i)
jQuery("#carrou0" + i).html(carouseltopHtml[i]);
//jQuery("#carrou_bottom_" + i ).css('display','block');
else
jQuery("#carrou0" + i).html('');
// jQuery("#carrou_bottom_" + i ).css('display','none');
}
loadtopslider(id + 1);
/*for(var i = 1; i < 6; i ++){
if(i == id)
document.getElementById('carrou0'+id).className += ' mostrar';
else
document.getElementById('carrou0'+i).className =document.getElementById('carrou0'+i).className.replace(/(?:^|\s)mostrar(?!\S)/g,'');
}*/
}
function loadtopslider(index) {
//jQuery( '.wcpscwc-product-slider' ).each(function( index ) {
var item = jQuery('.wcpscwc-product-slider')[0];
var slider_id = jQuery(item).attr('id');
var slider_conf = jQuery.parseJSON(jQuery(item).closest('.wcpscwc-product-slider-wrap').find('.wcpscwc-slider-conf').attr('data-conf'));
var slider_cls = slider_conf.slider_cls ? slider_conf.slider_cls : 'products';
jQuery('#' + slider_id + ' .' + slider_cls).not('.slick-initialized').slick({
dots: (slider_conf.dots) == "true" ? true : false,
infinite: true,
arrows: (slider_conf.arrows) == "true" ? true : false,
speed: parseInt(slider_conf.speed),
autoplay: (slider_conf.autoplay) == "true" ? true : false,
autoplaySpeed: parseInt(slider_conf.autoplay_speed),
slidesToShow: parseInt(slider_conf.slide_to_show),
slidesToScroll: parseInt(slider_conf.slide_to_scroll),
rtl: (slider_conf.rtl) == "true" ? true : false,
responsive: [{
breakpoint: 1023,
settings: {
slidesToShow: 3,
slidesToScroll: 1,
infinite: true,
dots: false
}
}, {
breakpoint: 767,
settings: {
slidesToShow: 2,
slidesToScroll: 1
}
},
{
breakpoint: 479,
settings: {
slidesToShow: 1,
slidesToScroll: 1,
dots: false
}
},
{
breakpoint: 319,
settings: {
slidesToShow: 1,
slidesToScroll: 1,
dots: false
}
}
]
});
//});
}
.btnstop:hover,
.btnstop:focus {
background-color: #ebebeb;
transform: scale(1.1);
box-shadow: 2px 1px 2px 2px rgba(0, 0, 0, 0.3);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="carouselcattop01">
<ul class="ulbtncatcar">
<li class="btncatcar01 btnstop" id="top_nav_category_0" onmouseover="onmuseoverslider(0)" style="width: 15%; height: 20%;">
<a href="/categorie-produit/les-rouges/" title="Vins Rouges" class="titre" title="Les vins rouges" id="top_a_category_0">
<h3 style="color: #000000; font-size: 2vw; margin-bottom: 0px; font-family: Prata; ">Vins</h3>
<h2 style="color: #025F6D; font-family: Montserrat; font-size: 1.5vw;"> Rouges</h2>
</a>
</li>
<li class="btncatcar02 btnstop" id="top_nav_category_1" onmouseover="onmuseoverslider(1)" style="width: 15%; height: 20%;">
<a href="/categorie-produit/les-roses/" title="Vins Rosés" class="titre" title="Les vins rosés" id="top_a_category_1">
<h3 style="color: #000000; font-size: 2vw; margin-bottom: 0px; font-family: Prata;">Vins</h3>
<h2 style="color: #0092A7; font-family: Montserrat; font-size: 1.5vw; margin-bottom: 0px;"> Rosés</h2>
</a>
</li>
<li class="btncatcar03 btnstop" id="top_nav_category_2" onmouseover="onmuseoverslider(2)" style="width: 15%; height: 20%;">
<a href="/categorie-produit/les-blanc-liquoreux-et-secs/" title="Vins Blancs Secs et Liquoreux" class="titre" title="Les vins blancs" id="top_a_category_2">
<h3 style="color: #000000; font-size: 2vw; margin-bottom: 0px; font-family: Prata; padding-top: 10px;">Vins</h3>
<h2 style="color: #0092A7; font-family: Montserrat; font-size: 1.5vw;"> Blancs</h2>
<h5 style="color: #0092A7; font-family: Montserrat; font-size: 1vw;"> Secs et Liquoreux</h5>
</a>
</li>
<li class="btncatcar04 btnstop" id="top_nav_category_3" onmouseover="onmuseoverslider(3)" style="width: 15%; height: 20%;">
<a href="/categorie-produit/les-bulles/" title="Vins Pétillants" class="titre" title="Les vins pétillants" id="top_a_category_3">
<h3 style="color: #000000; font-size: 2vw; margin-bottom: 0px; font-family: Prata;">Vins</h3>
<h2 style="color: #9BD0D9; font-family: Montserrat; font-size: 1.5vw;"> Pétillants</h2>
</a>
</li>
<li class="btncatcar05 btnstop" id="top_nav_category_4" onmouseover="onmuseoverslider(4)" style="width: 15%; height: 20%;">
<a href="/categorie-produit/idees-cadeaux/" title="Idées Cadeaux" class="titre" title="Les idées cadeaux" id="top_a_category_4">
<h3 style="color: #000000; font-size: 2vw; margin-bottom: 0px; font-family: Prata;">Idées</h3>
<h2 style="color: #B1B3B4; font-family: Montserrat; font-size: 1.5vw;"> Cadeaux</h2>
</a>
</li>
<ul id="carrou00" class="ulcarrousel ocultar mostrar">
<li class="licarrousel">
<div class="dudomaine">Les <strong>vins rouges</strong> du Domaine</div>
[products_slider cats="21" slide_to_show="5" design="design-5" dots="false" slide_to_scroll="2"]
</li>
</ul>
<ul id="carrou01" class="ulcarrousel ocultar mostrar">
<li class="licarrousel">
<div class="dudomaine">Les <strong>vins rosés</strong> du Domaine</div>
[products_slider cats="22" slide_to_show="5" design="design-5" dots="false" slide_to_scroll="2"]
</li>
</ul>
<ul id="carrou02" class="ulcarrousel ocultar mostrar">
<li class="licarrousel">
<div class="dudomaine">Les <strong>vins blancs</strong> du Domaine</div>
[products_slider cats="23" slide_to_show="5" design="design-5" dots="false" slide_to_scroll="2"]
</li>
</ul>
<ul id="carrou03" class="ulcarrousel ocultar mostrar">
<li class="licarrousel">
<div class="dudomaine">Les <strong>vins pétillants</strong> du Domaine</div>
[products_slider cats="24" slide_to_show="5" design="design-5" dots="false" slide_to_scroll="2"]
</li>
</ul>
<ul id="carrou04" class="ulcarrousel ocultar mostrar">
<li class="licarrousel">
<div class="dudomaine">Les <strong>idées cadeaux</strong> du Domaine</div>
[products_slider cats="25" slide_to_show="5" design="design-5" dots="false" slide_to_scroll="2"]
</li>
</ul>
</ul>
</div>

Related

canvasjs Charts takes too much time to render

through WebSocket fetching the data from The developers.binary but canvasjs is rendering to the charts taking too much time but I saw that a lot of charts all are rendering normally not taking much time. I want to know that why it happens
what should I do to render the charts quickly?
I need to visible the charts quickly
is it taking time to the API call or I've mistaken anything?
window.addEventListener('load', function(e) {
var ws, b, rnd, spot, time, dps, xd, digit, cnt, random, id, lng, str, chart, xVal, yVal, mType, mColor, rndMenu;
ws = new WebSocket("wss://ws.binaryws.com/websockets/v3?app_id=3738&l=" + lng);
str = ["R_100", "R_10", "R_25", "R_50", "R_75", "RDBEAR", "RDBULL"];
dps = [];
time = [0];
spot = [0];
digit = [0];
mType = "none";
mColor = "#32cd32";
lng = "EN";
xVal = 0;
yVal = 0;
cnt = 20;
rndMenu = document.querySelectorAll('div.menu > span');
function toggleDigit(d, m) {
var nameClass = document.querySelector("#digits > span:nth-child(" + d + ")").className;
if (nameClass != "digits_moved_" + m) {
document.querySelector("#digits > span:nth-child(" + d + ")").classList.remove(nameClass);
document.querySelector("#digits > span:nth-child(" + d + ")").classList.add("digits_moved_" + m);
}
}
function rndGet() {
random = document.querySelector("body > div.menu > span.menu-active").title;
rnd = "R_10";
xd = 3;
}
rndGet();
ws.onopen = function(evt) {
ws.send(JSON.stringify({
ticks: rnd
}));
};
ws.onmessage = function(msg) {
b = JSON.parse(msg.data);
if (b.tick) {
if (b.echo_req.ticks == rnd) {
id = b.tick.id;
ws.send(JSON.stringify({
ticks_history: rnd,
end: "latest",
start: 1,
style: "ticks",
count: cnt + 1
}));
} else {
ws.send(JSON.stringify({
forget: id
}));
ws.send(JSON.stringify({
forget_all: "ticks"
}));
ws.send(JSON.stringify({
ticks: rnd
}));
};
};
if (b.history) {
if (b.echo_req.ticks_history == rnd) {
for (var i = 0; i < cnt + 1; i++) {
time[i] = b.history.times[cnt - i];
spot[i] = b.history.prices[cnt - i];
spot[i] = Number(spot[i]).toFixed(xd);
digit[i] = spot[i].slice(-1);
}
for (var i = 0; i < cnt + 1; i++) {
xVal = new Date(time[i] * 1000);
yVal = parseFloat(spot[i]);
if (i == 0) mType = "circle";
else mType = "none";
if (yVal == Math.max.apply(null, spot)) {
mColor = "#29abe2";
mType = "circle";
} else if (yVal == Math.min.apply(null, spot)) {
mColor = "#c03";
mType = "circle";
} else {
mColor = "#32cd32";
}
dps.push({
x: xVal,
y: yVal,
markerType: mType,
markerColor: mColor,
markerBorderColor: "#ccc"
});
}
chart.render()
spot.reverse();
digit.reverse();
for (var i = 1; i < cnt + 1; i++) {
document.querySelector("#digits > span:nth-child(" + i + ")").innerHTML = digit[i];
if (spot[i - 1] < spot[i]) {
toggleDigit(i, "up");
} else if (spot[i - 1] > spot[i]) {
toggleDigit(i, "down");
} else if (spot[i - 1] == spot[i] && i - 1 > 0) {
if (document.querySelector("#digits > span:nth-child(" + (i - 1) + ")").className == "digits_moved_up") {
toggleDigit(i, "up");
} else if (document.querySelector("#digits > span:nth-child(" + (i - 1) + ")").className == "digits_moved_down") {
toggleDigit(i, "down");
}
}
}
};
};
};
chart = new CanvasJS.Chart("chartContainer", {
animationEnabled: false,
theme: "light2",
title: {
titleFontSize: 0,
text: ""
},
toolTip: {
enabled: true,
animationEnabled: true,
borderColor: "#ccc",
borderThickness: 1,
fontColor: "#000",
content: "{y}"
},
axisX: {
includeZero: false,
titleFontSize: 0,
labelFontSize: 0,
gridThickness: 0,
tickLength: 0,
lineThickness: 0
},
axisY: {
includeZero: false,
titleFontSize: 0,
labelFontSize: 0,
gridThickness: 0,
tickLength: 0,
lineThickness: 0
},
data: [{
type: "spline",
lineColor: "#ccc",
lineThickness: 2,
markerType: "none",
markerSize: 5,
markerBorderThickness: 0,
dataPoints: dps
}],
});
e.preventDefault()
}, false);
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Asim chart</title>
<style>
body {
margin: 0;
padding: 0 10px;
font-size: 16px;
text-align: center;
font-family: "Arial", sans-serif;
}
h1 {
font-size: 34px;
}
.menu {
margin-bottom: 16px;
display: flex;
}
.menu span {
padding: 3px 0;
flex-basis: auto;
flex-grow: 1;
text-align: center;
font-size: 16px;
border-radius: 5px;
color: #fff;
background-color: #666666;
}
.menu span:hover {
background: #191919;
}
span.menu-active {
background: #191919;
}
.digits {
margin-bottom: 20px;
display: flex;
}
.disclaimer {
font-size: 11px;
text-align: center;
font-family: "Arial", sans-serif;
color: #707070;
}
.digits span {
padding: 25px 0;
flex-basis: auto;
flex-grow: 1;
text-align: center;
font-size: 24px;
border-radius: 15px;
color: #fff;
}
.digits_moved_down {
background-color: #c03;
}
.digits_moved_up {
background-color: #29abe2;
}
.chartContainer {
min-height: 350px;
min-width: 50px;
}
</style>
<script type="text/javascript" src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<script type="text/javascript" src="script.js"></script>
</head>
<body class="EN">
<h1>charts</h1>
<h3>charts difference</h3>
<div class="menu">
<span class="" title="R_100">100</span>
<span class="menu-active" title="R_10">10</span>
<span class="" title="R_25">25</span>
<span class="" title="R_50">50</span>
<span class="" title="R_75">75</span>
<span class="" title="RDBEAR">ODD/EVEN</span>
<span class="" title="RDBULL">MATCH/DIFFERS</span>
</div>
<p>Charts might take up to 30 secs to load.. please wait...</p>
<div id="digits" class="digits">
<span class="_"></span>
<span class="_"></span>
<span class="_"></span>
<span class="_"></span>
<span class="_"></span>
<span class="_"></span>
<span class="_"></span>
<span class="_"></span>
<span class="_"></span>
<span class="_"></span>
<span class="_"></span>
<span class="_"></span>
<span class="_"></span>
<span class="_"></span>
<span class="_"></span>
<span class="_"></span>
<span class="_"></span>
<span class="_"></span>
<span class="_"></span>
<span class="_"></span>
</div>
<div class="chartContainer" id="chartContainer"></div>
<div class="disclaimer">
</div>
</body>
</html>
Chart is getting rendered within 20-30 milliseconds. However, API call & the response seems to be taking 3-5 secs. Below is the code showcasing the time taken:
window.addEventListener('load', function (e) {
var timeNow;
var ws, b, rnd, spot, time, dps, xd, digit, cnt, random, id, lng, str, chart, xVal, yVal, mType, mColor, rndMenu;
ws = new WebSocket("wss://ws.binaryws.com/websockets/v3?app_id=3738&l=" + lng);
str = ["R_100", "R_10", "R_25", "R_50", "R_75", "RDBEAR", "RDBULL"];
dps = [];
time = [0];
spot = [0];
digit = [0];
mType = "none";
mColor = "#32cd32";
lng = "EN";
xVal = 0;
yVal = 0;
cnt = 20;
rndMenu = document.querySelectorAll('div.menu > span');
function toggleDigit(d, m) {
var nameClass = document.querySelector("#digits > span:nth-child(" + d + ")").className;
if (nameClass != "digits_moved_" + m) {
document.querySelector("#digits > span:nth-child(" + d + ")").classList.remove(nameClass);
document.querySelector("#digits > span:nth-child(" + d + ")").classList.add("digits_moved_" + m);
}
}
function rndGet() {
random = document.querySelector("body > div.menu > span.menu-active").title;
rnd = "R_10";
xd = 3;
}
rndGet();
ws.onopen = function (evt) {
ws.send(JSON.stringify({
ticks: rnd
}));
};
ws.onmessage = function (msg) {
b = JSON.parse(msg.data);
if (b.tick) {
if (b.echo_req.ticks == rnd) {
id = b.tick.id;
ws.send(JSON.stringify({
ticks_history: rnd,
end: "latest",
start: 1,
style: "ticks",
count: cnt + 1
}));
} else {
ws.send(JSON.stringify({
forget: id
}));
ws.send(JSON.stringify({
forget_all: "ticks"
}));
ws.send(JSON.stringify({
ticks: rnd
}));
};
};
if (b.history) {
if (b.echo_req.ticks_history == rnd) {
for (var i = 0; i < cnt + 1; i++) {
time[i] = b.history.times[cnt - i];
spot[i] = b.history.prices[cnt - i];
spot[i] = Number(spot[i]).toFixed(xd);
digit[i] = spot[i].slice(-1);
}
for (var i = 0; i < cnt + 1; i++) {
xVal = new Date(time[i] * 1000);
yVal = parseFloat(spot[i]);
if (i == 0) mType = "circle";
else mType = "none";
if (yVal == Math.max.apply(null, spot)) {
mColor = "#29abe2";
mType = "circle";
} else if (yVal == Math.min.apply(null, spot)) {
mColor = "#c03";
mType = "circle";
} else {
mColor = "#32cd32";
}
dps.push({
x: xVal,
y: yVal,
markerType: mType,
markerColor: mColor,
markerBorderColor: "#ccc"
});
}
var startTime = new Date().getTime();
chart.render();
console.log("Chart rendered in: ", new Date().getTime() - startTime + "ms");
spot.reverse();
digit.reverse();
for (var i = 1; i < cnt + 1; i++) {
document.querySelector("#digits > span:nth-child(" + i + ")").innerHTML = digit[i];
if (spot[i - 1] < spot[i]) {
toggleDigit(i, "up");
} else if (spot[i - 1] > spot[i]) {
toggleDigit(i, "down");
} else if (spot[i - 1] == spot[i] && i - 1 > 0) {
if (document.querySelector("#digits > span:nth-child(" + (i - 1) + ")").className == "digits_moved_up") {
toggleDigit(i, "up");
} else if (document.querySelector("#digits > span:nth-child(" + (i - 1) + ")").className == "digits_moved_down") {
toggleDigit(i, "down");
}
}
}
};
};
};
chart = new CanvasJS.Chart("chartContainer", {
animationEnabled: false,
theme: "light2",
title: {
titleFontSize: 0,
text: ""
},
toolTip: {
enabled: true,
animationEnabled: true,
borderColor: "#ccc",
borderThickness: 1,
fontColor: "#000",
content: "{y}"
},
axisX: {
includeZero: false,
titleFontSize: 0,
labelFontSize: 0,
gridThickness: 0,
tickLength: 0,
lineThickness: 0
},
axisY: {
includeZero: false,
titleFontSize: 0,
labelFontSize: 0,
gridThickness: 0,
tickLength: 0,
lineThickness: 0
},
data: [{
type: "spline",
lineColor: "#ccc",
lineThickness: 2,
markerType: "none",
markerSize: 5,
markerBorderThickness: 0,
dataPoints: dps
}]
});
e.preventDefault()
}, false);
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Asim chart</title>
<style>
body {
margin: 0;
padding: 0 10px;
font-size: 16px;
text-align: center;
font-family: "Arial", sans-serif;
}
h1 {
font-size: 34px;
}
.menu {
margin-bottom: 16px;
display: flex;
}
.menu span {
padding: 3px 0;
flex-basis: auto;
flex-grow: 1;
text-align: center;
font-size: 16px;
border-radius: 5px;
color: #fff;
background-color: #666666;
}
.menu span:hover {
background: #191919;
}
span.menu-active {
background: #191919;
}
.digits {
margin-bottom: 20px;
display: flex;
}
.disclaimer {
font-size: 11px;
text-align: center;
font-family: "Arial", sans-serif;
color: #707070;
}
.digits span {
padding: 25px 0;
flex-basis: auto;
flex-grow: 1;
text-align: center;
font-size: 24px;
border-radius: 15px;
color: #fff;
}
.digits_moved_down {
background-color: #c03;
}
.digits_moved_up {
background-color: #29abe2;
}
.chartContainer {
min-height: 350px;
min-width: 50px;
}
</style>
<script type="text/javascript" src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<script type="text/javascript" src="script.js"></script>
</head>
<body class="EN">
<h1>charts</h1>
<h3>charts difference</h3>
<div class="menu">
<span class="" title="R_100">100</span>
<span class="menu-active" title="R_10">10</span>
<span class="" title="R_25">25</span>
<span class="" title="R_50">50</span>
<span class="" title="R_75">75</span>
<span class="" title="RDBEAR">ODD/EVEN</span>
<span class="" title="RDBULL">MATCH/DIFFERS</span>
</div>
<p>Charts might take up to 30 secs to load.. please wait...</p>
<div id="digits" class="digits">
<span class="_"></span>
<span class="_"></span>
<span class="_"></span>
<span class="_"></span>
<span class="_"></span>
<span class="_"></span>
<span class="_"></span>
<span class="_"></span>
<span class="_"></span>
<span class="_"></span>
<span class="_"></span>
<span class="_"></span>
<span class="_"></span>
<span class="_"></span>
<span class="_"></span>
<span class="_"></span>
<span class="_"></span>
<span class="_"></span>
<span class="_"></span>
<span class="_"></span>
</div>
<div class="chartContainer" id="chartContainer"></div>
<div class="disclaimer">
</div>
</body>
</html>

Auto Show and Div automatically after a set time in jQuery

I have divs that automatically cycle to the next div and show its contents after every few seconds. The functionality works fine however, there seems to be a gap when the last div hides and the first div is meant to show as the underline in the corresponding link for the div has a slight delay- it should change immediately. I can't figure out why this is happening. Also, I am trying execute the function 5 seconds after the page has loaded .delay(5000) does not seem to work. Below is the code:
var homeLinks = ['i-t', 'o-c', 'c-f', 'i-c', 'c-u'];
var currentLink = 0;
var hovered = false;
$(".home-link").hover(function() {
hovered = true;
$('.home-' + homeLinks[currentLink]).hide();
$('[data-hover=' + homeLinks[currentLink] + ']').toggleClass('default-underline');
currentLink = homeLinks.indexOf($(this).attr('data-hover'));
$('[data-hover=' + homeLinks[currentLink] + ']').toggleClass('default-underline');
$('.home-' + homeLinks[currentLink]).show();
}, function() {
hovered = false;
});
var autoNavInterval = setInterval(autoNav, 3000);
function autoNav() {
if (hovered === false) {
$('.home-' + homeLinks[currentLink]).hide();
$('[data-hover=' + homeLinks[currentLink] + ']').toggleClass('default-underline');
currentLink++;
if (currentLink >= homeLinks.length) {
currentLink = 0;
}
$('[data-hover=' + homeLinks[currentLink] + ']').toggleClass('default-underline');
$('.home-' + homeLinks[currentLink]).show();
}
}
.left-fill {
background: #0000006b;
height: 100vh;
}
.right-fill {
background: pink;
height: 100vh;
}
.vc_col-sm-6 {
width: 50%;
float: left;
}
.pivot-nav {
list-style: none;
font-family: 'Montserrat';
text-align: left;
}
.pivot-nav li a {
font-size: 1.6rem;
font-weight: 700;
text-transform: uppercase;
display: inline-block;
position: relative;
color: #fff;
text-decoration: none;
line-height: 40px;
}
.pivot-nav li a.default-underline::after,
.pivot-nav li a:hover::after {
width: 100%;
}
.pivot-nav:hover a.default-underline:not(:hover)::after {
width: 0;
}
.pivot-nav li a::after {
bottom: 0;
content: "";
display: block;
height: 4px;
position: absolute;
background: #fff;
transition: width 0.3s ease 0s;
width: 0;
}
.home-o-c,
.home-c-f,
.home-i-c,
.home-c-u {
display: none;
}
.our-company {
clear: both;
display: block;
height: 50vh;
}
.cf2 {
clear: both;
display: block;
height: 50vh;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="left-fill text-left wpb_column vc_column_container vc_col-sm-6">
<div class="wpb_wrapper">
<p class="home-i-t">TEXT One</p>
<p class="home-o-c">TEXT One</p>
<p class="home-c-f">TExt for C f.</p>
<p class="home-i-c">Some more text fo i c.</p>
<p class="home-c-u">Get in touch </p>
</div>
</div>
<div class="home-fill right-fill text-right wpb_column vc_column_container vc_col-sm-6">
<div class="wpb_wrapper">
<ul class="pivot-nav">
<li class="pivot-nav-item"><a data-hover="o-c" class="home-link" href="#" data-toggle="my-scrollspy-2">O C</a></li>
<li class="pivot-nav-item"><a data-hover="c-f" class="home-link" href="#" data-toggle="my-scrollspy-2">C F</a></li>
<li class="pivot-nav-item"><a data-hover="i-c" class="home-link" href="#" data-toggle="my-scrollspy-2">I C</a></li>
<li class="pivot-nav-item" data-toggle="my-scrollspy-2"><a data-hover="c-u" class="home-link" href="#">C U</a></li>
</ul>
</div>
</div>
To start function 5 secounds after the page was loaded first you need to be sure that your script starts working after the document is ready. Use the basic jQuery function $(function () { /* code executed after the document loaded */ } );.
Than use simple javaScript function setTimeout.
The underline switched between C U and O C longer because you set the currentLink value to 0 after you iterate through every element in the array homeLinks and the 0 element would be an a with data-hover="i-t" which doesn't exist. You can remove the first string from the array or create an element in the list or set the currentLink value to 1 after you reach the homeLinks value with currentLink.
I fixed your script code to do exactly what you described with as few changes as possible:
$(function () {
var homeLinks = ['i-t', 'o-c', 'c-f', 'i-c', 'c-u'];
var currentLink = 0;
var hovered = false;
$(".home-link").hover(function () {
hovered = true;
$('.home-' + homeLinks[currentLink]).hide();
$('[data-hover=' + homeLinks[currentLink] + ']').toggleClass('default-underline');
currentLink = homeLinks.indexOf($(this).attr('data-hover'));
$('[data-hover=' + homeLinks[currentLink] + ']').toggleClass('default-underline');
$('.home-' + homeLinks[currentLink]).show();
}, function (event) {
hovered = false;
currentLink = 0;
$('.wpb_wrapper p').hide();
$(event.target).toggleClass('default-underline');
});
setTimeout(() => {
var autoNavInterval = setInterval(autoNav, 1000);
}, 1000);
function autoNav() {
if (hovered === false) {
$('.home-' + homeLinks[currentLink]).hide();
$('[data-hover=' + homeLinks[currentLink] + ']').toggleClass('default-underline');
currentLink++;
if (currentLink >= homeLinks.length) {
currentLink = 1;
}
$('[data-hover=' + homeLinks[currentLink] + ']').toggleClass('default-underline');
$('.home-' + homeLinks[currentLink]).show();
}
else {
}
}
});

Make navigation clickable in fullpage script

I have a simple project based on one variation of fullpage script. Everything works perfect except for one annoying thing - I can't understand how to make my right navigation bullets clickable (to an appropriate section). My js knowledge is not too good at the moment so I'd really appreciate any help, guys. Thanks!
$.fullPage = function(option) {
var defaultOpt = {
box: "#fullPageBox", // 滚屏页父元素
page: ".fullPage", // 滚屏页面
index: true, // 是否显示索引
duration: 1000, // 动画时间
direction: "vertical", // 滚屏方向 horizontal or vertical
loop: true // 是否循环
},
This = this,
index = 0,
over = true;
this.option = $.extend({}, defaultOpt, option || {});
this.box = $(this.option.box);
this.pages = $(this.option.page);
this.duration = this.option.duration;
// 绑定鼠标滚轮事件
$(document).on("mousewheel DOMMouseScroll", function(ev) {
var dir = ev.originalEvent.wheelDelta || -ev.originalEvent.detail;
if (over === false) return;
dir < 0 ? nextPage() : prevPage();
});
if (this.option.index) {
initPagination();
};
function initPagination() {
var oUl = $("<ul id='fullPageIndex'></ul>"),
liStr = "";
for (var i = 0, len = This.pages.length; i < len; i++) {
liStr += "<li></li>";
};
$(document.body).append(oUl.append($(liStr)));
$("#fullPageIndex li").eq(index).addClass("active").siblings().removeClass("active");
};
function nextPage() {
if (index < This.pages.length - 1) {
index++;
} else {
index = 0;
}
scrollPage(index, This.pages.eq(index).position());
};
function prevPage() {
if (index === 0) {
index = This.pages.length - 1;
} else {
index--;
}
scrollPage(index, This.pages.eq(index).position());
};
function scrollPage(index, position) {
over = false;
var cssStr = This.option.direction === "vertical" ? {
top: -position.top
} : {
left: -position.left
};
This.box.animate(cssStr, This.duration, function() {
over = true;
})
$("#fullPageIndex li").eq(index).addClass("active").siblings().removeClass("active");
};
}
* {
margin: 0;
padding: 0;
}
html,
body {
height: 100%;
overflow: hidden;
}
.pageBox {
position: relative;
height: 100%;
}
.main {
width: 100%;
height: 500%;
min-width: 1200px;
position: absolute;
left: 0;
top: 0;
color: #fff;
}
.main .fullPage {
height: 25%;
}
.bg1 {
background-color: #27AE60;
}
.bg2 {
background-color: #3498DB;
}
.bg3 {
background-color: #C0392B;
}
.bg4 {
background-color: #4FC2E5;
}
.bg5 {
background-color: #8E44AD;
}
#fullPageIndex {
position: absolute;
top: 50%;
right: 20px;
transform: translateY(-50%);
}
#fullPageIndex li {
width: 10px;
height: 10px;
list-style: none;
background-color: black;
margin: 6px 0;
border-radius: 50%;
}
#fullPageIndex li.active {
background-color: white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<div class="pageBox">
<div class="main" id="fullPageBox">
<div class="fullPage bg1">jQuery fullPage.js</div>
<div class="fullPage bg2">Section 2</div>
<div class="fullPage bg3">Section 3</div>
<div class="fullPage bg4">Section 4</div>
<div class="fullPage bg5">Section 5</div>
</div>
</div>
<script>
$.fullPage();
</script>
</body>
Add an id attribute to you divs and add an anchor to the list elements that navigate to the desired sections. As follows:
<body>
<div class="pageBox">
<div class="main" id="fullPageBox">
<div id="section1" class="fullPage bg1">jQuery fullPage.js</div>
<div id="section2" class="fullPage bg2">Section 2</div>
<div id="section3" class="fullPage bg3">Section 3</div>
<div id="section4" class="fullPage bg4">Section 4</div>
<div id="section5" class="fullPage bg5">Section 5</div>
</div>
</div>
<script>
$.fullPage();
</script>
</body>
Update your js where you render the list items to look like this:
function initPagination() {
var oUl = $("<ul id='fullPageIndex'></ul>"),
liStr = "";
for (var i = 0, len = This.pages.length; i <= len; i++) {
var sectionNum = i + 1;
liStr += '<li></li>';
};
$(document.body).append(oUl.append($(liStr)));
$("#fullPageIndex li").eq(index).addClass("active").siblings().removeClass("active");
};
Read more here
EDIT:
Since you asked for a smooth scroll as well you could add this to your JS:
$('a[href*=#]:not([href=#])').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'')
|| location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top
}, 1000);
return false;
}
}
});
Source for the snippet can be found on this page.
there is some mistake in your script.
First, remove below code from your HTML file:
<script>
fullPage();
</script>
Second is, you've created wrong function (method) define. I'am replace $.fullpage = function(option) { with var fullpage = function(options) {
and for the last is: since we have removed your fullpage() initiator, so we need to call this method again. for example at end line of your JS file,
P.S:
In Javascript you can create function in several ways. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions for more detail.
See fixed code below:
var fullPage = function(option) {
var defaultOpt = {
box: "#fullPageBox", // 滚屏页父元素
page: ".fullPage", // 滚屏页面
index: true, // 是否显示索引
duration: 1000, // 动画时间
direction: "vertical", // 滚屏方向 horizontal or vertical
loop: true // 是否循环
},
This = this,
index = 0,
over = true;
this.option = $.extend({}, defaultOpt, option || {});
this.box = $(this.option.box);
this.pages = $(this.option.page);
this.duration = this.option.duration;
// 绑定鼠标滚轮事件
$(document).on("mousewheel DOMMouseScroll", function(ev) {
var dir = ev.originalEvent.wheelDelta || -ev.originalEvent.detail;
if (over === false) return;
dir < 0 ? nextPage() : prevPage();
});
if (this.option.index) {
initPagination();
};
function initPagination() {
var oUl = $("<ul id='fullPageIndex'></ul>"),
liStr = "";
for (var i = 0, len = This.pages.length; i < len; i++) {
liStr += "<li></li>";
};
$(document.body).append(oUl.append($(liStr)));
$("#fullPageIndex li").eq(index).addClass("active").siblings().removeClass("active");
};
function nextPage() {
if (index < This.pages.length - 1) {
index++;
} else {
index = 0;
}
scrollPage(index, This.pages.eq(index).position());
};
function prevPage() {
if (index === 0) {
index = This.pages.length - 1;
} else {
index--;
}
scrollPage(index, This.pages.eq(index).position());
};
function scrollPage(index, position) {
over = false;
var cssStr = This.option.direction === "vertical" ? {
top: -position.top
} : {
left: -position.left
};
This.box.animate(cssStr, This.duration, function() {
over = true;
})
$("#fullPageIndex li").eq(index).addClass("active").siblings().removeClass("active");
};
}
fullPage();
* {
margin: 0;
padding: 0;
}
html,
body {
height: 100%;
overflow: hidden;
}
.pageBox {
position: relative;
height: 100%;
}
.main {
width: 100%;
height: 500%;
min-width: 1200px;
position: absolute;
left: 0;
top: 0;
color: #fff;
}
.main .fullPage {
height: 25%;
}
.bg1 {
background-color: #27AE60;
}
.bg2 {
background-color: #3498DB;
}
.bg3 {
background-color: #C0392B;
}
.bg4 {
background-color: #4FC2E5;
}
.bg5 {
background-color: #8E44AD;
}
#fullPageIndex {
position: absolute;
top: 50%;
right: 20px;
transform: translateY(-50%);
}
#fullPageIndex li {
width: 10px;
height: 10px;
list-style: none;
background-color: black;
margin: 6px 0;
border-radius: 50%;
}
#fullPageIndex li.active {
background-color: white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<body>
<div class="pageBox">
<div class="main" id="fullPageBox">
<div class="fullPage bg1">jQuery fullPage.js</div>
<div class="fullPage bg2">Section 2</div>
<div class="fullPage bg3">Section 3</div>
<div class="fullPage bg4">Section 4</div>
<div class="fullPage bg5">Section 5</div>
</div>
</div>
</body>

floating label dropdown not working

Im creating a floating label , i manage to make a floating label on textbox but
in my dropdown it doesn't work. hope you can help me.
/** GLOBAL OBJECT **/
var $ = {
addClass: function(elem, name) {
var classes = elem.className.split(' '),
cIndex = classes.indexOf(name);
if (cIndex === -1) {
classes.push(name);
}
elem.className = classes.join(' ');
return this;
}, // END addClass
removeClass: function(elem, name) {
var classes = elem.className.split(' '),
cIndex = undefined;
function recursive() {
// use a recursive function to remove all instances
// of the class name
cIndex = classes.indexOf(name);
if (cIndex >= 0) {
classes.splice(cIndex, 1);
recursive();
}
}
recursive();
elem.className = classes.join(' ');
return this;
}, // END removeClass
hasClass: function(elem, name) {
var classes = elem.className.split(' '),
cIndex = classes.indexOf(name);
if (cIndex >= 0) {
return true;
} else {
return false;
}
}, // END hasClass
selectCreate: function(select, label) {
var _this = this;
id = '_' + select.id,
input = document.createElement('input'),
div = document.createElement('div'),
ul = document.createElement('ul'),
val = {
value: select.value,
text: select.options[select.selectedIndex].text
};
select.style.display = 'none';
ul.id = 'ul' + id;
ul.className = 'ddown-list';
ul.setAttribute('aria-live', 'polite');
input.setAttribute('type', 'text');
input.setAttribute('aria-autocomplete', 'list');
input.setAttribute('aria-haspopup', 'true');
input.setAttribute('aria-owns', ul.id);
input.className = 'dynamic-dropdown';
input.id = id;
if (select.getAttribute('data-required') === 'true') {
input.setAttribute('required', 'true');
}
label.setAttribute('for', id);
div.className = 'selectRegion';
div.appendChild(label);
div.appendChild(input);
div.appendChild(ul);
select.parentNode.insertBefore(div, select);
input.value = val.text;
if (input.value !== '') {
this.addClass(label, 'active');
} else {
this.addClass(label, 'inactive');
}
input.addEventListener('focus', function() {
_this.addClass(label, 'active')
.addClass(label, 'transition')
.removeClass(label, 'inactive');
if (this.setSelectionRange) {
this.setSelectionRange(0, this.value.length);
}
populateList(this, select, document.getElementById('ul' + this.id), -1, true);
}); // END focus
input.addEventListener('blur', function() {
var input = this;
setTimeout(function() {
if (input.value === '') {
_this.addClass(label, 'inactive')
.addClass(label, 'transition')
.removeClass(label, 'active');
} else {
var list = getList(input.value, select, false);
select.value = list.value[0];
input.value = list.text[0];
}
document.getElementById('ul' + input.id).innerHTML = '';
}, 250);
}); // END blur
input.addEventListener('keyup', function(e) {
var list = document.getElementById('ul' + this.id).getElementsByTagName('li'),
index = -1,
kC = e.keyCode;
for (var i = 0, x = list.length; i < x; i++) {
if (_this.hasClass(list[i], 'active')) {
index = i;
break;
}
}
if (kC !== 9 && kC !== 16) { // SHIFT && TAB
if (kC === 13) { // ENTER
var list = getList(this.value, select, false);
select.value = list.value[index];
this.value = list.text[index];
document.getElementById('ul' + this.id).innerHTML = '';
} else {
switch (kC) {
case 38: // ARROW UP
index--;
if (index < 0) {
index = 0;
}
break;
case 40: // ARROW DOWN
index++;
if (index >= list.length) {
index = list.length - 1;
}
break;
default:
index = -1;
break;
}
populateList(this, select, document.getElementById('ul' + this.id), index, false);
}
}
}); // END keyup
function populateList(input, select, target, index, focus) {
var list = getList(input.value, select, focus),
counter = 0,
output;
if (focus) {
index = select.selectedIndex - 1;
}
target.innerHTML = '';
for (var i = 0, x = list.value.length; i < x; i++) {
output = document.createElement('li');
if (counter === index) {
output.className = 'active';
}
output.appendChild(document.createTextNode(list.text[i]));
output.addEventListener('click', function() {
console.log('test');
input.value = this.innerHTML;
});
target.appendChild(output);
counter++;
}
if (index >= 0) {
var lis = target.getElementsByTagName('li'),
sTop = 0;
for (var i = 0, x = lis.length; i < x; i++) {
if (i >= index) {
break;
}
sTop += lis[i].clientHeight;
}
target.scrollTop = sTop;
}
} // END populateList
function getList(val, list, focus) {
var value = [],
text = [],
vLength = val.length;
if (focus) {
vLength = 0;
val = '';
}
for (var i = 0, x = list.length; i < x; i++) {
if (list[i].text !== '' &&
(list[i].text.toUpperCase().substring(0, vLength) === val.toUpperCase() ||
list[i].value.toUpperCase().substring(0, vLength) === val.toUpperCase())) {
value.push(list[i].value);
text.push(list[i].text);
}
}
return {
value: value,
text: text
};
} // END function getList
}, // END selectCreate()
}; // END $
window.onload = function() {
var labels = document.getElementsByTagName('label'),
id = '',
label = undefined,
input = undefined,
type = undefined;
for (var i = 0, x = labels.length; i < x; i++) {
label = labels[i];
id = label.getAttribute('for') || '';
input = document.getElementById(id);
if (input) {
type = input.getAttribute('type') || input.tagName;
type = type.toLowerCase();
if (input && (type === 'select')) {
$.selectCreate(input, label);
} // END if( input && select )
}
} // END for( labels )
}();
var demo = function() {
setTimeout(function() {
document.getElementById('_s').focus();
setTimeout(function() {
document.getElementById('_s').blur();
}, 750);
}, 500);
}();
body {
background-color: #F7F7F7;
font-family: Arial;
padding-top: 10%;
}
input,
label,
select {
width: 280px;
padding: 10px;
font-size: 16px;
}
input {
border: solid 1px #CCCCCC;
border: none;
overflow: visible;
outline: none;
background-color: transparent;
border-bottom: solid 1px #999;
}
label {
position: absolute;
}
label.active {
color: #3784BB;
margin-top: -20px;
font-size: 12px;
}
label.inactive {
color: #999999;
}
li.active {
background-color: rgba( 255, 0, 0, 0.1);
}
.transition {
transition: all linear 0.1s;
}
.input {
width: 300px;
margin: auto;
}
.input:first-child {
margin-bottom: 5%
}
.selectRegion {
width: 100%;
}
.selectRegion ul {
margin: 0;
padding: 0;
position: absolute;
width: 300px;
max-height: 200px;
overflow: auto;
box-shadow: 0 2px 3px rgba( 0, 0, 0, 0.1);
background-color: #FFFFFF;
z-index: 2;
}
.selectRegion ul li {
padding: 10px;
}
.selectRegion ul li:hover {
cursor: pointer;
}
.inputbox {
position: relative;
background: none;
margin-right: 50px;
}
.inputbox input {
width: 120%;
padding: 10px 0;
font-size: 19px;
color: #21a1e;
margin-bottom: 50px;
overflow: visible;
outline: none;
background-color: transparent;
border: none;
border-bottom: solid 1px #999;
margin-left: -10px;
margin-top: -15px;
}
.inputbox label {
display: block;
position: absolute;
top: 0;
left: 0;
padding: 10px 0;
font-size: 16px;
color: #999;
pointer-events: none;
transition: top 0.7s ease, opacity 0.7s ease;
border-radius: .25rem;
margin-left: -10px;
margin-top: -10px;
}
.inputbox input:focus+label,
.inputbox input:valid+label {
top: -18px;
left: 0;
color: #4285f4;
font-size: 12px;
cursor: pointer;
}
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
</head>
<body>
<div class="col-sm-5">
<button type="button" class="button2 " data-toggle="modal" data-target="#exampleModal1">Login</button>
</div>
<div class="modal fade" id="exampleModal1" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg " role="document">
<div class="modal-content">
<div class="modal-header ">
<h5 class="modal-title" id="exampleModalLabel" style=" color: #404E67;">Form</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form>
<div class="form-row ">
<div class="inputbox">
<input type="text" required>
<label>First Name </label>
</div>
<div class="inputbox">
<input type="text" required>
<label>Last Name</label>
</div>
</div>
<div class="form-row">
<div class="input">
<label for="s">Sample 1:</label>
<select id="s">
<option value=""></option>
<option value="1">Assignment</option>
<option value="2">Reading</option>
</select>
</div>
</div>
<div class="clear"></div>
<div class="input">
<label for="state">Sample 2</label>
<select id="state">
<option value=""></option>
<option value="AL">Alabama</option>
<option value="AK">Alaska</option>
</select>
</div>
</form>
</div>
</div>
</body>
</html>
here is my current output:
As you can see on my output the two dropdown is not working any idea how ca i make it a floating label like at my textbox?

Allow user to drop item in two different droppable areas inside loop

So I do have a loop of droppable areas where user is able to drop items. Size of the loop can be different. It depends on user's input. You can check fiddle here
Here is my droppable area:
$(".projLeader ol").droppable({
tolerance: 'pointer',
hoverClass: 'highlight',
drop: function(ev, ui)
{
var zz = ui.draggable.text()
var xyz = itm.includes(zz);
if (xyz === false)
{
var item = ui.draggable;
if (!ui.draggable.closest('.placeholder').length) item = item.clone().draggable();// if item was dragged from the source list - clone it
//this.innerHTML = ''; // clean the placeholder
item.addClass('dropClass').appendTo(this);
// append item to placeholder
//add to array
itm.push(zz);
var n = $(this).closest("div.proc").find(".dropClass").length;
$(this).closest("div.proc").find("h6").text("Items Dropped: " + n + ".");
}
else
{
alert('Name is Already Exist');
}
}
});
The problem is I got warning message for each field. For example if I drop item in box1 and then want to drop same item in box2 I got warning message. How can I fix it? Thanks for any help
I spent some time understanding your code and here's the solution. I added some code to detect if an existing box already exists.Hope it helps :)!
var itm = [];
$( "#savebutton" ).click(function() { LISTOBJ.saveList(); });
$("#myAccordion").accordion({heightStyle:"content", active: false, collapsible:true});
$("#myAccordion li").draggable({
appendTo: "body",
helper: "clone",
start: function(ev, ui){ ui.helper.width($(this).width()); }
});
$(".projLeader ol").droppable({
tolerance: 'pointer',
hoverClass: 'highlight',
drop: function(ev, ui)
{
var zz = ui.draggable.text()
var xyz = itm.includes(zz);
if (xyz === false)
{
var item = ui.draggable;
var map = {}, i , size;
var flag = false;
if (!ui.draggable.closest('.placeholder').length){
item = item.clone().draggable();// if item was dragged from the source list - clone it
//this.innerHTML = ''; // clean the placeholder
item.addClass('dropClass').appendTo(this);
// append item to placeholder
//add to array
var n = $(this).closest("div.proc").find(".dropClass").length;
$(this).closest("div.proc").find("h6").text("Items Dropped: " + n + ".");
var listOfElements = $(this).closest("div.proc").find("li").text();
var newarr = listOfElements.split('x');
newarr.shift();
var actualArrayLength = newarr.length;
for (i = 0, size = newarr.length; i < size; i++){
if (map[newarr[i]]){
xyz = true;
alert("Name is Already Exist");
$(this).closest("div.proc").find("h6").text("Items Dropped: " + (n - 1) + ".");
$(this).closest("div.proc").find("li:last-child").remove();
return false;
}
else{
map[newarr[i]] = true;
newarr[newarr.length - 1];
}
}
}
}
}
});
$(".projLeader").on('click', '.closer', function(){
var item = $(this).closest('.item');
itm.splice(item);
item.fadeTo(200, 0, function(){ item.remove(); })
});
var LISTOBJ = {
saveList: function() {
var listCSV = "";
$( ".projLeader li" ).each(function() {
if (listCSV === "") {
listCSV = $(this).text();
} else {
listCSV += ", " + $(this).text();
}
$("#output").text(listCSV);
$(".hiddenListInput").val(listCSV);
});
}
}
body {
font-family: verdana;
font-size: 12px;
}
ul {
list-style-type: none;
margin: 0;
padding: 0;
margin-bottom: 10px;
}
ol{list-style-type: none;}
.item { height:20px; width: 180px; margin:5px; padding:5px; border:1px solid gray; background-color: #cd8; position: relative; }
.item .closer { position: absolute; right: 5px; top: 2px; font: bold 14px arial; color: #666; padding: 1px 3px; line-height: 1; cursor: pointer; display: none;}
.item .closer:hover { color: #000; }
.placeholder { height: 30px; width: 195px; margin: 5px; background: #eee; border: 1px dashed #999; }
.placeholder .item { margin: 0; }
ol .item .closer { display: block; }
.highlight { border: 1px solid red; background: #fff; }
.highlight .item { opacity: 0.3; }
.ui-draggable-dragging { z-index: 99; opacity: 1 !important; }
.dropClass {
background-color: lightblue;
padding-left: 10px;
width: 180px;
border: 1px solid black;
border-radius: 8px;
margin-bottom: 5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<h1 class="ui-widget-header">Products</h1>
<div id="myAccordion">
<h3>T-Shirts</h3>
<div>
<ul>
<li class="item"><span class="closer">x</span>Lolcat Shirt</li>
<li class="item"><span class="closer">x</span>Cheezeburger Shirt</li>
<li class="item"><span class="closer">x</span>Buckit Shirt</li>
</ul>
</div>
<h3>Bags</h3>
<div>
<ul>
<li class="item"><span class="closer">x</span>Zebra Striped</li>
<li class="item"><span class="closer">x</span>Black Leather</li>
<li class="item"><span class="closer">x</span>Alligator Leather</li>
</ul>
</div>
<h3>Gadgets</h3>
<div>
<ul>
<li class="item"><span class="closer">x</span>iPhone</li>
<li class="item"><span class="closer">x</span>iPod</li>
<li class="item"><span class="closer">x</span>iPad</li>
</ul>
</div>
</div>
<div class='proc'><pre>
<h6> </h6><br /></pre>
<div class="projLeader">
<label>Box1:</label>
<div class="ui-widget-content">
<ol id = "ID1">
<li class="placeholder" name="projLeader"></li>
<input type="hidden" name="projLeader" class="hiddenListInput1" />
</ol>
</div>
</div>
</div>
<div class='proc'><pre>
<h6> </h6><br /></pre>
<div class="projLeader">
<label>Box2:</label>
<div class="ui-widget-content">
<ol id = "ID2" >
<li class="placeholder" name="projLeader"></li>
<input type="hidden" name="projLeader" class="hiddenListInput2" />
</ol>
</div>
</div>
</div>
<br/>
<input type="submit" id="savebutton" class="button" value="Save" onclick="userSubmitted = true;" />
<div id="output"></div>

Categories

Resources