Minimizing CSS "margin-" rules to one "margin:" rule with Javascript - javascript

I have entered each "margin-" CSS rule in an array giving me:
[ 'margin-left:15px', 'margin-right:25px', 'margin-top:100px' ]
I am trying to create an array that displays the values in the right order
var margRed1:[newMargTop, newMargRight, newMargBottom,newMargLeft];
My code is:
var directionRegex = /\d{2,3}px/;
var margRed = "margin: ";
var noMarg = "0px";
var margRed1 = [];
for (var i = 0; i < cssClassArrayMargin.length; i++) {
if (cssClassArrayMargin[i].match('-top')) {
var margTop = directionRegex.exec(cssClassArrayMargin[i]);
var newMargTop = margTop[0];
} else {
newMargTop = noMarg
}
if (cssClassArrayMargin[i].match('-right')) {
var margRight = directionRegex.exec(cssClassArrayMargin[i]);
var newMargRight = margRight[0];
} else {
newMargRight = noMarg
};
if (cssClassArrayMargin[i].match('-bot')) {
var margBot = directionRegex.exec(cssClassArrayMargin[i]);
var newMargBot = margBot[0];
} else {
newMargBot = noMarg
}
if (cssClassArrayMargin[i].match('-left')) {
var margLeft = directionRegex.exec(cssClassArrayMargin[i]);
var newMargLeft = margLeft[0];
} else {
newMargLeft = noMarg
}
}
if (newMargTop || newMargRight || newMargBot || newMargLeft === undefined) {
newMargTop = noMarg;
newMargBot = noMarg;
}
console.log(margRed1)
It gives me the following array:
[ '100px', '25px', undefined, '15px' ]
I do not understand why it does not display 0px and instead displays undefined.
Thanks

why don't you try to initial this "margRed1" array like this first?
var margRed1 = [ '0px', '0px', '0px', '0px' ];
and then remove these code
if (newMargTop || newMargRight || newMargBot || newMargLeft === undefined) {
newMargTop = noMarg;
newMargBot = noMarg;
}

[ 'margin-left:15px', 'margin-right:25px', 'margin-top:100px' ]
In the above code the entered value does not have all four value but in array there are four values
var margRed1:[newMargTop, newMargRight, newMargBottom,newMargLeft];
Give margin-bottom:0 where you have entered the values like this
[ 'margin-left:15px', 'margin-right:25px', 'margin-top:100px', 'margin-bottom:0px' ]

