Javascript positioning element - javascript

I try to create input controls dynamically , works fine apart from the positioning, for some reason I cant put the elements under the previous one, because I'm unable to get "style.top" property.
What I'm doing wrong and how can I fix it?
the HTML code:
<div id='div_attach' class='scrollbox' style='top: 380px; height: 65px; left: 100px; right: 135px;'>
<a href='goes_nowhere' style='top: 5px; left: 5px;'>click_me_if_you_dare</a>
</div>
<button type='button' style='top: 380px; width: 120px; right: 10px; height: 20px;' onclick='createFileInput("div_attach");'>new input</button>
the JS code:
function createFileInput(parentID) {
var atop, index;
var parent = document.getElementById(parentID);
var control = document.createElement('input');
control.setAttribute('type', 'file');
elements = parent.getElementsByTagName('*');
// debug only ...
for (index = 0; index < elements.length; ++index) {
alert(elements[index].style.top);
alert(elements[index].style.height);
};
if (elements.length > 0)
atop = elements[elements.length - 1].style.top + elements[elements.length - 1].style.height + 5;
else
atop = 5;
control.setAttribute('name', 'FILE_' + elements.length);
control.className = 'flat';
control.style.left = 5 + 'px';
control.style.top = atop + 5 + 'px';
// control.style.top = (elements.length * 30) + 5 + 'px';
control.style.width = 500 + 'px';
parent.appendChild(control);
control.focus();
}

The code:
atop = elements[elements.length - 1].style.top + elements[elements.length - 1].style.height + 5;
will return something like "5px5" because it's a string to which you append 5.
Replace it with
atop = parseInt(elements[elements.length - 1].style.top, 10) + parseInt(elements[elements.length - 1].style.height, 10) + 5;
Make sure those element have a top and height value, or else parseInt() will return NaN.
edit: In the example, the <a> has no height.

Related

Getting back correct index value from Array

