.Width() & .clientWidth get same bad info - javascript

I'm trying to Gsap a Horizontal scrolling text, but when I want to receive the width of the div element for check it's width (depending on a dynamic .txt file) It returns me a wrong width.
Sometimes when I refresh the page (brackets) it gives me the good width but when I refresh again always become wrong again!
Only when I let the page refresh without looking active window, and check it after a sec from being auto-refreshed it bring the exact value.
Code:
<!DOCTYPE html>
<html>
<head>
<style>
#font-face {
font-family: aclonica;
src: url(./fonts/Aclonica-Regular.ttf);
}
div {
display: inline-block;
position: relative;
font-family: aclonica;
}
div.hijos{
white-space: nowrap;
display: inline-block;
text-align: right;
vertical-align: bottom;
background-color: lightblue;
left: 160px;
width: 300px;
height: 50px;
overflow: hidden;
}
div.Titulos {
display: block;
left: 160px;
width: 300px;
height: 25px;
}
.nombres {
padding-top: 2px;
}
.dinero {
padding-top: 2px;
color: #53a9ea;
}
.Titulos{
margin-top: 2px;
margin-bottom: 2px;
text-align: right;
vertical-align: middle;
color: #53a9ea;
font-family: aclonica;
font-size: 24px;
text-shadow: 0px 0px 3px rgba(0, 0, 0, 1),1px 1px 5px rgba(0, 0, 0, 1), 0px 0px 4px rgba(0, 0, 0, 1), 0px 0px 4px rgba(0, 0, 0, 0.5);
}
.hijos{
display: block;
text-align: right;
color: #ffffff;
font-family: aclonica;
font-size: 22px;
text-shadow: 0px 0px 3px rgba(0, 0, 0, 1),1px 1px 5px rgba(0, 0, 0, 1), 0px 0px 4px rgba(0, 0, 0, 1), 0px 0px 4px rgba(0, 0, 0, 0.5);
}
.info{
padding-top: 2px;
}
span {
line-height: 100%;
display: inline-block;
}
#Top1{
display: block;
white-space: nowrap;
position: relative;
background-color:blue;
}
.NoWrap {
white-space: normal;
}
#Tinfo{
padding-left: 5px;
padding-right: 25px;
}
#Tinfo2{
padding-left: 5px;
padding-right: 25px;
}
#Sline{
line-height: 200%;
}
.Inline{
display: inline-block;
vertical-align:top;
}
#Inside1{
position: relative;
display:inline-block;
background-color: chocolate;
}
#Inside2{
position: relative;
display:inline-block;
background-color:chartreuse;
}
#TDonator{
display: block;
}
</style>
<script src="js/jquery.js"></script>
<script src="js/TimelineLite.min.js"></script>
<script src="js/TimelineMax.min.js"></script>
<script src="js/TweenMax.min.js"></script>
<script type="text/JavaScript">
setTimeout("location.href = 'TwitchAlerts.html';",30000);
</script>
</head>
<body bgcolor="#E6E6FA">
<div id="5Don" class="Titulos" >Last 5 Donators</div>
<div id="Donators" class="hijos"></div>
<div id="LastF" class="Titulos" >Last Follow</div>
<div id="Follower" class="hijos" class="NoWrap"></div>
<div id="TopDonator" class="Titulos" >Top Donator</div>
<div id="TDonator" class="hijos"></div>
<div id="salida1" ><h1></h1></div>
<div id="salida2" >holaaaaa</div>
<div id="salida3" ></div>
<script>
function hola(){
$("#Follower").load("../StreamLabs/most_recent_follower.txt");
$("#Donators").load("../StreamLabs/session_donators.txt");
$("#TDonator").load("../StreamLabs/all_time_top_donator.txt");
}
hola();
function animation(){
//var width1 = $Inside1.width();
var tl = new TimelineMax();
tl.staggerFrom(".Titulos", 0.5, {left:400, autoAlphalpha:0, ease: Back.easeOut.config(1.7)},0.25);
//.from("#Inside1", 5, {left:500, autoAlphalpha:0, ease: Linear.easeNone},0.25);
var $hold = $("#Inside1");
var $holdclone = $("#Inside2");
var listWidth = $("#Inside1").width();
//var listWidth = 253.36; //Real Value//
//listWidth = document.getElementById("Inside1").offsetWidth;;
document.getElementById("salida1").innerHTML = listWidth;
var salida2 = document.getElementById("Tname").offsetWidth;
//var salida2 = " uno "
document.getElementById("salida2").innerHTML = "hola a todos si "+salida2;
var infinite = new TimelineMax({repeat: -1, paused: false});
var time = 10;
infinite.fromTo($hold, time, {left:0}, {left: -listWidth, ease: Linear.easeNone}, 1);
infinite.fromTo($holdclone, time, {left:0}, {left:-listWidth, ease: Linear.easeNone}, 1);
infinite.fromTo($hold, time, {left:0}, {left: -250, ease: Linear.easeNone}, 11);
infinite.fromTo($holdclone, time, {left:0}, {left: -250, ease: Linear.easeNone}, 11);
//infinite.set($hold, {left: 50});
//infinite.to($holdclone, time, {left: -listWidth, ease: Linear.easeNone}, time);
//infinite.to($hold, time, {left: 0, ease: Linear.easeNone}, time);
}
$(document).ready(function(){
var str = document.getElementById("Donators").innerHTML;
var res = str.split(" ");
document.getElementById("Donators").innerHTML ="";
for (i = 1; i < res.length; i+=2) {
document.getElementById("Donators").innerHTML += '<span class="nombres">'+res[i-1] +'</span>';
document.getElementById("Donators").innerHTML += ' <span class="dinero">'+res[i] +' </span> ';
}
var str2 = document.getElementById("TDonator").innerHTML;
var res2 = str2.split(" ");
document.getElementById("TDonator").innerHTML ="";
document.getElementById("TDonator").innerHTML += '<div id="Top1"><div id="Inside1" ><div class="info2 nombres" id="Tname" >'+res2[0] +' </div><div class="info2 dinero" id="Tinfo">'+res2[1] +'</div></div></div>';
$('<div id="Inside2"><div class="info2 nombres" id="Tname2" >'+"hola" +' </div><div class="info2 dinero" id="Tinfo2"> '+"res2[1]" +'</div></div>').insertAfter("#Inside1");
var str3 = document.getElementById("Follower").innerHTML;
document.getElementById("Follower").innerHTML = '<span class="info" id="Fline">'+str3 +' </span><br><span class="info" id="Sline">'+str3+'</span>';
animation();
});
</script>