You need to read about variable hoisting. You are declaring variables in blocks, which means they are hoisted to the top of the function and start their lives as undefined. This is very poor code:
if (someCondition) {
var x = 0;
} else {
x = 1;
}
It would be better written as:
var x;
...
x = someCondition ? 0 : 1;
Also the line:
if (newMargTop || newMargRight || newMargBot || newMargLeft === undefined) {
Is this intentional? You are testing for newMartTop, newMargRight, or newMartBot to be truthy, or newMargLeft to be undefined. You would be better to omit the === undefined altogether.

Related

Javascript How to check the length of multiple variables and return the result in an efficient way?

At the moment I have an if the condition that checks if any of the string variable lengths is greater than 2 if true check for another condition, else console.log the output.
var previous_data_change = 'last_changed on 10/01/2019 13:56:34';
var current_data_change= "";
var current_data_end = "";
var current_data_profile = "normal";
// check for changes
if (
previous_data_change.length >= 2 ||
current_data_start.length >= 2 ||
current_data_end.length >= 2 ||
current_data_profile.length >= 2
) {
if (previous_data_change.includes("last_changed")) {
console.log(`last change comments: ${previous_data_change}`)
}
} else {
console.log(`no change in previous record`)
}
i have tried refactoring it using some,
var previous_data_change = 'last_changed on 10/01/2019 13:56:34';
var current_data_change= "";
var current_data_end = "";
var current_data_profile = "normal";
var filter_col = [
previous_data_change,
current_data_change,
current_data_end,
current_data_profile
];
change_boolean = filter_col.some((element) => element.length >= 2);
if (change_boolean && previous_data_change.includes("last_changed")) {
console.log(`last change comments: ${previous_data_change}`);
} else {
console.log("no change in previous record");
}
is there any way to shorten it further?
Since you want any of them to be length greater than 2. You can simply merge them instead of writing 4 if conditions.
var previous_data_change = 'last_changed on 10/01/2019 13:56:34';
var current_data_change= "";
var current_data_end = "";
var current_data_profile = "normal";
var string_to_check = previous_data_change + current_data_start + current_data_end + current_data_profile;
// check for changes
if (string_to_check.length < 2) {
console.log(`no change in previous record`)
return false;
}
if (previous_data_change.includes("last_changed")) {
console.log(`last change comments: ${previous_data_change}`)
return true;
}

value is not added to multidimensional array

The first time the function fires I get this result:
output1:test
The output2 2 alert is not firing. I know something is probably undefined in alert Does anyone know why the value won't be added in the multidimensional array?
I expect this to display after the false1:
output2:test2
Also if you want to fiddle with the code here it is:
https://jsfiddle.net/ndf0sjgf/1/
var carSelectedArray = [
[null]
];
addRow(carSelectedArray);
addRow(carSelectedArray);
function addRow(carSelectedArray) {
var arrayempty = false;
if (carSelectedArray[0][0] == null || carSelectedArray.length == 0) {
arrayempty = true;
} else {
arrayempty = false;
}
if (arrayempty == true) {
carSelectedArray[0][0] = "test";
alert("output1:" + carSelectedArray[0][0]);
} else {
carSelectedArray[1][0] = "test2";
alert("output2:" + carSelectedArray[1][0]);
}
}
Your loop works well, however your didn't define your array well.
there is only 1 dimension here :
var carSelectedArray = [[null]];
So replace with this :
var carSelectedArray = [[],[]];
PS : null is not required
and at the beginning in your function, you define arrayempty to false, so you can remove this :
else {
arrayempty = false;
}
Solution here : https://plnkr.co/edit/Qikalr0jc54R3MRSea4G?p=preview
var carSelectedArray = [[],[]];
addRow(carSelectedArray);
addRow(carSelectedArray);
function addRow(carSelectedArray) {
var arrayempty = false;
if (carSelectedArray[0][0] == null || carSelectedArray.length == 0) {
arrayempty = true;
}
if (arrayempty == true) {
carSelectedArray[0][0] = "test";
alert("output1:" + carSelectedArray[0][0]);
} else {
carSelectedArray[1][0] = "test2";
alert("output2:" + carSelectedArray[1][0]);
}
}

JavaScript Check multiple variables being empty

I'm trying the following code:
var var1 = "";
var var2 = "test";
var var3 = "";
vars = new Array('var1','var2','var3');
var count = 0;
for (var i = 0; i < vars.length; ++i) {
var name = vars[i];
if (field_is_empty(name)) {
count++;
}
}
console.log(count);
function field_is_empty(sValue) {
if (sValue == "" || sValue == null || sValue == "undefined")
{
return true;
}
return false;
}
The result here should have been count = 2 because two of the variables are empty but it's always 0. I guess it must something when using if (field_is_empty(name)) because it might not getting the name converted to the name of the actual var.
PROBLEM 2# Still related
I've updated the code as Karthik Ganesan mentioned and it works perfectly.
Now the code is:
var var1 = "";
var var2 = "test";
var var3 = "";
vars = new Array(var1,var2,var3);
var count = 0;
for (var i = 0; i < vars.length; ++i) {
var name = vars[i];
if (field_is_empty(name)) {
count++;
}
}
console.log(count);
function field_is_empty(sValue) {
if (sValue == "" || sValue == null || sValue == "undefined")
{
return true;
}
return false;
}
And the problem is that if add a new if statement something like this:
if (count == '3') {
console.log('AllAreEmpty');
} else {
for (var i = 0; i < vars.length; ++i) {
var name = vars[i];
if (field_is_empty(name)) {
//Set the empty variables as "1900-01-01"
variableService.setValue(name,"test");
}
}
}
It does nothing and I've tested using variableService.setValue('var1',"test") and it works.
PS: The variableService.setValue is a function controlled by the software I don't know exactly what it does I know if use it like mentioned on above line it works.
In your first attempt you used the variable names as strings when you created an array. You need to either use the values themselves:
vars = new Array(var1,var2,var3);
or if you insist to use them by their names, then you need to find them by names when you use them:
if (field_is_empty(window[name])) {
It does nothing
That's not really possible. It could throw an error, or enter the if or enter the else, but doing nothing is impossible. However, since you intended to use the variables by name in the first place (probably not without a reason) and then you intend to pass a name, but it is a value and it does not work as expected, I assume that your initial array initialization was correct and the if should be fixed like this:
var var1 = "";
var var2 = "test";
var var3 = "";
vars = new Array(var1,var2,var3);
var count = 0;
for (var i = 0; i < vars.length; ++i) {
var v = window[vars[i]]; //You need the value here
if (field_is_empty(v)) {
count++;
}
}
console.log(count);
if (count == '3') {
console.log('AllAreEmpty');
} else {
for (var i = 0; i < vars.length; ++i) {
var v = window[vars[i]];
if (field_is_empty(v)) {
//Set the empty variables as "1900-01-01"
variableService.setValue(vars[i],"test");
}
}
}
function field_is_empty(sValue) {
if (sValue == "" || sValue == null || sValue == "undefined")
{
return true;
}
return false;
}
You definitely incorrectly initialize array, you put strings "var1", "var2", "var3" instead of references to strings (variables).
Try this:
vars = new Array(var1,var2,var3);
Your array is wrong
it should be
vars = new Array(var1,var2,var3);
here is the jsfiddle

how to reindex object start from 0

I have an object output from below code how to set the index start from 0 in js?
Object
3: Object
id: 34
type: 0
var obj = {};
var edited = false;
for (var i = 0; i < $(".list").length; i++) {
var data_id = parseInt($(".list").eq(i).attr('data-id'));
var data_type = parseInt($(".list").eq(i).attr('data-type'));
if ((data_type != 0)) {
edited = true;
} else {
edited = false;
}
if (edited == true) {
obj[i] = {};
obj[i]['id'] = data_id;
obj[i]['type'] = data_type;
}
}
console.log(obj);
Needs more jQuery ?
var arr = $(".list").filter(function() {
return $(this).data('type') != 0;
}).map(function() {
return { id : $(this).data('id'), type : $(this).data('type') };
}).get();
FIDDLE
Actually if you want to start in 0, use another variable and not "i" (which I think is 3 when you use it as index).
var obj = {};
var edited = false;
var obj_idx = 0;
for (var i = 0; i < $(".list").length; i++) {
var data_id = parseInt($(".list").eq(i).attr('data-id'));
var data_type = parseInt($(".list").eq(i).attr('data-type'));
if ((data_type != 0)) {
edited = true;
} else {
edited = false;
}
if (edited == true) {
obj[obj_idx] = {};
obj[obj_idx]['id'] = data_id;
obj[obj_idx]['type'] = data_type;
obj_idx += 1;
}
}
console.log(obj);
I think this time obj will be something like:
Object
0: Object
id: 34
type: 0
you could fake object as array by Array.prototype.push.call, in that way you could also gain the side effect: obj.length. it's kinda ninja and elegant :]
var obj = {};
var edited = false;
for (var i = 0; i < $(".list").length; i++) {
var data_id = parseInt($(".list").eq(i).attr('data-id'));
var data_type = parseInt($(".list").eq(i).attr('data-type'));
if ((data_type != 0)) {
edited = true;
} else {
edited = false;
}
if (edited == true) {
Array.prototype.push.call(obj, {id: data_id, type: data_type});
}
}
I am going to give a very simple and readable example. Say you've got an object with the following structure:
Object
0: Object
key: 'some-key'
value: 'some-value'
1: Object
...
Then you might want to delete an entry from it and reindex the whole thing, this is how I do it:
// obj is Object from above
const reIndexed = Object.entries(obj).map((element, index) => {
if (parseInt(element[0] != index) {
element[0] = index.toString();
}
return element;
});

javascript - Failed to load source for: http://localhost/js/m.js

Why oh why oh why... I can't figure out why I keep getting this error. I think I might cry.
/*** common functions */
function GE(id) { return document.getElementById(id); }
function changePage(newLoc) {
nextPage = newLoc.options[newLoc.selectedIndex].value
if (nextPage != "")
{
document.location.href = nextPage
}
}
function isHorizO(){
if (navigator.userAgent.indexOf('iPod')>-1)
return (window.orientation == 90 || window.orientation==-90)? 1 : 0;
else return 1;
}
function ShowHideE(el, act){
if (GE(el)) GE(el).style.display = act;
}
function KeepTop(){
window.scrollTo(0, 1);
}
/* end of common function */
var f = window.onload;
if (typeof f == 'function'){
window.onload = function() {
f();
init();
}
}else window.onload = init;
function init(){
if (GE('frontpage')) init_FP();
else {
if (GE('image')) init_Image();
setTimeout('window.scrollTo(0, 1)', 100);
}
AddExtLink();
}
function AddExtLink(){
var z = GE('extLink');
if (z){
z = z.getElementsByTagName('a');
if (z.length>0){
z = z[0];
var e_name = z.innerHTML;
var e_link = z.href;
var newOption, oSe;
if (GE('PSel')) oSe = new Array(GE('PSel'));
else
oSe = getObjectsByClassName('PSel', 'select')
for(i=0; i<oSe.length; i++){
newOption = new Option(e_name, e_link);
oSe[i].options[oSe[i].options.length] = newOption;
}
}
}
}
/* fp */
function FP_OrientChanged() {
init_FP();
}
function init_FP() {
// GE('orientMsg').style.visibility = (!isHorizO())? 'visible' : 'hidden';
}
/* gallery */
function GAL_OrientChanged(link){
if (!isHorizO()){
ShowHideE('vertCover', 'block');
GoG(link);
}
setTimeout('window.scrollTo(0, 1)', 500);
}
function init_Portfolio() {
// if (!isHorizO())
// ShowHideE('vertCover', 'block');
}
function ShowPortfolios(){
if (isHorizO()) ShowHideE('vertCover', 'none');
}
var CurPos_G = 1
function MoveG(dir) {
MoveItem('G',CurPos_G, dir);
}
/* image */
function init_Image(){
// check for alone vertical images
PlaceAloneVertImages();
}
function Img_OrtChanged(){
//CompareOrientation(arImgOrt[CurPos_I]);
//setTimeout('window.scrollTo(0, 1)', 500);
}
var CurPos_I = 1
function MoveI(dir) {
CompareOrientation(arImgOrt[CurPos_I+dir]);
MoveItem('I',CurPos_I, dir);
}
var arImgOrt = new Array(); // orientation: 1-horizontal, 0-vertical
var aModeName = new Array('Horizontal' , 'Vertical');
var arHs = new Array();
function getDims(obj, ind){
var arT = new Array(2);
arT[0] = obj.height;
arT[1] = obj.width;
//arWs[ind-1] = arT;
arHs[ind] = arT[0];
//**** (arT[0] > arT[1]) = (vertical image=0)
arImgOrt[ind] = (arT[0] > arT[1])? 0 : 1;
// todor debug
if(DebugMode) {
//alert("["+obj.width+","+obj.height+"] mode="+((arT[0] > arT[1])? 'verical' : 'hoziontal'))
writeLog("["+obj.width+","+obj.height+"] mode="+((arT[0] > arT[1])? 'verical' : 'hoziontal')+' src='+obj.src)
}
if (arImgOrt[ind]) {
GE('mi'+ind).className = 'mImageH';
}
}
function CompareOrientation(imgOrt){
var iPhoneOrt = aModeName[isHorizO()];
GE('omode').innerHTML = iPhoneOrt;
//alert(imgOrt == isHorizO())
var sSH = (imgOrt == isHorizO())? 'none' : 'block';
ShowHideE('vertCover', sSH);
var sL = imgOrt? 'H' : 'V';
if (GE('navig')) GE('navig').className = 'navig'+ sL ;
if (GE('mainimage')) GE('mainimage').className = 'mainimage'+sL;
var sPfL = imgOrt? 'Port-<br>folios' : 'Portfolios' ;
if (GE('PortLnk')) GE('PortLnk').innerHTML = sPfL;
}
function SetGetDim( iMInd){
var dv = GE('IImg'+iMInd);
if (dv) {
var arI = dv.getElementsByTagName('img');
if (arI.length>0){
var oImg = arI[0];
oImg.id = 'Img'+iMInd;
oImg.className = 'imageStyle';
//YAHOO.util.Event.removeListener('Img'+iMInd,'load');
YAHOO.util.Event.on('Img'+iMInd, 'load', function(){GetDims(oImg,iMInd);}, true, true);
//oImg.addEventListener('load',GetDims(oImg,iMInd),true);
}
}
}
var occ = new Array();
function PlaceAloneVertImages(){
var iBLim, iELim;
iBLim = 0;
iELim = arImgOrt.length;
occ[0] = true;
//occ[iELim]=true;
for (i=1; i<iELim; i++){
if ( arImgOrt[i]){//horizontal image
occ[i]=true;
continue;
}else { // current is vertical
if (!occ[i-1]){//previous is free-alone. this happens only the first time width i=1
occ[i] = true;
continue;
}else {
if (i+1 == iELim){//this is the last image, it is alone and vertical
GE('mi'+i).className = 'mImageV_a'; //***** expand the image container
}else {
if ( arImgOrt[i+1] ){
GE('mi'+i).className = 'mImageV_a';//*****expland image container
occ[i] = true;
occ[i+1] = true;
i++;
continue;
}else { // second vertical image
occ[i] = true;
occ[i+1] = true;
if (arHs[i]>arHs[i+1]) GE('mi'+(i+1)).style.height = arHs[i]+'px';
i++;
continue;
}
}
}
}
}
//arImgOrt
}
function AdjustWebSiteTitle(){
//if (GE('wstitle')) if (GE('wstitle').offsetWidth > GE('wsholder').offsetWidth) {
if (GE('wstitle')) if (GE('wstitle').offsetWidth > 325) {
ShowHideE('dots1','block');
ShowHideE('dots2','block');
}
}
function getObjectsByClassName(className, eLTag, parent){
var oParent;
var arr = new Array();
if (parent) oParent = GE(parent); else oParent=document;
var elems = oParent.getElementsByTagName(eLTag);
for(var i = 0; i < elems.length; i++)
{
var elem = elems[i];
var cls = elem.className
if(cls == className){
arr[arr.length] = elem;
}
}
return arr;
}
////////////////////////////////
///
// todor debug
var DebugMode = (getQueryVariable("debug")=="1")
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
var sRet = ""
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if (pair[0] == variable) {
sRet = pair[1];
}
}
return sRet
//alert('Query Variable ' + variable + ' not found');
}
var oLogDiv=''
function writeLog(sMes){
if(!oLogDiv) oLogDiv=document.getElementById('oLogDiv')
if(!oLogDiv) {
oLogDiv = document.createElement("div");
oLogDiv.style.border="1px solid red"
var o = document.getElementsByTagName("body")
if(o.length>0) {
o[0].appendChild(oLogDiv)
}
}
if(oLogDiv) {
oLogDiv.innerHTML = sMes+"<br>"+oLogDiv.innerHTML
}
}
First, Firebug is your friend, get used to it. Second, if you paste each function and some supporting lines, one by one, you will eventually get to the following.
var DebugMode = (getQueryVariable("debug")=="1")
function getQueryVariable(variable)
You can't execute getQueryVariable before it is defined, you can create a handle to a future reference though, there is a difference.
There are several other potential issues in your code, but putting the var DebugMode line after the close of the getQueryVariable method should work fine.
It would help if you gave more context. For example, is
Failed to load source for:
http://localhost/js/m.js
the literal text of an error message? Where and when do you see it?
Also, does that code represent the contents of http://localhost/js/m.js? It seems that way, but it's hard to tell.
In any case, the JavaScript that you've shown has quite a few statements that are missing their semicolons. There may be other syntax errors as well. If you can't find them on your own, you might find tools such as jslint to be helpful.
make sure the type attribute in tag is "text/javascript" not "script/javascript".
I know it is more than a year since this question was asked, but I faced this today. I had a
<script type="text/javascript" src="/test/test-script.js"/>
and I was getting the 'Failed to load source for: http://localhost/test/test-script.js' error in Firebug. Even chrome was no loading this script. Then I modified the above line as
<script type="text/javascript" src="/test/test-script.js"></script>
and it started working both in Firefox and chrome. Documenting this here hoping that this will help someone. Btw, I dont know why the later works where as the previous one didn't.

Categories

Resources