I have to show Array values in circle kind of shape and it has to be run in a loop forever. Things are working fine when you rotate circle counter clockwise. But it has a problem in when we move circle in opposite direction.
I have an active element on the wheel. So when you user clicks on any other slide then active it calculates the difference between clicked slide and active slide then add and remove items in wheel accordingly.
So basically it picks the value from Array. if you move circle clockwise it picks values from the back of the Array and if you move it counterclockwise it starts picking up values from next available. If 11 items are rendered in first-page load then it will start taking values from 12 no index.
The problem occurs when you click the item which has above position from the active element and then you again rotates it counterclockwise.
Let say you click item no. 8 then you click item no.7. In this case item, no.2 should have been added into the wheel.
Here is fiddle.
var numberOfElement = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30];
var initialRender = numberOfElement.slice(0, 11);
var startPoint = initialRender.length;
var endPoint = numberOfElement.length;
function generateHtml() {
var html = '';
initialRender.forEach(function(item, index) {
var angle = 18 * (index);
var className = angle === 90 ? 'active' : '';
html += '<div class="shapes ' + className + '" data-deg="' + angle + '" style="--deg:' + angle + 'deg;"> <span class="set-pos">' + (item) + '</span> <span> ' + angle + ' deg </span></div>';
})
document.querySelector('#dynamic-html').innerHTML = html;
}
generateHtml();
$('#dynamic-html').on('click', '.shapes', function() {
var deg = 90;
var activeDeg = $('.active').data('deg');
var needToremoveElement = activeDeg;
var selectedElement = $(this).data('deg');
var degrees = deg - selectedElement;
var diff = Math.abs((activeDeg - selectedElement) / 18);
$('.shapes').removeClass('active');
$(this).addClass('active');
var movementCloseWise = degrees > ($('.circle').data('deg') || 0);
$('.circle').removeData('deg');
$('.circle').css({
'transform': 'rotate(' + degrees + 'deg)'
}).attr('data-deg', degrees);
if (movementCloseWise) {
var itemLength = $('.shapes').length;
$('.shapes:gt(' + ((itemLength - 1) - diff) + ')').remove()
var newItems = generateItem(getItemsFromBack(diff), true);
newItems = $(newItems).get().reverse();
$('#dynamic-html').prepend(newItems)
startPoint -= diff;
} else {
var newItems = generateItem(getItemFromStart(diff), false)
$('#dynamic-html').append(newItems)
$('.shapes:lt(' + (diff) + ')').remove()
endPoint += diff;
}
})
function getItemsFromBack(length) {
var values = [];
endPoint = endPoint - length;
if (endPoint < 0) {
endPoint = numberOfElement.length - Math.abs(endPoint)
var otherVal = 0;
if (endPoint + length >= numberOfElement.length) {
otherVal = (endPoint + length) - numberOfElement.length;
values = numberOfElement.slice(endPoint, numberOfElement.length)
}
if (otherVal > 0) {
values = values.concat(numberOfElement.slice(0, otherVal))
}
} else {
values = numberOfElement.slice(endPoint, endPoint + length)
}
var valuesCount = values.length;
return values.reverse();
}
function getItemFromStart(length) {
var values = numberOfElement.slice(startPoint, startPoint + length);
var valueCount = values.length;
startPoint += valueCount;
if (valueCount < length) {
startPoint = 0;
return values.concat(getItemFromStart(length - valueCount));
} else if (startPoint >= numberOfElement.length) {
startPoint = 0;
}
return values;
}
function generateItem(items, isClockWise) {
var html = "",
lastItemAngle;
if (isClockWise) {
lastItemAngle = $('#dynamic-html .shapes:first').data('deg');
} else {
lastItemAngle = $('#dynamic-html .shapes:last').data('deg');
}
items.forEach(function(item, index) {
if (isClockWise) {
var angles = lastItemAngle - (18 * (index + 1))
} else {
var angles = lastItemAngle + (18 * (index + 1))
}
html += '<div class="shapes" data-deg="' + (angles) + '" style="--deg:' + angles + 'deg;"> <span class="set-pos">' + (item) + '</span> <span> ' + angles + ' deg </span></div>';
});
return html;
}
I think your problem is just your endPoint initialization value. In your code, you initialize it as var endPoint = numberOfElement.length; which is wrong( I think) and it should be initialized by 0; I changed it and it worked:
var numberOfElement = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30];
var initialRender = numberOfElement.slice(0,11);
var startPoint = initialRender.length;
var endPoint = 0; /* here is the change */
function generateHtml(){
var html ='';
initialRender.forEach(function(item,index){
var angle = 18 * (index);
var className = angle === 90? 'active':'';
html+='<div class="shapes '+className+'" data-deg="'+angle+'" style="--deg:'+angle+'deg;"> <span class="set-pos">'+(item)+'</span> <span> '+angle+' deg </span></div>';
})
document.querySelector('#dynamic-html').innerHTML= html;
}
generateHtml();
$('#dynamic-html').on('click','.shapes',function(){
var deg = 90;
var activeDeg = $('.active').data('deg');
var needToremoveElement = activeDeg;
var selectedElement = $(this).data('deg');
var degrees = deg - selectedElement;
var diff = Math.abs((activeDeg - selectedElement) / 18);
$('.shapes').removeClass('active');
$(this).addClass('active');
var movementCloseWise = degrees > ($('.circle').data('deg') || 0);
$('.circle').removeData('deg');
$('.circle').css({'transform' : 'rotate('+ degrees +'deg)'}).attr('data-deg',degrees);
if(movementCloseWise){
var itemLength = $('.shapes').length;
$('.shapes:gt('+((itemLength-1)-diff)+')').remove()
var newItems = generateItem(getItemsFromBack(diff), true);
newItems = $(newItems).get().reverse();
$('#dynamic-html').prepend(newItems)
startPoint -= diff;
}else{
var newItems = generateItem(getItemFromStart(diff), false)
$('#dynamic-html').append(newItems)
$('.shapes:lt('+(diff)+')').remove()
endPoint += diff;
}
})
function getItemsFromBack(length) {
var values = [];
endPoint = endPoint - length;
if (endPoint < 0) {
endPoint = numberOfElement.length - Math.abs(endPoint)
var otherVal = 0;
if (endPoint + length >= numberOfElement.length) {
otherVal = (endPoint + length) - numberOfElement.length;
values = numberOfElement.slice(endPoint, numberOfElement.length)
}
if (otherVal > 0) {
values = values.concat(numberOfElement.slice(0, otherVal))
}
} else {
values = numberOfElement.slice(endPoint, endPoint + length)
}
var valuesCount = values.length;
return values.reverse();
}
function getItemFromStart(length) {
var values = numberOfElement.slice(startPoint, startPoint + length);
var valueCount = values.length;
startPoint += valueCount;
if (valueCount < length) {
startPoint = 0;
return values.concat( getItemFromStart(length - valueCount) );
} else if (startPoint >= numberOfElement.length) {
startPoint = 0;
}
return values;
}
function generateItem (items, isClockWise){
var html = "", lastItemAngle;
if(isClockWise){
lastItemAngle = $('#dynamic-html .shapes:first').data('deg');
}
else{
lastItemAngle = $('#dynamic-html .shapes:last').data('deg');
}
items.forEach(function(item,index){
if(isClockWise){
var angles = lastItemAngle - (18 * (index +1))
}
else{
var angles = lastItemAngle + (18 * (index +1))
}
html+='<div class="shapes" data-deg="'+(angles)+'" style="--deg:'+angles+'deg;"> <span class="set-pos">'+(item)+'</span> <span> '+angles+' deg </span></div>';
});
return html;
}
.main{
display: flex;
justify-content: center;
align-items: center;
height: 500px;
}
.pos{
height:150px;
width:150px;
position: relative;
}
.circle{
background: red;
height:150px;
width:150px;
border-radius: 50%;
transition: transform 0.3s ease-in-out;
}
.shapes{
position: absolute;
top:calc(50% - 75px);
left:calc(50% - 10px);
width: 20px;
height: 150px;
transform: rotate(var(--deg)) translate(0, 160px);
background: green;
text-align: center;
}
.fake-overlay{
position: absolute;
width: 203%;
height: 320%;
background: #fff;
top: -160px;
right: -148%;
display: none
}
.active{
background: red
}
.set-pos{
position: absolute;
bottom: 0
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="main">
<div class="pos">
<div class="circle">
<div id="dynamic-html"></div>
</div>
<div class="fake-overlay"></div>
</div>
</div>
And here is Jsfiddle
I have fixed this by the following code.
function getItemsFromBack(length) {
var values = [];
if (endPoint > numberOfElement.length) {
var diff = endPoint - numberOfElement.length;
values = numberOfElement.slice(diff - length, diff)
endPoint = endPoint - length;
return values.reverse();
}
endPoint = endPoint - length;
if (endPoint < 0) {
endPoint = numberOfElement.length - Math.abs(endPoint)
var otherVal = 0;
if (endPoint + length >= numberOfElement.length) {
otherVal = (endPoint + length) - numberOfElement.length;
values = numberOfElement.slice(endPoint, numberOfElement.length)
}
if (otherVal > 0) {
values = values.concat(numberOfElement.slice(0, otherVal))
}
} else {
values = numberOfElement.slice(endPoint, endPoint + length)
}
var valuesCount = values.length;
return values.reverse();
}
I am checking if endPoint is greater then total Array length. Then endPoint- Array.length and using diff to get the element
Your CSS is awesome, but your JavaScript still has a bug. Try this:
click 7, then click 2
To fix it, I propose we simplify your logic a bit:
give meaningful ids to items so we can easily select them, compare them and deduce the item angle
do not use hard coded arrays (if you did it because of a code quality tool like jslint, consider telling it to tolerate for loops)
The complexity of your code was coming from the management of start and end points within a range of 1-30. This is now made easy by 1st point above.
I have not changed your code too much so you can recognize your working parts easily:
// Global variables
var numberOfItems = 30,
numberOfRenderedItems = 11,
firstItem = 0
;
function generateHtml(){
var html ='';
for (var item = 0; item < numberOfRenderedItems; item++) {
var angle = 18 * item,
className = angle === 90? 'active':'';
html +=
'<div class="shapes '+className+'" data-item="'+item+'" data-deg="'+angle+'" style="--deg:'+angle+'deg;">'+
' <span class="set-pos">'+(item+1)+'</span>'+
' <span>'+angle+' deg </span>'+
'</div>';
}
document.querySelector('#dynamic-html').innerHTML= html;
}
generateHtml();
$('#dynamic-html').on('click','.shapes',function(){
// Set clicked item active
$('.shapes').removeClass('active');
$(this).addClass('active');
var selectedItem = Number($(this).data('item')),
previousActiveItem = firstItem + Math.floor(numberOfRenderedItems/2),
diff = selectedItem - previousActiveItem,
selectedAngle = selectedItem * 18,
degrees = 90 - selectedAngle,
isClockWise = diff < 0;
// Rotate all items
$('.circle').removeData('deg');
$('.circle').css({'transform' : 'rotate('+ degrees +'deg)'}).attr('data-deg',degrees);
var items;
if (isClockWise)
items = getItemsFromBack(diff);
else
items = getItemsFromFront(diff);
// Remove items
items.toRemove.forEach( function (item) {
$(".shapes[data-item="+item+"]").remove();
});
// Add items
var newItems = items.toAdd.reduce( function (html, item) {
// Get item number between 1 and max
var itemNumber = getNumberInRange(item),
angle = 18 * item;
return html +
'<div class="shapes" data-item="'+item+'" data-deg="'+angle+'" style="--deg:'+angle+'deg;">'+
' <span class="set-pos">'+itemNumber+'</span>'+
' <span>'+angle+' deg </span>'+
'</div>';
}, '');
if (isClockWise)
$('#dynamic-html').append(newItems);
else
$('#dynamic-html').prepend(newItems)
})
function getItemsFromBack (diff) {
var items = {
toAdd: [],
toRemove: []
};
firstItem += diff;
for (var i = 0; i < Math.abs(diff); i++) {
items.toAdd.push(firstItem + i);
items.toRemove.push(firstItem + i + numberOfRenderedItems);
}
return items;
}
function getItemsFromFront (diff) {
var items = {
toAdd: [],
toRemove: []
};
for (var i = 0; i < Math.abs(diff); i++) {
items.toAdd.push(firstItem + i + numberOfRenderedItems);
items.toRemove.push(firstItem + i);
}
firstItem += diff;
return items;
}
function getNumberInRange (item) {
do {
item = (item + numberOfItems) % numberOfItems;
}
while (item < 0);
return item + 1;
}
Updated JSFiddle link is below
https://jsfiddle.net/dpvjtvjd/2/

How to make a barcode smaller in HTML for printing on one page?

So I am having trouble making my bar codes smaller to fit on one page.
There are supposed to be 3 bar codes per row and when I view it on the screen it looks fine.However, when I go to preview how it will look when it prints they get stuck together.If I make their width too small they no longer scan.
So, how do I make them smaller to fit on one page while they are still able to be scanned?
I have included the main part of my code below it is an HTML file but includes both HTML and JavaScript. I can't put the JavaScript in another file and have it as a source because everything has to be in one file. Any help is appreciated!
<body>
<div width = 100%>
<table class="no-spacing" cellspacing="0">
<tr>
<td width = 25%>
<div id="barcodecontainer" style="width:125%">
<div id="inputdata" >123456123</div> <!-- Enter the NIIN for the barcode here -->
Description : Code128A<br /><!-- Enter the description for the barcode here-->
</div></div>
</td><br/>
<td width = 25%>
<div id="barcodecontainer" style="width:125%">
<div id="inputdata1" >456789123</div> <!-- Enter the NIIN for the barcode here -->
Description : Code128A<br /><!-- Enter the description for the barcode here-->
</div>
</div>
</td>
<td width = 25%>
<div id="barcodecontainer" style="width:125%">
<div id="inputdata2" >111111123</div> <!-- Enter the NIIN for the barcode here -->
Description : Code128A<br /><!-- Enter the description for the barcode here-->
</div>
</div>
</td>
</tr>
</table>
<script type="text/javascript">
/* <![CDATA[ */
function get_object(id) {
var object = null;
if (document.layers) {
object = document.layers[id];
} else if (document.all) {
object = document.all[id];
} else if (document.getElementById) {
object = document.getElementById(id);
}
return object;
get_object("inputdata").innerHTML=DrawHTMLBarcode_Code128A(get_object("inputdata").innerHTML,"yes","in",0,2.5,.6,"bottom","center","","black","white");
get_object("inputdata1").innerHTML=DrawHTMLBarcode_Code128A(get_object("inputdata1").innerHTML,"yes","in",0,2.3,.6,"bottom","center","","black","white");
get_object("inputdata2").innerHTML=DrawHTMLBarcode_Code128A(get_object("inputdata2").innerHTML,"yes","in",0,2.4,.6,"bottom","center","","black","white"</script>
Not sure if this will be any help, but I use CSS to control label size and page formatting.
<!doctype html>
<html lang="en">
<head>
<title>Plain Vanilla JS Code 128B Barcodes</title>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" >
<style type="text/css">
<!- CSS adapted from article: boulderinformationservices.wordpress.com/2011/08/25/print-avery-labels-using-css-and-html/ ->
body {
margin-top: 0in;
margin-left: 0in;
}
.page {
width: 8.5in;
height: 10.5in;
margin-top: 0.5in;
margin-left: 0.25in;
}
.label {
width: 2.1in;
height: .9in;
padding: .125in .3in 0;
margin-right: 0.125in;
float: left;
text-align: center;
overflow: hidden;
}
.page-break {
clear: left;
display:block;
page-break-after:always;
}
</style>
</head>
<body>
<div id="result"></div>
<script type="text/javascript">
// The MIT License (MIT)
// Copyright (c) 2017, Notionovus, LLC.
// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
var arrayCode128Bin = [ '11011001100', '11001101100', '11001100110', '10010011000', '10010001100', '10001001100', '10011001000', '10011000100', '10001100100', '11001001000', '11001000100', '11000100100', '10110011100', '10011011100', '10011001110', '10111001100', '10011101100', '10011100110', '11001110010', '11001011100', '11001001110', '11011100100', '11001110100', '11101101110', '11101001100', '11100101100', '11100100110', '11101100100', '11100110100', '11100110010', '11011011000', '11011000110', '11000110110', '10100011000', '10001011000', '10001000110', '10110001000', '10001101000', '10001100010', '11010001000', '11000101000', '11000100010', '10110111000', '10110001110', '10001101110', '10111011000', '10111000110', '10001110110', '11101110110', '11010001110', '11000101110', '11011101000', '11011100010', '11011101110', '11101011000', '11101000110', '11100010110', '11101101000', '11101100010', '11100011010', '11101111010', '11001000010', '11110001010', '10100110000', '10100001100', '10010110000', '10010000110', '10000101100', '10000100110', '10110010000', '10110000100', '10011010000', '10011000010', '10000110100', '10000110010', '11000010010', '11001010000', '11110111010', '11000010100', '10001111010', '10100111100', '10010111100', '10010011110', '10111100100', '10011110100', '10011110010', '11110100100', '11110010100', '11110010010', '11011011110', '11011110110', '11110110110', '10101111000', '10100011110', '10001011110', '10111101000', '10111100010', '11110101000', '11110100010', '10111011110', '10111101110', '11101011110', '11110101110', '11010000100', '11010010000', '11010011100', '1100011101011', '11010111000'];
var array5bit_A = [ 'f//AAAAAAAAAAAAAAAAAAAA', 'f//AAAAAAAAAAAAAAAAAAAB', 'f//AAAAAAAAAAAAAAEAAAD/', 'f//AAAAAAAAAAAAAAEAAAAA', 'f//AAAAAAAAAQAAAP8AAAAA', 'f//AAAAAAAAAQAAAP8AAAAB', 'f//AAAAAAAAAQAAAAAAAAD/', 'f//AAAAAAAAAQAAAAAAAAAA', 'f//AAABAAAA/wAAAAAAAAAA', 'f//AAABAAAA/wAAAAAAAAAB', 'f//AAABAAAA/wAAAAEAAAD/', 'f//AAABAAAA/wAAAAEAAAAA', 'f//AAABAAAAAAAAAP8AAAAA', 'f//AAABAAAAAAAAAP8AAAAB', 'f//AAABAAAAAAAAAAAAAAD/', 'f//AAABAAAAAAAAAAAAAAAA', 'QD/AAD/AAAAAAAAAAAAAAAA', 'QD/AAD/AAAAAAAAAAAAAAAB', 'QD/AAD/AAAAAAAAAAEAAAD/', 'QD/AAD/AAAAAAAAAAEAAAAA', 'QD/AAD/AAAAAQAAAP8AAAAA', 'QD/AAD/AAAAAQAAAP8AAAAB', 'QD/AAD/AAAAAQAAAAAAAAD/', 'QD/AAD/AAAAAQAAAAAAAAAA', 'QD/AAAAAAAA/wAAAAAAAAAA', 'QD/AAAAAAAA/wAAAAAAAAAB', 'SL/AADeAAAA/gAAAAIAAAD+', 'QD/AAAAAAAA/wAAAAEAAAAA', 'QD/AAAAAAAAAAAAAP8AAAAA', 'QD/AAAAAAAAAAAAAP8AAAAB', 'QD/AAAAAAAAAAAAAAAAAAD/', 'QD/AAAAAAAAAAAAAAAAAAAA'];
var array5bit_B = [ 'US0CAuSD38g', 'UUYCA7QBErs', 'ajEDAm49ReY', 'UUoCA+juogg', 'bjEDAjQrOn0', 'bkoDA3iPVH4', 'ajUDAt82atY', 'UU4CA1nljTg', 'cjEDAghkmFU', 'ckoDA0TA9lY', 'izUEAhrxcbg', 'ck4DAxY8F10', 'bjUDAlvFFR8', 'bk4DAxdhexw', 'ajkDAr7LFAw', 'UVICAyQ+UJI', 'TTECAq7UnEM', 'TUoCA+Jw8kA', 'ZjUDAmZGozo', 'TU4CA7CME0s', 'ajUDAvnk9E4', 'ak4DA7VAmk0', 'ZjkDAtle3bI', 'TVICAxOyzrM', 'STUCAqHeHtM', 'SU4CA+16cNA', 'h6QEAZKdo54', 'SVICA62zYxM', 'RTkCAqx1lb4', 'RVICA/z3WM0', 'QT0CAkdoxRU', 'KFYBA46vJCA'];
var stringStart = '<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAACCAQAAADLaIVbAAAANUlEQVQIHQEqANX/A';
var stringMid = 'AAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAA';
var stringEnd = 'AAAAASUVORK5CYII=" style="width:';
function genBarcode(inputString, intWidth, intHeight) {
var arraySeq = [], i, intChunks, resultString;
var intRawmod = inputString.length % 5;
for (i = 0; i < 5 - intRawmod; i += 1) {
inputString += "0";
}
intChunks = inputString.length / 5;
for (i = 0; i < intChunks; i += 1) {
arraySeq[i] = parseInt(inputString.substr(i * 5, 5), 2);
}
resultString = "";
for (i = 0; i < arraySeq.length; i += 1) {
resultString += stringStart + array5bit_A[arraySeq[i]] + stringMid + array5bit_B[arraySeq[i]] + stringEnd + intWidth + 'px;height:' + intHeight + 'px;">';
}
return resultString;
}
function funcCode128B(strText) {
var j, intWeight, intWtProd = 0;
var strRaw = "";
var arrayData = [];
arrayData[0] = 104;
intWtProd = 104;
for (j = 0; j < strText.length; j += 1) {
arrayData[j + 1] = strText.charCodeAt(j) - 32;
intWeight = j + 1;
intWtProd += intWeight * arrayData[j + 1];
}
arrayData[j + 1] = intWtProd % 103;
arrayData[j + 2] = 106;
for (j = 0; j < arrayData.length; j += 1) {
strRaw += arrayCode128Bin[arrayData[j]];
}
return(strRaw);
}
function fnNewPage(pageno) {
var strNewPage, startNewPage = '<div class="page" id="page';
strNewPage = startNewPage + pageno + '">';
return strNewPage;
}
function fnEndPage() {
var strEndPage = '<div class="page-break"></div></div>';
return strEndPage;
}
function fnNewLabel(barcode, txtHR) {
var strNewLabel, startNewLabel = '<div class="label">';
strNewLabel = startNewLabel + barcode + '<br>' + txtHR + '</div>';
return strNewLabel;
}
function fnShowPage() {
var outerLoop, innerLoop, indexBarcode, txtHumanReadable, strPage = "";
for (outerLoop = 0; outerLoop < 2; outerLoop += 1) {
strPage += fnNewPage(outerLoop + 1);
for (innerLoop = 0; innerLoop < 30; innerLoop += 1) {
indexBarcode = (30 * outerLoop) + innerLoop + 400;
switch (indexBarcode) {
case 400:
txtHumanReadable = '' + 123456123; break;
case 401:
txtHumanReadable = '' + 456789123; break;
case 402:
txtHumanReadable = '' + 111111123; break;
default:
txtHumanReadable = 'Test1' + indexBarcode;
}
txtBarcode = genBarcode(funcCode128B(txtHumanReadable), 6.5, 34);
strPage += fnNewLabel(txtBarcode, txtHumanReadable)
}
strPage += fnEndPage();
}
document.getElementById("result").innerHTML = strPage;
}
fnShowPage();
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
</script>
</body>
</html>
In order to prevent the DIVs from getting mixed up, you need to set the width of the divs with id="barcodecontainer" to 100%. This way its content won't get out of its parent <td>.
<div id="barcodecontainer" style="width:100%">
Then just set the width of the "parent" DIVs to whatever percentage of the screen you want, preferable using the style attribute and vw units other than width and %:
<td style="width:20vw">
and not:
<td width = 25%>
In general, I suggest you use CSS instead of repeating the style attributes for each element, especially because your code is already built in hierarchy.
Here's a complete example.
Not to be super critical, but in my opinion you are using out dated web practices.
I recommend not using table and using my little best friend flexbox.
That being said, you are trying to shrink a bar code down without it losing its scan ability.
I would try and make a few divs, then from their flex them into the location you want. From that make them a big or small as you want by resizing the divs.
Hopefully, this helped.
It's hard to come up with a solution without seeing a running demo of the problem you are facing. (https://stackoverflow.com/help/mcve)
(Moreover the script that you have included has some syntax errors as well. Missing closing brackets for function definition as well as on the last line. I assume these are just some typos you made while posting the question here.)
Looking at the API documentation for DrawHTMLBarcode_Code128A # https://www.barcoderesource.com/htmlBarcodeAPI.shtml, I can see that the 4th param is minBarWidth. You have currently set it to 0. Instead you can set it to 2.5, same as the value for width param, and see if that helps.
(You should combine this suggestion with the suggestions given by #GalAbra. Those are also valid points)

Javascript - changing widths of images

I'm creating a tug of war website as a small project. My problem is that my javascript doesn't seem to want to work.
<script>
function randomTeam(){
var TeamV = Math.floor((Math.random() *2 ) + 1)
document.getElementById("TeamHeader").innerHTML = "Team: " + TeamV;
return TeamV;
}
function changeWidth(TeamV){
var MetreLeftV = document.getElementById('MetreLeft');
var MetreRightV = document.getElementById('MetreRight');
if(TeamV == 1){
MetreLeftV.style.width += '10px';
MetreRightV.style.width -= '10px';
}
else if(TeamV == 2){
MetreRightV.style.width += '10px';
MetreLeftV.style.width -= '10px';
}
}
</script>
Basically, when the page is loaded the randomTeam function is called, and when the button is pressed, it increments the size of your teams side, and decrements the side of the enemy's team. The problem is, it doesn't work at all. Could anyone help me see where this is going wrong? Thank you in advance :')
You can not just add 10px to the width. Convert the width to a number, add 10, than add px to it.
MetreLeftV.style.width = (parseFloat(MetreLeftV.style.width) + 10) + "px"
Do the same for the others and you will need a check for negative numbers.
function randomTeam() {
var TeamV = Math.floor((Math.random() * 2) + 1)
document.getElementById("TeamHeader").innerHTML = "Team: " + TeamV;
return TeamV;
}
function changeWidth(TeamV) {
var MetreLeftV = document.getElementById('MetreLeft');
var MetreRightV = document.getElementById('MetreRight');
console.log(parseFloat(MetreLeftV.style.width) + 10 + 'px')
if (TeamV == 1) {
MetreLeftV.style.width = parseFloat(MetreLeftV.style.width) + 10 + 'px';
MetreRightV.style.width = parseFloat(MetreRightV.style.width) - 10 + 'px';
} else if (TeamV == 2) {
MetreLeftV.style.width = parseFloat(MetreLeftV.style.width) - 10 + 'px';
MetreRightV.style.width = parseFloat(MetreRightV.style.width) + 10 + 'px'
}
}
window.setInterval( function () {
var move = randomTeam();
changeWidth(move);
}, 1000);
#MetreLeft {
background-color: red
}
#MetreRight {
background-color: yellow
}
<div id="TeamHeader"></div>
<div id="MetreLeft" style="width:200px">Left</div>
<div id="MetreRight" style="width:200px">Right</div>

Dynamically creating divs and applying values from arrays to them

I want to loop through an array (palettesDIVArray) that contains arrays ( paletteOne,paletteTwo & paletteThree) and apply colors values contained in the arrays to divs (palettesDIV) that are created dynamically.
The number of palettesDIV created should be based on the number of arrays in palettesDIVArray.
Each palettesDIV should then be filled with colors from one array, for this purpouse a number of divs (palettesDIVparts) are created depdning on the number of colors contained in each palette array.
As you can see in the jsfiddle, it all works fine as long as I just target a specific div and pick specific array to apply.
Any idea of how I can modify my code so that it creates 3 divs and applies the colors from the arrays that contain colors in a more dynamic way?
https://jsfiddle.net/ccxtbpzz/6/
javascript:
var
divPalette,
palettePage,
contentSection,
paletteOne,
paletteTwo,
paletteThree,
paletteArray,
palettePart,
widthOfdivPalette,
palettesDIV,
palettesDIVArray,
palettesDIVparts,
divOffSetWidth,
nrOfDivParts,
widthInPixels;
//Initializing varibles and attatching functions
palettePage = document.getElementById("palettePage");
paletteOne = ["hsla(300,21%,85%,0.92)", "hsla(100,91%,85%,0.92)", "hsla(19,71%,85%,0.92)"];
paletteTwo = ["hsla(176,51%,85%,0.92)", "hsla(216,11%,85%,0.92)", "hsla(350,91%,85%,0.92)", "hsla(240,31%,85%,0.92)", "hsla(111,11%,25%,0.92)"];
paletteThree = ["hsla(276,51%,15%,0.92)", "hsla(116,20%,85%,0.32)", "hsla(150,91%,85%,0.92)", "hsla(240,31%,85%,0.92)", "hsla(111,11%,25%,0.92)"];
paletteArray = [paletteOne, paletteTwo, paletteThree];
palettesDIVArray = [];
function createPalettesDivs() {
for (var i = 0; i < paletteArray.length; i++) {
palettesDIV = document.createElement("div");
palettesDIVArray.push(palettesDIV);
palettesDIV.className = "palettesDIV";
palettePage.appendChild(palettesDIV);
}
}
createPalettesDivs();
function createpalettesDIVparts() {
for (var i = 0; i < paletteArray[1].length; i++) {
palettesDIVparts = document.createElement("div");
palettesDIVArray[0].appendChild(palettesDIVparts);
palettesDIVparts.className = "palettesDIVparts";
palettesDIVparts.style.backgroundColor = paletteArray[2][i];
//Setting width of each palettesDIVparts
divOffSetWidth = palettesDIV.offsetWidth;
nrOfDivParts = paletteArray[1].length;
widthInPixels = divOffSetWidth / nrOfDivParts;
palettesDIVparts.style.width = widthInPixels / divOffSetWidth * 100 + "%";
}
}
createpalettesDIVparts();
html:
<div id="palettePage"></div>
css:
#palettePage {
height: 100%;
width: 100%;
position: absolute;
left: 0;
bottom:0;
}
.palettesDIV {
width: 20%;
height: 20%;
float: left;
margin: 2.5%;
border: 1px solid black;
}
.palettesDIVparts {
height: 100%;
float: left;
}
This will get you closer although I think the whole thing is a bit overcomplicated.
function createpalettesDIVparts() {
palettesDIVArray.forEach(function(div, divIdx){
// define pallet being used to make it easier to read throughout function
var pallet = paletteArray[divIdx]
for (i = 0; i < pallet.length; i++) {
var palettesDIVparts = document.createElement("div");
div.appendChild(palettesDIVparts);
palettesDIVparts.className = "palettesDIVparts";
palettesDIVparts.style.backgroundColor = pallet[i];
//Setting width of palettesDIVparts
divOffSetWidth = palettesDIV.offsetWidth;
nrOfDivParts = pallet.length;
widthInPixels = divOffSetWidth / nrOfDivParts;
palettesDIVparts.style.width = widthInPixels / divOffSetWidth * 100 + "%";
}
});
}
DEMO
I updated the jsfiddle to apply the color pallets across all three divs
https://jsfiddle.net/ccxtbpzz/8/
I simply added a second loop to your function createpalettesDIVparts() and used its index as a reference like so:
function createpalettesDIVparts() {
for (x = 0; x < paletteArray.length; x++) {
for (i = 0; i < paletteArray[x].length; i++) {
palettesDIVparts = document.createElement("div");
palettesDIVArray[x].appendChild(palettesDIVparts);
palettesDIVparts.className = "palettesDIVparts";
palettesDIVparts.style.backgroundColor = paletteArray[x][i];
//Setting width of palettesDIVparts
divOffSetWidth = palettesDIV.offsetWidth;
nrOfDivParts = paletteArray[x].length;
widthInPixels = divOffSetWidth / nrOfDivParts;
palettesDIVparts.style.width = widthInPixels / divOffSetWidth * 100 + "%";
}
}
}
Hope this helps.

How to stop Looping - Javascript 100%

I was hoping someone could help me figure this out. I will list the code, and it works just fine, as it is an animation. However, when I check it out in the console it wont stop looping even though it hit the last item in the array. The image itself stops, but if you view the console it shows it looping.
Here is the code, have at it!
var position_X = ["0px", "-525px", "-1050px", "-1575px", "-2100px", "-2625px", "-3150px", "-3675px", "-4200px", "-4725px", "-5250px", "-5775px", "-6300px", "-6825px", "-7350px"];
var _lock = document.getElementById('hi');
// console.log(_lock);
_lock.style.border = "1px solid black";
_lock.style.backgroundImage = "url('http://handbagmanufacturing.com/wp-content/CDN/images/lock.png')";
function lockAnimation(){
setInterval(function(){
var _count = position_X.length;
for(var i = 0; i < _count; i++){
if(i == _count) break;
_lock.style.backgroundPosition = position_X[i] + " 263px";
console.log("Here is the background positions : " + i + ") " + position_X[i]);
}
}
, 100);
}
#hi {
width: 525px;
height: 263px;
background-position-x: "-7875px"
}
<button onclick="lockAnimation()">Click Me I'm Irish!</button>
<div id="hi"></div>
Change setInterval to setTimeout. This will run the function only once instead of running it every 100 ms.
var position_X = ["0px", "-525px", "-1050px", "-1575px", "-2100px", "-2625px", "-3150px", "-3675px", "-4200px", "-4725px", "-5250px", "-5775px", "-6300px", "-6825px", "-7350px"];
var _lock = document.getElementById('hi');
// console.log(_lock);
_lock.style.border = "1px solid black";
_lock.style.backgroundImage = "url('http://handbagmanufacturing.com/wp-content/CDN/images/lock.png')";
function lockAnimation(){
setTimeout(function(){
var _count = position_X.length;
for(var i = 0; i < _count; i++){
if(i == _count) break;
_lock.style.backgroundPosition = position_X[i] + " 263px";
console.log("Here is the background positions : " + i + ") " + position_X[i]);
}
}
, 100);
}
#hi {
width: 525px;
height: 263px;
background-position-x: "-7875px"
}
<button onclick="lockAnimation()">Click Me I'm Irish!</button>
<div id="hi"></div>

Categories