Related

Show the data and loader inside carousel

Before appending the loader to my page carousel works fine. But after adding loader to my page data not appending in the carousel. It appends after carousel. I want to show data inside carousel. I have tried but have not been able to figure out the problems. In this code, I am not fetching the data from the server but I have hard-coded data which is showing using local storage.
let movieData = JSON.parse(localStorage.getItem("movies"));
//console.log(movieData)
function sortLH() {
let data = JSON.parse(localStorage.getItem('movies'));
sort_data = data.sort(function(a, b) {
return a.rating - b.rating;
});
displayDOM(sort_data);
console.log(sort_data);
}
function sortHL() {
let data = JSON.parse(localStorage.getItem('movies'));
sort_data = data.sort(function(a, b) {
return b.rating - a.rating;
});
displayDOM(sort_data);
}
function displayDOM(data) {
let parent = document.querySelector('.carousel');
parent.innerHTML = null;
data.forEach(function(el) {
let container = document.createElement("div");
container.className = "carousel-cell";
let poster = document.createElement("img");
poster.src = el.poster;
let name = document.createElement("p");
name.innerText = `Movie: ${el.name}`;
let release = document.createElement("p");
release.innerText = `Year: ${el.release_Date}`;
let rating = document.createElement("p");
rating.innerText = `Rating: ${el.rating}`;
container.append(poster, name, release, rating)
parent.append(container);
});
}
////Loader/////
getme_dataPromise = new Promise(function(resolve, reject) {
setTimeout(function() {
let data = movieData;
if (data != null) {
resolve(data);
} else {
reject(`ERR: Server could not get your data`);
}
}, 5000);
});
//console.log(getme_dataPromise)
getme_dataPromise.then(function(res) {
displayDOM(res);
}).catch(function(err) {
console.log('err:', err);
});
* {
box-sizing: border-box;
}
div>img {
display: block;
margin: auto;
margin-left: 20%;
}
/* changes seen after refresh */
body {
font-family: sans-serif;
background: #0c111b;
}
.carousel {
/* background: #0c111b; */
width: 95%;
margin: auto;
margin-top: 49px;
padding: 8px 8px;
}
.carousel-cell {
width: 24%;
height: 500px;
margin-right: 80px;
margin-bottom: 40px;
/* border: 2px solid red; */
border-radius: 5px;
box-shadow: rgba(0, 0, 0, 0.25) 0px 54px 55px, rgba(0, 0, 0, 0.12) 0px -12px 30px, rgba(0, 0, 0, 0.12) 0px 4px 6px, rgba(0, 0, 0, 0.17) 0px 12px 13px, rgba(0, 0, 0, 0.09) 0px -3px 5px;
}
.flickity-page-dots {
display: none;
}
/* cell number */
.carousel-cell>img {
height: 80%;
width: 100%;
border-radius: 5px;
}
.carousel-cell>p {
color: #fff;
font-size: 0.8em;
text-align: center;
}
<link rel="stylesheet" href="./body-carousel.css">
<link rel="stylesheet" href="https://unpkg.com/flickity#2/dist/flickity.min.css">
<body>
<button onclick="sortLH()">Low to High</button>
<button onclick="sortHL()">High to low</button>
<div class="carousel" data-flickity='{ "cellAlign": "left", "contain": true }'>
<!-- gif image for loader -->
<img src="./uxplanet.gif" alt="gif">
</div>
</body>
<script src="./data.js"></script>
<script src="./body.js"></script>
<script src="https://unpkg.com/flickity#2/dist/flickity.pkgd.min.js"></script>
Why are you calling same function three times?
1.displayDOM(sort_data);inside SortLH()
2.displayDOM(res); inside .then
3.displayDOM(sort_data); inside SortHL().
i am calling the function that generates our html one time only that is inside my .then
I am just mimicking the data with an array of objects & checked cells are appended inside .carousel.
Update:Added Loading Animation Before Promise is Resolved or Timeout
Duration.
The svg will be generated(length of movieData)times.fore.g in this
case we have 2 movies so there are two loading circles.
I don't think there is any other issue. feel free to respond if you think otherwise
/*let svg = `<svg version="1.1" id="L9" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
viewBox="0 0 100 100" enable-background="new 0 0 0 0" xml:space="preserve">
<path fill="#e72f2f" d="M73,50c0-12.7-10.3-23-23-23S27,37.3,27,50 M30.9,50c0-10.5,8.5-19.1,19.1-19.1S69.1,39.5,69.1,50">
<animateTransform
attributeName="transform"
attributeType="XML"
type="rotate"
dur="1s"
from="0 50 50"
to="360 50 50"
repeatCount="indefinite" />
</path>
</svg>`;*/
let movieData = [{
name: "CuttPutlli",
release_Date: "2022",
rating: "5.9/10 ImDb",
poster: "https://img1.hotstarext.com/image/upload/f_auto,t_web_vl_3x/sources/r1/cms/prod/6531/1326531-v-e6302c49fcd9"
},
{
name: "Thor:Love & Thunder",
release_Date: "2022",
rating: "6.5/10 ImDb",
poster: "https://img1.hotstarext.com/image/upload/f_auto,t_web_vl_3x/sources/r1/cms/prod/8317/1328317-v-56412010beba"
}
];
const getme_dataPromise = new Promise(function(resolve, reject) {
/*let parent = document.querySelector(".carousel");
let i = 0;
while (i < movieData.length) {
parent.innerHTML += svg;
i++
}*/
setTimeout(function() {
let data = movieData;
if (data != null) {
resolve(data);
} else {
reject(`ERR: Server could not get your data`);
}
}, 2000);
});
//console.log(getme_dataPromise)
getme_dataPromise
.then(function(res) {
displayDOM(res); //<--------------------Calling The DisplayDom Fuction.
})
.catch(function(err) {
console.log("err:", err);
});
function displayDOM(data) {
let parent = document.querySelector(".carousel");
/*parent.innerHTML = "";*/
data.forEach(function(el) {
let container = document.createElement("div");
container.className = "carousel-cell";
let poster = document.createElement("img");
poster.src = el.poster;
let name = document.createElement("p");
name.innerText = `Movie: ${el.name}`;
let release = document.createElement("p");
release.innerText = `Year: ${el.release_Date}`;
let rating = document.createElement("p");
rating.innerText = `Rating: ${el.rating}`;
container.append(poster, name, release, rating);
parent.append(container);
});
}
* {
box-sizing: border-box;
}
/* changes seen after refresh */
body {
font-family: sans-serif;
background: #0c111b;
}
.carousel {
/* background: #0c111b; */
width: 95%;
margin: auto;
margin-top: 49px;
padding: 8px 8px;
}
.carousel-cell {
width: min-content;
/*let it take the size of the image*/
/*height: 500ox; let it take the space it needs*/
margin-right: 80px;
margin-bottom: 40px;
/* border: 2px solid red; */
border-radius: 5px;
box-shadow: rgba(0, 0, 0, 0.25) 0px 54px 55px, rgba(0, 0, 0, 0.12) 0px -12px 30px, rgba(0, 0, 0, 0.12) 0px 4px 6px, rgba(0, 0, 0, 0.17) 0px 12px 13px, rgba(0, 0, 0, 0.09) 0px -3px 5px;
}
.flickity-page-dots {
display: none;
}
/* cell number */
.carousel-cell>img {
height: 60%;
/*width: 100%; change only one of height or width to maintaint the aspect ratio*/
border-radius: 5px;
}
.carousel-cell>p {
color: #fff;
font-size: 0.8em;
text-align: center;
}
svg {
width: 200px;
height: 200px;
margin-bottom: 100px;
display: block;
}
<link rel="stylesheet" href="https://unpkg.com/flickity#2/dist/flickity.min.css">
<div class="carousel" data-flickity='{ "cellAlign": "left", "contain": true }'></div>
<script src="https://unpkg.com/flickity#2/dist/flickity.pkgd.min.js"></script>

