I am trying to make a debugger that will be dynamiaclly created with some variables. The names on the left div need to show a div for the corresponding variables Description,Variable ID, and initial Value as well as another div that will show history and lock status when variables are updated later. Where I am having trouble is properly adding the show/hide to the dom I think. Everything starts hidden and then when I click a name the Variables for that name show up but the next click doesn't hide the values from the former. Also any cleanup/optimization advice?
<script type="text/javascript">
var variableIDArray = {};
function loadVariables(variables) {
if (typeof variables != "object") { alert(variables); return; }
var namearea = document.getElementById('namearea');
var description = document.getElementById('description');
var varid = document.getElementById('varid');
var initialvalue = document.getElementById('initialvalue');
var valuelock = document.getElementById('valuelock');
for (var i = 0; i < variables.length - 1; i++) {
var nameDiv = document.createElement('div');
nameDiv.id = variables[i].variableID + "namearea";
nameDiv.className = "nameDiv";
nameDiv.onclick = (function (varid) {
return function () { showvariable(varid); };
})(variables[i].variableID);
nameDiv.appendChild(document.createTextNode(variables[i].name));
namearea.appendChild(nameDiv);
var descriptionDiv = document.createElement('div');
descriptionDiv.id = variables[i].variableID + "description";
descriptionDiv.className = "descriptionDiv";
descriptionDiv.appendChild(document.createTextNode("Description : " + variables[i].description));
description.appendChild(descriptionDiv);
var varidDiv = document.createElement('div');
varidDiv.id = variables[i].variableID + "varid";
varidDiv.className = "varidDiv";
varidDiv.appendChild(document.createTextNode("Var ID : " + variables[i].variableID));
varid.appendChild(varidDiv);
var initialvalueDiv = document.createElement('div'); ;
initialvalueDiv.id = variables[i].variableID + "initialvalue";
initialvalueDiv.className = "initialvalueDiv";
initialvalueDiv.appendChild(document.createTextNode("Initial Value : " + variables[i].value));
initialvalue.appendChild(initialvalueDiv);
var valuelockDiv = document.createElement('div');
valuelockDiv.id = variables[i].variableID + "valuelock";
valuelockDiv.className = "valuelockDiv ";
valuelockDiv.appendChild(document.createTextNode("Value : " + variables[i].value));
valuelockDiv.appendChild(document.createTextNode("Lock : " + variables[i].locked.toString()));
valuelock.appendChild(valuelockDiv);
variableIDArray[variables[i].variableID];
}
};
function showvariable(varid) {
for (v in variableIDArray)
hide(variableIDArray[v]);
show(varid + "description");
show(varid + "varid");
show(varid + "initialvalue");
show(varid + "valuelock");
}
function show(elemid) {
document.getElementById(elemid).style.display = "block";
}
function hide(elemid) {
document.getElementById(elemid).style.display = "none";
}
Yes. jQuery. Will reduce your code to about 6 lines. :) http://jquery.com
Related
I have a server that collects data from 10 sources and constantly pushes JSON data to a webpage. The page uses JSON.Parse to get it into an object widgetData. The object widgetData has 10 properties that I want to display in the "widget".
So, the server is pushing WidgetData1, WidgetData2, etc..
For each widgetData, I want to create/instantiate a new widget and show the data. If widget1 exists, then update the widget. Also, the widgets should be sorted by some text property(e.g. widgetdata.name).
Here's what I've done so far, but the it doesn't seem that robust:
<script type="text/javascript">
var properties = ["MachineID", "p1","p2,"p3","p4"];
var currentWidget;
function CreateBlock(widgetData)
{
var widgetID = widgetData.MachineID.replace(/ /g,"_");
var myWidget = document.getElementById('widget-' + widgetID);
if (myWidget == null)
{
CreateCard(widgetID);
}
var currentDate = new Date();
var day = currentDate.getDay();
var month = currentDate.getMonth(); //Be careful! January is 0 not 1
var year = currentDate.getFullYear();
var hour = currentDate.getHours();
var min = currentDate.getMinutes();
var sec = currentDate.getSeconds();
var dateString = year + "-" + ZeroPad(month+1,2) + "-" + day + " " + ZeroPad(hour,2) + ":" + ZeroPad(min,2) + ":" + ZeroPad(sec,2);
var data;
for (let i = 0; i < properties.length; i++)
{
data = widgetData[properties[i]];
AddDataElement(widgetID,properties[i],data);
}
AddDataElement(widgetID,"Timestamp",dateString);
}
//create the card
function CreateCard(cardID)
{
var parent
var newdiv
var cardElement = document.createElement("div");
cardElement.className = "card";
cardElement.id = "widget-" + cardID;
cardElement.style = "height:500px;";
parent=cardElement;
newdiv = document.createElement("div");
newdiv.className = "card-header";
parent.appendChild(newdiv);
//parent=newdiv;
newdiv = document.createElement("div");
newdiv.className = "card-body";
newdiv.id = "cardbody";
parent.appendChild(newdiv);
parent=newdiv;
newdiv = document.createElement("div");
newdiv.className = "card-title";
newdiv.id = "title";
newdiv.textContent = "title";
parent.appendChild(newdiv);
newdiv = document.createElement("div");
newdiv.className = "card-sub-title";
newdiv.id = "subtitle";
newdiv.textContent = "subtitle";
parent.appendChild(newdiv);
newdiv = document.createElement("div");
parent.appendChild(newdiv);
//last add to the parent div
var parent = document.getElementById("Cards");
parent.appendChild(cardElement);
}
//Add a data element
function AddDataElement(machineID, title, value)
{
var cardElement = document.getElementById("widget-" + machineID);
var cardElementBody = findChild("widget-" + machineID, "cardbody");
var dataElement = findChild2(cardElementBody, title);
if (dataElement == null)
{
dataElement = document.createElement("div");
dataElement.id = title;
dataElement.className = "card-item";
}
dataElement.innerText = title + ": " + value;
cardElementBody.appendChild(dataElement);
}
function CreateElement(parentDivObject, childName)
{
var dataElement = document.createElement('DIV');
dataElement.id = childName;
dataElement.textContent = childName;
parentDivObject.appendChild(dataElement);
}
function findChild(idOfElement, idOfChild)
{
let element = document.getElementById(idOfElement);
return element.querySelector('[id=' + idOfChild + ']');
}
function findChild2(parentElement, idOfChild)
{
//let element = document.getElementById(idOfElement);
return parentElement.querySelector('[id=' + idOfChild + ']');
}
function ZeroPad(num, places)
{
var zero = places - num.toString().length + 1;
return Array(+(zero > 0 && zero)).join("0") + num;
}
</script>
<script type="text/javascript">
var widgetList = new Set(); //hold list of widgets
var start = function () {
var inc = document.getElementById('incomming');
var wsImpl = window.WebSocket || window.MozWebSocket;
var form = document.getElementById('sendForm');
var input = document.getElementById('sendText');
inc.innerHTML += "connecting to server ..<br/>";
// create a new websocket and connect
window.ws = new wsImpl('ws://localhost:8181/');
//when data is comming from the server, this method is called
//ws.onmessage = function (evt) {
// inc.innerHTML += evt.data + '<br/>';
//};
ws.onmessage = function (evt)
{
var machineStatus = JSON.parse(evt.data);
if (!widgetList.has(machineStatus.MachineID))
{
widgetList.add(machineStatus.MachineID)
}
CreateBlock(machineStatus)
}
// when the connection is established, this method is called
ws.onopen = function () {
inc.innerHTML += '.. connection open<br/>';
};
// when the connection is closed, this method is called
ws.onclose = function () {
inc.innerHTML += '.. connection closed<br/>';
}
form.addEventListener('submit', function(e){
e.preventDefault();
var val = input.value;
ws.send(val);
input.value = "";
});
}
window.onload = start;
</script>
What is an alternative, proper way, or best practice to accomplish this?
For an assignment i need to create a website which outputs mobile phone contracts based on the users preferences. I am currently stuck at the DOM part of the assignment.
I would like to output the results into a list, which i have managed to do, though i'm sure there's a better way to do it using less code.
This is what i have so far: https://jsfiddle.net/fn2ewtck/
The code i am trying to improve is this:
function search() {
var userBrandCtrl = document.getElementById("userBrand");
var userBrand = userBrandCtrl.value;
var userModelCtrl = document.getElementById("userModel");
var userModel = userModelCtrl.value;
var userNetworkCtrl = document.getElementById("userNetwork");
var userNetwork = userNetworkCtrl.value;
for (var i = 0; cont.length; i++) {
if (userBrand === cont[i].brand && userModel === cont[i].model && userNetwork === cont[i].network) {
var body = document.body;
var ulCont = document.createElement("ul");
var liBrand = document.createElement("li");
var liModel = document.createElement("li");
var liNetwork = document.createElement("li");
var liMins = document.createElement("li");
var liTexts = document.createElement("li");
var liData = document.createElement("li");
var liUpfront = document.createElement("li");
var liMonthly = document.createElement("li");
var liLength = document.createElement("li");
var textBrand = document.createTextNode("Brand: " + cont[i].brand);
var textModel = document.createTextNode("Model: " + cont[i].model);
var textNetwork = document.createTextNode("Network " + cont[i].network);
var textMins = document.createTextNode("Mins: " + cont[i].mins);
var textTexts = document.createTextNode("Texts: " + cont[i].texts);
var textData = document.createTextNode("Data: " + cont[i].data);
var textUpfront = document.createTextNode("Upfront: " + cont[i].upfront);
var textMonthly = document.createTextNode("Monthly: " + cont[i].monthly);
var textLength = document.createTextNode("Length: " + cont[i].length);
liBrand.appendChild(textBrand);
liModel.appendChild(textModel);
liNetwork.appendChild(textNetwork);
liMins.appendChild(textMins);
liTexts.appendChild(textTexts);
liData.appendChild(textData);
liUpfront.appendChild(textUpfront);
liMonthly.appendChild(textMonthly);
liLength.appendChild(textLength);
ulCont.appendChild(liBrand);
ulCont.appendChild(liModel);
ulCont.appendChild(liNetwork);
ulCont.appendChild(liMins);
ulCont.appendChild(liTexts);
ulCont.appendChild(liData);
ulCont.appendChild(liUpfront);
ulCont.appendChild(liMonthly);
ulCont.appendChild(liLength);
body.appendChild(ulCont);
}
}
};
How could i do this better?
Thanks.
You could create an array of the properties you want to display from the object and loop over them like this:
var arr = ['brand', 'model', 'network', 'mins']
for (i = 0; i < arr.length; i++) {
//Upercase first letter
var label = arr[i].charAt(0).toUpperCase() + arr[i].slice(1);
//create html elements
var li = document.createElement("li"),
text = document.createTextNode(label + ": " + cont[i][arr[i]]);
li.appendChild(text);
ulCont.appendChild(li);
}
//append to body after loop
body.appendChild(ulCont);
You should look at Backbone and Dust. They'll help you templatize the HTML you're trying to write.
Another angularJS question i have scope binding a click that should add one value on the first click ad another value on the second click but it just keeps returning and empty array and filling the first value again why? :
scope.dbclickalert = function (scope, $watch) {
var getCheckInDate = this.cellData.date;
var formatcheckindate = new Date(getCheckInDate);
var checkingdates = [];
var curr_datecell = formatcheckindate.getDate();
var padded_day = (curr_datecell < 10) ? '0' + curr_datecell : curr_datecell;
var curr_monthcell = formatcheckindate.getMonth() + 1;
var padded_month = (curr_monthcell < 10) ? '0' + curr_monthcell : curr_monthcell;
var curr_yearcell = formatcheckindate.getFullYear();
var date_stringcell = + padded_month + "/" + padded_day + "/" + curr_yearcell;
var checkindatestrg = "checkindate";
console.log(checkingdates.length);
if (checkingdates.length < 2) {
alert("element exists in array");
checkingdates.push('checkoutdate');
checkingdates.push(date_stringcell);
console.log(checkingdates + checkingdates.length);
} else {
checkingdates.push('checkindate');
checkingdates.push(date_stringcell);
}
var setCheckInDate = el.hasClass('checkInDate');
if (checkingdates === true) {
alert('You have allready set your check In Date');
} else {
el.addClass('checkInDate');
$('#checkoutbar').addClass('datePickerchecout');
}
$(".date-cell").each(function removeclasses() {
$(this).removeClass('true');
});
return getCheckInDate;
};
ok so when i declare this outside of the function i get undefined error:
scope.checkingdates = [];
scope.dbclickalert = function(scope, $watch){
var getCheckInDate = this.cellData.date;
var formatcheckindate = new Date(getCheckInDate);
var checkingdates = scope.checkingdates;
var curr_datecell = formatcheckindate.getDate();
var padded_day = (curr_datecell < 10) ? '0'+curr_datecell : curr_datecell;
var curr_monthcell = formatcheckindate.getMonth() + 1;
var padded_month = (curr_monthcell < 10) ? '0'+curr_monthcell : curr_monthcell;
var curr_yearcell = formatcheckindate.getFullYear();
var date_stringcell = + padded_month + "/" + padded_day + "/" + curr_yearcell;
var checkindatestrg = "checkindate";
console.log(checkingdates.length);
if (checkingdates.length < 2){
alert("element exists in array");
checkingdates.push('checkoutdate');
checkingdates.push(date_stringcell);
console.log(checkingdates+checkingdates.length);
}else{
checkingdates.push('checkindate');
checkingdates.push(date_stringcell);
}
var setCheckInDate = el.hasClass('checkInDate');
if (checkingdates === true){
alert('You have allready set your check In Date');
} else{
el.addClass('checkInDate');
$('#checkoutbar').addClass('datePickerchecout');
}
$(".date-cell").each(function removeclasses() {
$(this).removeClass('true');
});
return getCheckInDate;
};
ok in the third version of this it the same data "the date" again if the same div has been clicked but not if a second div with the same ng-click="dbclickalert()" is clicked why?
link: function(scope, el, attributes, dateSheetCtrl, $watch) {
scope.checkingdatesarry = [];
scope.dbclickalert = function(){
var getCheckInDate = this.cellData.date;
var formatcheckindate = new Date(getCheckInDate);
var checkingdates = scope.checkingdates;
var curr_datecell = formatcheckindate.getDate();
var padded_day = (curr_datecell < 10) ? '0'+curr_datecell : curr_datecell;
var curr_monthcell = formatcheckindate.getMonth() + 1;
var padded_month = (curr_monthcell < 10) ? '0'+curr_monthcell : curr_monthcell;
var curr_yearcell = formatcheckindate.getFullYear();
var date_stringcell = + padded_month + "/" + padded_day + "/" + curr_yearcell;
var checkindatestrg = "checkindate";
var checkoutdatestrg = "checkoutdate";
if( $.inArray('checkindate', scope.checkingdates) !== -1 ) {
scope.checkingdatesarry.push(checkoutdatestrg);
scope.checkingdatesarry.push(date_stringcell);
console.log(scope.checkingdatesarry + scope.checkingdatesarry.length);
}
else{
scope.checkingdatesarry.push(checkindatestrg);
scope.checkingdatesarry.push(date_stringcell);
console.log(scope.checkingdatesarry + scope.checkingdatesarry.length);
}
var setCheckInDate = el.hasClass('checkInDate');
if (scope.checkingdates === true){
alert('You have allready set your check In Date');
} else{
el.addClass('checkInDate');
$('#checkoutbar').addClass('datePickerchecout');
}
$(".date-cell").each(function removeclasses() {
$(this).removeClass('true');
});
return scope.checkingdatesarry;
};
ok for anyone that cares the answer was that because my div's where being created with a angularJS directive it was returning and array per div instead of one global array I have taken the array all the way out of the directive and moved it into a service and it works fine.
Because you redefined the array with empty list in the dbclickalert action. So every time when the action is triggered, the array will be empty.
var checkingdates = [];
You should move it outside the function and declare as
$scope.checkingdates = []; //In your code, you may use scope.checkingdates = []; if you renamed the $scope when you inject it
i got an anchor in the DOM and the following code replaces it with a fancy button. This works well but if i want more buttons it crashes. Can I do it without a for-loop?
$(document).ready(buttonize);
function buttonize(){
//alert(buttonAmount);
//Lookup for the classes
var button = $('a.makeabutton');
var buttonContent = button.text();
var buttonStyle = button.attr('class');
var link = button.attr('href');
var linkTarget = button.attr('target');
var toSearchFor = 'makeabutton';
var toReplaceWith = 'buttonize';
var searchButtonStyle = buttonStyle.search(toSearchFor);
if (searchButtonStyle != -1) {
//When class 'makeabutton' is found in string, build the new classname
newButtonStyle = buttonStyle.replace(toSearchFor, toReplaceWith);
button.replaceWith('<span class="'+newButtonStyle
+'"><span class="left"></span><span class="body">'
+buttonContent+'</span><span class="right"></span></span>');
$('.buttonize').click(function(e){
if (linkTarget == '_blank') {
window.open(link);
}
else window.location = link;
});
}
}
Use the each method because you are fetching a collection of elements (even if its just one)
var button = $('a.makeabutton');
button.each(function () {
var btn = $(this);
var buttonContent = btn.text();
var buttonStyle = btn.attr('class');
var link = btn.attr('href');
var linkTarget = btn.attr('target');
var toSearchFor = 'makeabutton';
var toReplaceWith = 'buttonize';
var searchButtonStyle = buttonStyle.search(toSearchFor);
...
};
the each method loops through all the elements that were retrieved, and you can use the this keyword to refer to the current element in the loop
var button = $('a.makeabutton');
This code returns a jQuery object which contains all the matching anchors. You need to loop through them using .each:
$(document).ready(buttonize);
function buttonize() {
//alert(buttonAmount);
//Lookup for the classes
var $buttons = $('a.makeabutton');
$buttons.each(function() {
var button = $(this);
var buttonContent = button.text();
var buttonStyle = button.attr('class');
var link = button.attr('href');
var linkTarget = button.attr('target');
var toSearchFor = 'makeabutton';
var toReplaceWith = 'buttonize';
var searchButtonStyle = buttonStyle.search(toSearchFor);
if (searchButtonStyle != -1) {
newButtonStyle = buttonStyle.replace(toSearchFor, toReplaceWith);
button.replaceWith('<span class="'
+ newButtonStyle
+ '"><span class="left"></span><span class="body">'
+ buttonContent
+ '</span><span class="right"></span></span>');
$('.buttonize').click(function(e) {
if (linkTarget == '_blank') {
window.open(link);
} else window.location = link;
}); // end click
} // end if
}); // end each
}
I have hacked this tab system together.
I need to reduce the spacing(padding) between each tab. When viewed in firebug, you can see the javascript function is adding various left pixels between each, but instead of random padding-left pixels I need padding-left: 100px between each tab. Any idea how I can do that?
Below is the javascript.
<script type="text/javascript">
var menuAlignment = 'left'; // Align menu to the left or right?
var topMenuSpacer = 0; // Horizontal space(pixels) between the main menu items
var activateSubOnClick = false; // if true-> Show sub menu items on click, if false, show submenu items onmouseover
var leftAlignSubItems = true; // left align sub items t
var activeMenuItem = false; // Don't change this option. It should initially be false
var activeTabIndex = 0; // Index of initial active tab (0 = first tab) - If the value below is set to true, it will override this one.
var rememberActiveTabByCookie = true; // Set it to true if you want to be able to save active tab as cookie
var MSIE = navigator.userAgent.indexOf('MSIE')>=0?true:false;
var Opera = navigator.userAgent.indexOf('Opera')>=0?true:false;
var navigatorVersion = navigator.appVersion.replace(/.*?MSIE ([0-9]\.[0-9]).*/g,'$1')/1;
/*
These cookie functions are downloaded from
http://www.mach5.com/support/analyzer/manual/html/General/CookiesJavaScript.htm
*/
function Get_Cookie(name) {
var start = document.cookie.indexOf(name+"=");
var len = start+name.length+1;
if ((!start) && (name != document.cookie.substring(0,name.length))) return null;
if (start == -1) return null;
var end = document.cookie.indexOf(";",len);
if (end == -1) end = document.cookie.length;
return unescape(document.cookie.substring(len,end));
}
// This function has been slightly modified
function Set_Cookie(name,value,expires,path,domain,secure) {
expires = expires * 60*60*24*1000;
var today = new Date();
var expires_date = new Date( today.getTime() + (expires) );
var cookieString = name + "=" +escape(value) +
( (expires) ? ";expires=" + expires_date.toGMTString() : "") +
( (path) ? ";path=" + path : "") +
( (domain) ? ";domain=" + domain : "") +
( (secure) ? ";secure" : "");
document.cookie = cookieString;
}
function showHide()
{
if(activeMenuItem){
activeMenuItem.className = 'inactiveMenuItem';
var theId = activeMenuItem.id.replace(/[^0-9]/g,'');
document.getElementById('submenu_'+theId).style.display='none';
var img = activeMenuItem.getElementsByTagName('IMG');
if(img.length>0)img[0].style.display='none';
}
var img = this.getElementsByTagName('IMG');
if(img.length>0)img[0].style.display='inline';
activeMenuItem = this;
this.className = 'activeMenuItem';
var theId = this.id.replace(/[^0-9]/g,'');
document.getElementById('submenu_'+theId).style.display='block';
if(rememberActiveTabByCookie){
Set_Cookie('dhtmlgoodies_tab_menu_tabIndex','index: ' + (theId-1),100);
}
}
function initMenu()
{
var mainMenuObj = document.getElementById('mainMenu');
var menuItems = mainMenuObj.getElementsByTagName('A');
if(document.all){
mainMenuObj.style.visibility = 'hidden';
document.getElementById('submenu').style.visibility='hidden';
}
if(rememberActiveTabByCookie){
var cookieValue = Get_Cookie('dhtmlgoodies_tab_menu_tabIndex') + '';
cookieValue = cookieValue.replace(/[^0-9]/g,'');
if(cookieValue.length>0 && cookieValue<menuItems.length){
activeTabIndex = cookieValue/1;
}
}
var currentLeftPos = 1;
for(var no=0;no<menuItems.length;no++){
if(activateSubOnClick)menuItems[no].onclick = showHide; else menuItems[no].onmouseover = showHide;
menuItems[no].id = 'mainMenuItem' + (no+1);
if(menuAlignment=='left')
menuItems[no].style.left = currentLeftPos + 'px';
else
menuItems[no].style.right = currentLeftPos + 'px';
currentLeftPos = currentLeftPos + menuItems[no].offsetWidth + topMenuSpacer;
var img = menuItems[no].getElementsByTagName('IMG');
if(img.length>0){
img[0].style.display='none';
if(MSIE && !Opera && navigatorVersion<7){
img[0].style.bottom = '-1px';
img[0].style.right = '-1px';
}
}
if(no==activeTabIndex){
menuItems[no].className='activeMenuItem';
activeMenuItem = menuItems[no];
var img = activeMenuItem.getElementsByTagName('IMG');
if(img.length>0)img[0].style.display='inline';
}else menuItems[no].className='inactiveMenuItem';
if(!document.all)menuItems[no].style.bottom = '-1px';
if(MSIE && navigatorVersion < 6)menuItems[no].style.bottom = '-2px';
}
var mainMenuLinks = mainMenuObj.getElementsByTagName('A');
var subCounter = 1;
var parentWidth = mainMenuObj.offsetWidth;
while(document.getElementById('submenu_' + subCounter)){
var subItem = document.getElementById('submenu_' + subCounter);
if(leftAlignSubItems){
// No action
}else{
var leftPos = mainMenuLinks[subCounter-1].offsetLeft;
document.getElementById('submenu_'+subCounter).style.paddingLeft = LeftPos + 'px';
subItem.style.position ='absolute';
if(subItem.offsetWidth > parentWidth){
leftPos = leftPos - Math.max(0,subItem.offsetWidth-parentWidth);
}
subItem.style.paddingLeft = leftPos + 'px';
subItem.style.position ='static';
}
if(subCounter==(activeTabIndex+1)){
subItem.style.display='block';
}else{
subItem.style.display='none';
}
subCounter++;
}
if(document.all){
mainMenuObj.style.visibility = 'visible';
document.getElementById('submenu').style.visibility='visible';
}
document.getElementById('submenu').style.display='block';
}
window.onload = initMenu;
</script>
I don't want to put down your effort, but your solution looks very complicated, feels slow on a 3Ghz dual-core workstation, throws a lot of Javascript errors and, as your question illustrates, makes customization very difficult. I'm not sure this is the way to go - I find it hard to dig into the script to even find the place to make the change you want to make.
Why not, for example, use something pre-built and small like the old but mostly reliable framework-agnostic DOMTab?
There is a great number of tab scripts based on the popular frameworks as well, see e.g. here.