javascript on a webpage displaying text wrongly

I have JS code on a webpage that loads questions in from mysql db and displays the text . What happens is that it cuts off words at the end of the line and continues the word on the next line at the start. So all text across the screen starts/ends at the same point.
This seems to be the code where it displays the text.
For example the text will look like at the end of a line 'cont' and then on next line at the start 'inue'.
How do i fix this?
var questions = <?=$questions;?>;
// Initialize variables
//------------------------------------------------------------------
var tags;
var tagsClass = '';
var liTagsid = [];
var correctAns = 0;
var isscorrect = 0;
var quizPage = 1;
var currentIndex = 0;
var currentQuestion = questions[currentIndex];
var prevousQuestion;
var previousIndex = 0;
var ulTag = document.getElementsByClassName('ulclass')[0];
var button = document.getElementById('submit');
var questionTitle = document.getElementById('question');
//save class name so it can be reused easily
//if I want to change it, I have to change it one place
var classHighlight = 'selected';
// Display Answers and hightlight selected item
//------------------------------------------------------------------
function showQuestions (){
document.body.scrollTop = 0; // For Safari
document.documentElement.scrollTop = 0; // For Chrome, Firefox, IE and Opera
if (currentIndex != 0) {
// create again submit button only for next pages
ulTag.innerHTML ='';
button.innerHTML = 'Submit';
button.className = 'submit';
button.id = 'submit';
if(quizPage<=questions.length){
//update the number of questions displayed
document.getElementById('quizNumber').innerHTML = quizPage;
}
}
//Display Results in the final page
if (currentIndex == (questions.length)) {
ulTag.innerHTML = '';
document.getElementById('question').innerHTML = '';
if(button.id == 'submit'){
button.className = 'buttonload';
button.innerHTML = '<i class="fa fa-spinner fa-spin"></i>Loading';
}
showResults();
return
}
questionTitle.innerHTML = "Question No:" + quizPage + " "+currentQuestion.question.category_name +"<br/>"+ currentQuestion.question.text;
if(currentQuestion.question.filename !== ''){
var br = document.createElement('br');
questionTitle .appendChild(br);
var img = document.createElement('img');
img.src = currentQuestion.question.filename;
img.className = 'imagecenter';
img.width = 750;
img.height = 350;
questionTitle .appendChild(img);
}
// create a for loop to generate the options and display them in the page
for (var i = 0; i < currentQuestion.options.length; i++) {
// creating options
var newAns = document.createElement('li');
newAns.id = 'ans'+ (i+1);
newAns.className = "notSelected listyle";
var textAns = document.createTextNode(currentQuestion.options[i].optiontext);
newAns.appendChild(textAns);
if(currentQuestion.options[i].file !== ''){
var br = document.createElement('br');
newAns .appendChild(br);
var img1 = document.createElement('img');
img1.src = currentQuestion.options[i].file;
img1.className = 'optionimg';
img1.width = 250;
img1.height = 250;
newAns .appendChild(img1);
newAns .appendChild(br);
}
var addNewAnsHere = document.getElementById('options');
addNewAnsHere.appendChild(newAns);
}
//.click() will return the result of $('.notSelected')
var $liTags = $('.notSelected').click(function(list) {
list.preventDefault();
//run removeClass on every element
//if the elements are not static, you might want to rerun $('.notSelected')
//instead of the saved $litTags
$liTags.removeClass(classHighlight);
//add the class to the currently clicked element (this)
$(this).addClass(classHighlight);
//get id name of clicked answer
for (var i = 0; i < currentQuestion.options.length ; i++) {
// console.log(liTagsid[i]);
if($liTags[i].className == "notSelected listyle selected"){
//store information to check answer
tags = $liTags[i].id;
// tagsClass = $LiTags.className;
tagsClassName = $liTags[i];
}
}
});
//check answer once it has been submitted
button.onclick = function (){
if(button.id == 'submit'){
button.className = 'buttonload';
button.innerHTML = '<i class="fa fa-spinner fa-spin"></i>Loading';
}
setTimeout(function() { checkAnswer(); }, 100);
};
}
//self calling function
showQuestions();
The website is on my local now but i can upload a screenimage if need be and the whole code of the webpage. Or is the issue in html?
edit: here is html/css code
<style>
/*========================================================
Quiz Section
========================================================*/
/*styling quiz area*/
.main {
background-color: white;
margin: 0 auto;
margin-top: 30px;
padding: 30px;
box-shadow: 0 0 20px 0 rgba(0, 0, 0, 0.2), 0 5px 5px 0 rgba(0, 0, 0, 0.24);
/*white-space: nowrap;*/
}
/*Editing the number of questions*/
.spanclass {
font-size: x-large;
}
#pages{
border: 3px solid;
display: inline-flex;
border-radius: 0.5em;
float: right;
}
#question{
word-break: break-all;
}
/*format text*/
p {
text-align: left;
font-size: x-large;
padding: 10px 10px 0;
}
.optionimg{
border: 2px solid black;
border-radius: 1.5em;
}
/*Form area width*/
/*formatting answers*/
.listyle {
list-style-type: none;
text-align: left;
background-color: transparent;
margin: 10px 5px;
padding: 5px 10px;
border: 1px solid lightgray;
border-radius: 0.5em;
font-weight: normal;
font-size: x-large;
display: inline-grid;
width: 48%;
height: 300px;
overflow: auto;
}
.listyle:hover {
background: #ECEEF0;
cursor: pointer;
}
/*Change effect of question when the questions is selected*/
.selected, .selected:hover {
background: #FFDEAD;
}
/*change correct answer background*/
.correct, .correct:hover {
background: #9ACD32;
color: white;
}
/*change wrong answer background*/
.wrong, .wrong:hover {
background: #db3c3c;
color: white;
}
/*========================================================
Submit Button
========================================================*/
.main button {
text-transform: uppercase;
width: 20%;
border: none;
padding: 15px;
color: #FFFFFF;
}
.submit:hover, .submit:active, .submit:focus {
background: #43A047;
}
.submit {
background: #4CAF50;
min-width: 120px;
}
/*next question button*/
.next {
background: #fa994a;
min-width: 120px;
}
.next:hover, .next:active, .next:focus {
background: #e38a42;
}
.restart {
background-color:
}
/*========================================================
Results
========================================================*/
.circle{
position: relative;
margin: 0 auto;
width: 200px;
height: 200px;
background: #bdc3c7;
-webkit-border-radius: 100px;
-moz-border-radius: 100px;
border-radius: 100px;
overflow: hidden;
}
.fill{
position: absolute;
bottom: 0;
width: 100%;
height: 80%;
background: #31a2ac;
}
.score {
position: absolute;
width: 100%;
top: 1.7em;
text-align: center;
font-family: Arial, sans-serif;
color: #fff;
font-size: 40pt;
line-height: 0;
font-weight: normal;
}
.circle p {
margin: 400px;
}
/*========================================================
Confeeti Effect
========================================================*/
canvas{
position:absolute;
left:0;
top:11em;
z-index:0;
border:0px solid #000;
}
.imagecenter{
display: block;
margin: 0 auto;
}
.buttonload {
background-color: #04AA6D; /* Green background */
border: none; /* Remove borders */
color: white; /* White text */
padding: 12px 24px; /* Some padding */
font-size: 16px; /* Set a font-size */
}
/* Add a right margin to each icon */
.fa {
margin-left: -12px;
margin-right: 8px;
}
#media only screen and (max-width: 900px){
.listyle {
width: 100% !important;
height: auto !important;
}
.imagecenter {
width: 100% !important;
}
.listyle img{
width: inherit !important;
height: unset !important;
}
.ulclass
{
padding:0px !important;
}
}
</style>
<!-- Main page -->
<div class="main">
<!-- Number of Question -->
<div class="wrapper" id="pages">
<span class="spanclass" id="quizNumber">1</span><span class="spanclass">/<?=$count?></span>
</div>
<!-- Quiz Question -->
<div class="quiz-questions" id="display-area">
<p id="question"></p>
<ul class="ulclass" id="options">
</ul>
<div id="quiz-results" class="text-center">
<button type="button" name="button" class="submit" id="submit">Submit</button>
</div>
</div>
</div>
<canvas id="canvas"></canvas>
<script src="https://code.jquery.com/jquery-3.2.1.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
I'm guessing that #question{ word-break: break-all; } is probably the culprit then? –
CB..yes that fixed it:)

Can't seem to integrate my CSS and JS/Jquery files in my HTML

Pretty new to coding, was just wondering if maybe someone could revise why my .CSS & .JS files are not linking with my HTML?
Here are the lines & this is what it's supposed to look like: https://codepen.io/MatteoV/pen/aGqQBe
I will also be trying to implement this code into Webflow, would anyone know where I can implement these lines?
Thank you guys for the help! :D
jQuery(document).ready(function($) {
// Terms & Discounts
var termArr = [1, 12, 24, 36],
discArr = [0, 0.2, 0.25, 0.3];
// Custom Region Pricing
var prices = {
ca: [0.12, 0.11, 0.1],
az: [0.12, 0.11, 0.1],
va: [0.12, 0.11, 0.1],
sg: [0.2, 0.19, 0.18],
th: [0.2, 0.19, 0.18],
hk: [0.2, 0.19, 0.18]
};
// Exchange Rates & Symbols
var exchange = {
rates: {
USD: 1,
CNY: 6.92,
THB: 35
},
symbol: {
USD: "$",
CNY: "¥",
THB: "฿"
}
};
// Total TB Slider
$("#gb-slider")
.slider({
range: "min",
value: 2000,
step: 500,
max: 10000,
min: 1000,
slide: function(event, ui) {
if (ui.value < 10000) {
$(".contact-us").fadeOut(200, function() {
$(".price-wrap").fadeIn(200);
});
var term = $("#term-slider").slider("option", "value");
$('[name="qty"]').val(ui.value);
$("#total-price .price").text(calcPrice(ui.value, term));
$("#price-per-gb .price").html(pricePerGB(ui.value).toFixed(2));
$('[name="unit_price"]').val(pricePerGB(ui.value).toFixed(2));
} else {
$(".price-wrap").fadeOut(200, function() {
$(".contact-us").fadeIn(200);
});
}
}
})
.each(function() {
var opt = $(this).data().uiSlider.options;
var vals = (opt.max - opt.min) / 1000;
for (var i = 0; i <= vals; i++) {
var el = $('<label class="value-label">' + (i + 1) + "TB</label>").css(
"left",
"calc(" + i / vals * 100 + "% - 10px)"
);
$(this).append(el);
}
});
// Contract Slider
$("#term-slider")
.slider({
range: "min",
max: termArr.length - 1,
slide: function(event, ui) {
var size = $("#gb-slider").slider("option", "value");
$('[name="period"]').val(termArr[ui.value]);
$("#total-price .price").text(calcPrice(size, ui.value));
$('[name="discount_term"]').val(discArr[ui.value]);
}
})
.each(function() {
var opt = $(this).data().uiSlider.options;
var vals = opt.max - opt.min;
for (var i = 0; i <= vals; i++) {
if (i == 0) {
var el = $('<label class="value-label">Monthly</label>').css("left", "0%");
} else {
var el = $(
'<label class="value-label">' + termArr[i] + " Mo.</label>"
).css("left", i / vals * 95 + "%");
}
$(this).append(el);
}
});
// Calcutate Price Per GB
function pricePerGB(value) {
var region = $("#region").val();
if (value <= 2000) {
return prices[region][0];
} else if (value <= 4999) {
return prices[region][1];
} else if (value <= 10000) {
return prices[region][2];
} else {
return false;
}
}
// Calculate Total Price
function calcPrice(size, term) {
var basePrice = size * pricePerGB(size),
discount = basePrice - basePrice * discArr[term],
rate = exchange.rates[$("#currency-select").val()],
price = (discount * rate).toFixed(2);
return price;
}
// Changing Currencies
$("#currency-select, #region").change(function() {
var pricePer = pricePerGB($("#gb-slider").slider("option", "value")).toFixed(
2
);
$(".currency-symbol").text(exchange.symbol[$(this).val()]);
$("#total-price .price").text(
calcPrice(
$("#gb-slider").slider("option", "value"),
$("#term-slider").slider("option", "value")
)
);
$('[name="unit_price"]').val(pricePer);
$("#price-per-gb .price").text(pricePer);
});
// Load price when page does
$("#total-price .price").text(
calcPrice(
$("#gb-slider").slider("option", "value"),
$("#term-slider").slider("option", "value")
)
);
$("#price-per-gb .price").html(
pricePerGB($("#gb-slider").slider("option", "value")).toFixed(2)
);
$('[name="discount_term"]').val(
discArr[$("#term-slider").slider("option", "value")]
);
$("#backup-form").submit(function(e) {
console.log($(this).serialize());
e.preventDefault();
});
});
#import "susy"; Add
#import "breakpoint"; Add
#import "color-schemer"; Add
#import "bourbon#5.*"; Add
#import "neat#2.*"; Add
#import "modularscale#3.*";
*,
*:before,
*:after {
box-sizing: border-box;
}
$yellow: #fdb022;
$yellow-alt: #eea61e;
$grey: #e6e6e6;
html,
body {
font: 16px "Open Sans", Arial, sans-serif;
}
#veeam-sliders {
width: 72em;
margin: 40px auto 0;
h3 {
font-weight: 600;
font-size: 21px;
margin: 0;
}
label {
font: normal 16px/1 "Open Sans", Arial, sans-serif;
text-transform: uppercase;
color: #aaa;
}
button,
.btn {
text-decoration: none;
border: none;
background: $yellow;
color: #fff;
text-transform: uppercase;
font: 700 14px "Open Sans", Arial, sans-serif;
padding: 8px 20px;
border-radius: 3px;
box-shadow: 0 2px 0 0 darken($yellow-alt, 5%);
cursor: pointer;
&:active {
position: relative;
top: 2px;
box-shadow: none;
}
}
.select-wrap {
margin-bottom: 40px;
margin-left: 15px;
display: inline-block;
position: relative;
&:after {
position: absolute;
top: 8px;
right: 10px;
content: "▾";
color: black;
display: block;
z-index: -1;
font-size: 20px;
}
#region,
#currency-select {
padding: 10px 30px 10px 10px;
font-size: 16px;
border-radius: 5px;
border: 1px solid #ccc;
margin: 0;
appearance: none;
position: relative;
background: rgba(255, 255, 255, 0);
color: #222;
&:hover {
box-shadow: 0 2px 2px rgba(0, 0, 0, 0.15);
}
}
}
.sliders-wrap {
width: 70%;
padding-right: 100px;
float: left;
.slider {
position: relative;
margin: 25px 0;
}
#gb-slider {
margin-bottom: 80px;
}
}
.total-wrap {
width: 30%;
float: left;
button {
margin-top: 40px;
}
.price-wrap {
h3 {
margin-bottom: 10px;
}
#total-price {
font-size: 42px;
line-height: 1.15;
color: #999;
border-bottom: 1px solid $grey;
padding: 0 0 20px;
margin: 0 0 10px;
span {
color: #999;
}
}
#price-per-gb {
color: #222;
font-size: 21px;
clear: both;
.price {
color: #222;
}
}
}
.veeam-provider {
float: right;
}
}
.value-label {
white-space: nowrap;
position: absolute;
top: 25px;
font-size: 15px;
color: #666;
text-transform: none;
font-weight: normal;
}
.contact-us {
margin-top: 25px;
display: none;
h3 {
margin: 0;
line-height: 1;
}
p {
margin: 10px 0 25px;
}
}
/* jQuery UI Slider Theming */
.ui-slider,
.ui-slider-handle,
.ui-slider-range {
border-radius: 500px;
}
.ui-slider {
background: $grey;
border: none;
height: 1em;
}
.ui-slider-handle {
width: 1.8em;
height: 1.8em;
top: -0.4em;
margin-left: -0.7em;
cursor: grab;
background: $yellow-alt;
border-color: $yellow-alt;
}
.ui-slider-range {
background: $yellow;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<!DOCTYPE html>
<html lang "en">
<head>
<meta charset="utf-8">
<title>...</title>
<link rel="stylesheet" type="text/css" href="https://raw.githubusercontent.com/Crackerzzzz/slider/master/slider.css" />
<script type='text/javascript' src='https://raw.githubusercontent.com/Crackerzzzz/slider/master/Slider.js'></script>
</head>
<body>
<section id="veeam-sliders" class="clearfix">
<form id="backup-form">
<div class="sliders-wrap">
<label>Select Data Center:</label>
<div class="select-wrap">
<select id="region" name="idc">
<option value="ca">Los Angeles, CA</option>
<option value="az">Phoenix, AZ</option>
<option value="va">Ashburn, VA</option>
<option value="sg">Singapore, SG</option>
<option value="th">Bangkok, TH</option>
<option value="hk">Hong Kong, HK</option>
</select>
</div>
<div class="tb-wrap">
<h3>Total GB to Backup</h3>
<div id="gb-slider" class="slider"></div>
<input type="hidden" name="qty" value="2000">
</div>
<div class="contract-wrap">
<h3>Contract Term Length</h3>
<div id="term-slider" class="slider"></div>
<input type="hidden" name="period" value="1">
</div>
</div>
<div class="total-wrap">
<label>Select Currency:</label>
<div class="select-wrap">
<select id="currency-select">
<option value="USD">USD</option>
<option value="CNY">CNY</option>
<option value="THB">THB</option>
</select>
</div>
<div class="price-wrap">
<h3>Total:</h3>
<div id="total-price">
<span class="currency-symbol">$</span><span class="price">000.00</span> /m.
</div>
<div id="price-per-gb">
<span>$</span><span class="price">0.00</span> /GB
<input type="hidden" name="unit_price" value="0.12">
</div>
<button type="submit">Add To Cart</button>
<img class="veeam-provider" src="/wp-content/uploads/veeam-gold-provider_x100.jpg">
</div>
<div class="contact-us">
<h3>Contact Us</h3>
<p>If you're interested in enterprise backup with over 10TB of space, please contact our sales agent for a custom quote based on your needs.</p>
Contact Us
</div>
</div>
<input name="discount_term" type="hidden">
<input name="id" value="621" type="hidden">
<input name="option" value="7688:53546" type="hidden">
</form>
</section>
</body>
</html>
Note: the css is messed up due to not having sass installed.

jQuery each() first iteration is wrong, the rest are correct

So, I'm creating a piece of code so the images in my div are automatically centered and adjusted, so they fit in a squared box.
Currently, I've managed to do so, but, something is wrong with the first iteration, because I get the wrong result, let me show you the code.
// news section height calculator
$(window).load(function () {
$('.news-picture').find('img').each(function () {
var screenImage = $(this);
var theImage = new Image();
theImage.src = screenImage.attr("src");
// Get accurate measurements from that.
var imageWidth = theImage.width;
var imageHeight = theImage.height;
var $imgClass = (imageWidth / imageHeight);
var $imgPos = -((imageWidth - $(window).width()) / 2);
console.log(imageWidth);
console.log($(window).width());
if ($imgClass >= 1) {
$(this).addClass('wide').css("left" , $imgPos);
} else {
$(this).addClass('tall');
}
});
});
<div class="news-picture">
<?php the_post_thumbnail('large'); ?>
<div class="news-title">
<h1><?php the_title(); ?></h1>
<div class="datetime"><span><time datetime="<?php the_time('l, F j, Y'); ?>"><?php the_time('l, F j, Y'); ?></time></span></div>
</div>
</div>
As you may notice, I'm working with Wordpress, and specifically with post images.
The case; The iteration runs 3 times, it is supposed to assign a class, and a left value, which will center the image.
But, the first iteration gets the height value of the second iteration, which in first place should be getting the width, of its own iteration. Weird huh.
I'll attach an image of what i'm trying to accomplish, maybe you have suggestions as to how to approach this dilemma.Structure
Thank you for paying attention, I actually fixed by adding two lines only, specifying the current and rendered width and height of the image.
// news section height calculator
$(window).load(function () {
$('.news-picture').find('img').each(function () {
var screenImage = $(this);
var theImage = new Image();
theImage.src = screenImage.attr("src");
theImage.width = screenImage.attr("width");
theImage.height = screenImage.attr("height");
// Get accurate measurements from that.
var imageWidth = theImage.width;
var imageHeight = theImage.height;
var $imgClass = (imageWidth / imageHeight);
var $imgPos = -((imageWidth - $(window).width()) / 2);
console.log(imageWidth);
console.log($(window).width());
if ($imgClass >= 1) {
$(this).addClass('wide').css("left" , $imgPos);
} else {
$(this).addClass('tall');
}
});
});
body {
margin:0;
}
.news-content {
background-color: #fff;
margin: 25px auto;
}
.news-picture {
-webkit-filter: grayscale(100%);
filter: grayscale(100%);
position: relative;
overflow: hidden;
width: 100vw;
height: 100vw;
margin: 0 auto;
}
.news-picture:after {
-moz-box-shadow: 0 0 10em #000 inset;
-webkit-box-shadow: 0 0 10em #000 inset;
box-shadow: 0 0 10em #000 inset;
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
content: "";
}
.news-picture a {
border: 0;
display: block;
}
.wide {
height: 100vw;
width: auto;
max-width: initial;
position: relative;
}
h1 {
}
.news-title {
background-color: rgba(0, 0, 0, 0.5);
z-index: 1;
position: absolute;
bottom: 0;
width: 100%;
}
.news-title h1 {
padding: 15px 10px 0 10px;
margin: 0;
text-align: center;
line-height: 22px;
font-size: 16px;
}
.news-title h1 a {
color: #fff;
margin: 0;
text-decoration: none;
font-family: "Oswald", sans-serif;
}
.datetime {
font-family: "Titillium Web", sans-serif;
font-size: 10px;
padding: 5px;
margin-bottom: 5px;
text-align: center;
text-transform: uppercase;
letter-spacing: 2px;
color: #fff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="news-container">
<div class="news-content">
<div class="news-picture">
<img width="1298px" height="934px" src="http://www.elliotjaystocks.com/assets/article_digest_1.png">
<div class="news-title">
<h1>First Iteration of the problem</h1>
<div class="datetime"><span><time datetime="Sunday, October 23, 2016">Sunday, October 23, 2016</time></span></div>
</div>
</div>
</div>
<div class="news-content">
<div class="news-picture">
<img src="https://guides.area17.com/app/uploads/sites/2/2015/10/05.08_AI_smart_guides-680x301.png">
<div class="news-title">
<h1>Second Iteration of the problem</h1>
<div class="datetime"><span><time datetime="Sunday, October 23, 2016">Sunday, October 23, 2016</time></span></div>
</div>
</div>
</div>
<div class="news-content">
<div class="news-picture">
<img src="https://s-media-cache-ak0.pinimg.com/736x/d6/05/49/d60549cbc19204feee1a672f71e43cee.jpg">
<div class="news-title">
<h1>Third Iteration of the problem</h1>
<div class="datetime"><span><time datetime="Sunday, October 23, 2016">Sunday, October 23, 2016</time></span></div>
</div>
</div>
</div>
</div>

Empty array in form with button click and dynamic input positioning

I have a form that I am using to calculate the sum and average of an array of numbers. I am using a button to trigger the form to appear and then users can add extra input fields to enter as many values as they wish. When they click the 'Calc' button, they receive an alert of the sum and average. This much is working fine. The problem is when I click the trigger again to close and then to reopen the form, the same number of input fields as the user selected appear and, despite having been able to clear their values, I have not been able to empty the associated array. Thus, when the user inputs values the second time and attempts to perform the calculation, the previous values are being added to these new ones.
On top of this, I would like for the the dynamically added inputs to appear one on top of the other and for the '.remove-field' div (or at least the icon it contains) to appear to the right of each input field. I have tried various display values, positioning, etc. but nothing seems to produce a consistent look.
Here is my HTML markup:
<button class="form-launch" data-icon="&#xe17f">AVG</button>
<div class="form-space">
<form role="form" action="/wohoo" method="POST" class="form-add-remove">
<label class="label">Average Calculation</label>
<div id="horizontal_bar"></div>
<div class="multi-field-wrapper">
<div class="add-field"><i class="fa fa-plus-circle"></i></div>
<div class="multi-fields">
<div class="multi-field">
<input type="text" name="stuff[]" class="input-field"/>
<div class="remove-field"><i class="fa fa-minus-circle"></i></div>
</div>
</div>
</div>
<button type="button" class="check">Calc</button>
</form>
</div>
My CSS:
.form-launch {
position: absolute;
top: 20px;
left: 20px;
}
.form-space {
opacity: 0;
}
.form-add-remove {
font-family: "DJB Chalk It Up";
color: #FFF;
font-size: 30px;
width: 600px;
height: 300px;
padding: 20px;
border: 2px solid #FFF;
border-radius: 25px;
box-shadow: 0px 0px 10px 5px #000;
background: transparent url("http://mrlambertsmathpage.weebly.com/files/theme/blackboard.jpeg") repeat-y scroll left center;
text-align: center;
vertical-align: middle;
display: inline-flex;
-moz-box-pack: center;
justify-content: center;
align-items: center;
-moz-box-orient: vertical;
opacity: 1;
position: absolute;
top: 50%;
left: 50%;
margin-left: -300px;
margin-top: -125px;
display: inline-block;
}
.label {
position: absolute;
top: 20px;
left: 20px;
}
#horizontal_bar {
position: absolute;
top: 60px;
left: 0px;
width: 95%;
height: 4px;
border-radius: 2px;
background: #00A2E8 none repeat scroll 0% 0%;
margin: 2.5%;
box-shadow: 0px 0px 6px 3px #000, 0px 0px 1px #000 inset;
}
.multi-field-wrapper {
height: 130px;
width: 90%;
padding: 20px;
margin-left: 0px;
margin-top: 80px;
border: 2px dashed rgba(255, 255, 255, 0.1);
border-radius: 10px;
transition: all 1.5s ease-in-out 0.5S;
overflow-y: scroll;
}
.multi-field-wrapper:hover {
border: 2px solid rgba(255, 255, 255, 0.1);
transition: all 1.5s ease-in-out 0s;
}
.multi-field {
display: inline-block;
}
.add-field {
position: absolute;
right: 20px;
bottom: 20px;
}
i {
color: #00a2e8;
}
.calc {
position: absolute;
left: 20px;
bottom: 20px;
}
input {
font-family: "Borders Divide, But Hearts Shall Conquer";
border-radius: 5px;
border: 2px inset rgba(0, 0, 0, 0.4);
width: 100px;
text-align: right;
padding-right: 10px;
}
And my jQuery:
var launchCount = 0;
var arr = [],
sum = 0;
$('.form-launch').click(function() {
launchCount++;
if ((launchCount % 2) == 1) {
$('.form-space').css('opacity', '1');
// Initialize Average Form
$('.multi-field-wrapper').each(function() {
var $wrapper = $('.multi-fields', this);
$(".add-field", $(this)).click(function(e) {
$('.multi-field:first-child', $wrapper).clone(true).appendTo($wrapper).find('input').val('').focus();
});
$('.multi-field .remove-field', $wrapper).click(function() {
if ($('.multi-field', $wrapper).length > 1)
$(this).parent('.multi-field').remove();
});
});
$(".calc").click(function() {
$("input[type=text]").each(function() {
arr.push($(this).val());
sum += parseInt($(this).val());
});
var n = arr.length;
var AVG = (sum / n);
alert(sum + "," + AVG);
});
// End Average Form
} else if ((launchCount % 2) == 0) {
$('.form-space').css('opacity', '0');
$('.form-add-remove').find("input[type=text]").val('');
if ($('.multi-field', $wrapper).length > 1) {
$(this).parent('.multi-field').remove(); // does not seem to work!
}
arr = []; // also does not seem to work
}
});
I have commented a few lines at the bottom of my jQuery to illustrate what I have tried. I also looked at setting the array length to 0, but I was not able to get that to work either.
Obviously, this is a work in progress. My jsfiddle is here: http://jsfiddle.net/e3b9bopz/77/
Can you try this?
$(".calc").click(function() {
$("input[type=text]").each(function() {
arr.push($(this).val());
sum += parseInt($(this).val());
});
var n = arr.length;
var AVG = (sum / n);
alert(sum + "," + AVG);
arr = []; # How about putting your reset here?
sum = 0; # reinitialized the sum
});
I think you need to reset the arr after you make a calculation.
Not exactly what you need, but move $(".check").click out of $('.form-launch').click, and wrap the whole thing in a jquery ready.
$(function() {
$(".check").click(function() {
$("input[type=text]").each(function() {
arr.push($(this).val());
sum += parseInt($(this).val());
});
var n = arr.length;
var AVG = (sum / n);
alert(sum + "," + AVG);
arr = [];
});
})
JSFiddle

Categories