My current code is directly below. Everything works except my button function.
The one line that is giving me issues is the
var tesbut = new onclickfunc(buttons[g], 'testbuttloc');
line. I believe this is because I cannot make the buttons[g] into an HTMLButtonElement which is why I have this line.
buttons[g].setAttribute("type", "HTMLButtonElement");
I believe that I need the line directly above because whenever I use
var tesbut = new onclickfunc(testbutt, 'testbuttloc');
it works. (These are the names of the variables that are declared in XML) So, is there any advice?
var buttons = [];
var subbuttons = [];
for(var mainsplunkcount = 0; mainsplunkcount<mx.length; mainsplunkcount++){
buttons[mainsplunkcount] = mx[mainsplunkcount].getElementsByTagName("BUTTON")[0].childNodes[0].nodeValue;
subbuttons[mainsplunkcount] =mx[mainsplunkcount].getElementsByTagName("BUTTONLOC")[0].childNodes[0].nodeValue;
mainnewstat.id = mainstatus[mainsplunkcount];
$("<div />", { "class":"Main_Category", id:"product"+group[mainsplunkcount] })
$("<button />", { id:buttons[mainsplunkcount] })
//divs that work
.append($('</button>'))
.append($('</div>'))
.appendTo(main_sort[mainsplunkcount]);
$("<div />", { id:subbuttons[mainsplunkcount], "class" : "hidden"})
.append($('<div class="group"><font size="2">' + maingroup[mainsplunkcount] + '</div></div>'))
.append($('</div>'))
.appendTo(main_sort[mainsplunkcount]);
}
//dropdown for submenus of menus
var onclickfunc = function(button, newpost){
button.onclick = function(){
var div = document.getElementById(newpost);
if(div.style.display !== 'none'){
div.style.display = 'none';
} else{
div.style.display = 'inline';
}
};
};
for(var g = 0; g<mx.length; g++){
buttons[g].setAttribute("type", "HTMLButtonElement");
var tesbut = new onclickfunc(buttons[g], 'testbuttloc');
}
XML code
<MAINCONTAINER>
<GROUP>Test</GROUP>
<INOUT>test</INOUT>
<CRITICALITY>test</CRITICALITY>
<CALLNUMBER>6</CALLNUMBER>
<LOCATION>sortAll5</LOCATION>
<STATUSNAME>testt</STATUSNAME>
<BUTTON>testbutt</BUTTON>
<BUTTONLOC>testbuttloc</BUTTONLOC>
Related
I have a loop in which I am calling rec_append() recursively, apparently the first pass alone works, then the loop stops.
I have an array of 4 elements going into that $.each loop but I see only the first element going into the function recursively. Help!
I switched it for a element.forEach but that gives me only the second element and I am stuck, is there a better solution to process a tree of elements? My array is a part of a tree.
var data = JSON.parse(JSON.stringify(result))
var graph = $(".entry-point");
function rec_append(requestData, parentDiv) {
var temp_parent_details;
$.each(requestData, function (index, jsonElement) {
if (typeof jsonElement === 'string') {
//Element construction
//Name and other details in the form of a : delimited string
var splitString = jsonElement.split(':');
var details = document.createElement("details");
var summary = document.createElement("summary");
summary.innerText = splitString[0];
details.append(summary);
temp_parent_details = details;
parentDiv.append(details);
var kbd = document.createElement("kbd");
kbd.innerText = splitString[1];
summary.append(' ');
summary.append(kbd);
var div = document.createElement("div");
div.className = "col";
details.append(div);
var dl = document.createElement("dl");
div.append(dl);
var dt = document.createElement("dt");
dt.className = "col-sm-1";
dt.innerText = "Path";
div.append(dt);
var dd = document.createElement("dd");
dd.className = "col-sm-11";
dd.innerText = splitString[2];
div.append(dd);
var dt2 = document.createElement("dt");
dt2.className = "col-sm-1";
dt2.innerText = "Type";
div.append(dt2);
var dd2 = document.createElement("dd");
dd2.className = "col-sm-11";
dd2.innerText = splitString[1];
div.append(dd2);
} else {
$.each(jsonElement, function (jsonElementArrIndx, jsonChildElement) {
rec_append(jsonChildElement, temp_parent_details); //Only 1 pass works, rest skip
});
}
});
}
rec_append(data, graph);
Sample data:enter image description here
On my page I have two buttons, button 1 and button 2. Under those buttons I want to get the value of a javascript per button, so that I can switch the javascript per button. I am a beginner and I can really use some help for this :) I have tried everything that is possible at my knowledge level. I searched on Stack but didn't find anything close to what I needed. Hopefully you can help me.
EDIT: Ive updated my snippet. Now one button is working en de graph is coming. When i push the second button nothing happens.
function myFunction1() {
var x = document.getElementById('3d-graph');
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
function myFunction2() {
var x = document.getElementById('graph');
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
var elem = document.getElementById("graph");
var drivertwo = neo4j.v1.driver("bolt+routing://90bfd895.databases.neo4j.io", neo4j.v1.auth.basic("got", "got"),{encrypted: true});
var sessiontwo = drivertwo.session();
var starttwo = new Date()
sessiontwo
.run('MATCH (n)-[r]->(m) RETURN { id: id(n), label:head(labels(n)), community:n.title, caption:n.title, size:n.title } as source, { id: id(m), label:head(labels(m)), community:n.title, caption:m.title, size:m.title } as target, { weight:r.title, type:type(r), community:case when n.title < m.title then n.title else m.title end} as rel LIMIT $limit', {limit: 1000})
.then(function (result) {
var nodes = {}
var links = result.records.map(r => {
var source = r.get('source');source.id = source.id.toNumber();
nodes[source.id] = source;
var target = r.get('target');target.id = target.id.toNumber();
nodes[target.id] = target;
var rel = r.get('rel'); if (rel.weight) { rel.weight = rel.weight.toNumber(); }
return Object.assign({source:source.id,target:target.id}, rel);
});
sessiontwo.close();
console.log(links.length+" links loaded in "+(new Date()-starttwo)+" ms.")
var gData = { nodes: Object.values(nodes), links: links}
var Graph = ForceGraph()(elem)
.graphData(gData)
.nodeAutoColorBy('label')
.linkDirectionalParticles('weight')
.linkDirectionalParticleSpeed(0.001)
.nodeLabel(node => `${node.label}: ${node.caption}`)
.onNodeHover(node => elem.style.cursor = node ? 'pointer' : null);
});
var elem = document.getElementById('3d-graph');
var driver = neo4j.v1.driver("bolt+routing://90bfd895.databases.neo4j.io", neo4j.v1.auth.basic("got", "got"),{encrypted: true});
var session = driver.session();
var start = new Date()
session
.run('MATCH (n)-[r]->(m) RETURN { id: id(n), label:head(labels(n)), community:n.title, caption:n.title, size:n.title } as source, { id: id(m), label:head(labels(m)), community:n.title, caption:m.title, size:m.title } as target, { weight:r.title, type:type(r), community:case when n.title < m.title then n.title else m.title end} as rel LIMIT $limit', {limit: 1000})
.then(function (result) {
var nodes = {}
var links = result.records.map(r => {
var source = r.get('source');source.id = source.id.toNumber();
nodes[source.id] = source;
var target = r.get('target');target.id = target.id.toNumber();
nodes[target.id] = target;
var rel = r.get('rel'); if (rel.weight) { rel.weight = rel.weight.toNumber(); }
return Object.assign({source:source.id,target:target.id}, rel);
});
session.close();
console.log(links.length+" links loaded in "+(new Date()-start)+" ms.")
var gData = { nodes: Object.values(nodes), links: links}
var Graph = ForceGraph3D()(elem)
.graphData(gData)
.nodeAutoColorBy('label')
.linkDirectionalParticles('weight')
.linkDirectionalParticleSpeed(0.001)
.nodeLabel(node => `${node.label}: ${node.caption}`)
.onNodeHover(node => elem.style.cursor = node ? 'pointer' : null);
});
<script src="https://unpkg.com/force-graph"></script>
<script src="https://unpkg.com/3d-force-graph"></script>
<script src="https://cdn.rawgit.com/neo4j/neo4j-javascript-driver/1.2/lib/browser/neo4j-web.min.js"></script>
<button onclick="myFunction1()">Try it</button>
<button onclick="myFunction2()">Try it</button>
<p id="graph"></p>
<p id="3d-graph"></p>
The buttons work correctly. The reason you don't see one of the images is that you declared var elem twice.
If you replace elem by elem2 in var elem = document.getElementById('3d-graph'); and in the code below that, then it will be fixed.
But it would be better to wrap the image loading in a separate function, like this:
function loadImage(elementId) {
var elem = document.getElementById(elementId);
...
...
}
and then call this function twice:
loadImage('graph');
loadImage('3d-graph');
try this and let me know if there are other problems:
<button id='1' onclick="myFunction(this)">button 1</button>
<button id='2' onclick="myFunction(this)">button 2</button>
<p id="graph"></p>
<p id="3d-graph"></p>
Passing "this" to myFunction, the "elem", will be the button you click.
Remember that is better to use .addEventListener('click', function(ev){}) instead "onclick=function()"
function myFunction(elem) {
document.getElementById("graph").innerHTML = "ID:" + elem.id;
document.getElementById("3d-graph").innerHTML = "ID:" + elem.id;
}
I don't know what the code below what the rest of the code will do, and if it works, but i see a lot of duplications. If you can, try to put all the neo4j call inside a function, so that you can use this every time you need it.
I developed the store locator using open street map and leaflet. The problem is when I want to type in searchbox it will become lagging to finish the word. That store locator read from the CSV file that has 300++ data. Below is the code for the searchbox:
var locationLat = [];
var locationLng = [];
var locMarker;
var infoDiv = document.getElementById('storeinfo');
var infoDivInner = document.getElementById('infoDivInner');
var toggleSearch = document.getElementById('searchIcon');
var hasCircle = 0;
var circle = [];
//close store infor when x is clicked
var userLocation;
$("#infoClose").click(function() {
$("#storeinfo").hide();
if (map.hasLayer(circle)) {
map.removeLayer(circle);
}
});
var listings = document.getElementById('listingDiv');
var stores = L.geoJson().addTo(map);
var storesData = omnivore.csv('assets/data/table_1.csv');
function setActive(el) {
var siblings = listings.getElementsByTagName('div');
for (var i = 0; i < siblings.length; i++) {
siblings[i].className = siblings[i].className
.replace(/active/, '').replace(/\s\s*$/, '');
}
el.className += ' active';
}
function sortGeojson(a,b,prop) {
return (a.properties.name.toUpperCase() < b.properties.name.toUpperCase()) ? -1 : ((a.properties.name.toUpperCase() > b.properties.name.toUpperCase()) ? 1 : 0);
}
storesData.on('ready', function() {
var storesSorted = storesData.toGeoJSON();
//console.log(storesSorted);
var sorted = (storesSorted.features).sort(sortGeojson)
//console.log(sorted);
storesSorted.features = sorted;
//console.log(storesSorted)
stores.addData(storesSorted);
map.fitBounds(stores.getBounds());
toggleSearch.onclick = function() {
//var s = document.getElementById('searchbox');
//if (s.style.display != 'none') {
//s.style.display = 'yes';
//toggleSearch.innerHTML = '<i class="fa fa-search"></i>';
//$("#search-input").val("");
//search.collapse();
//document.getElementById('storeinfo').style.display = 'none';
//$('.item').show();
//} else {
//toggleSearch.innerHTML = '<i class="fa fa-times"></i>';
//s.style.display = 'block';
//attempt to autofocus search input field when opened
//$('#search-input').focus();
//}
};
stores.eachLayer(function(layer) {
//New jquery search
$('#searchbox').on('change paste keyup', function() {
var txt = $('#search-input').val();
$('.item').each(function() {
if ($(this).text().toUpperCase().indexOf(txt.toUpperCase()) != -1) {
$(this).show();
} else {
$(this).hide();
}
});
});
I dont know what is the cause of the lag in the search box. It is something wrong in code or the csv file? Thank you
Every iteration of $('.item').each is causing a layout change because $(this).hide() or $(this).show() causes the item to removed/added to the DOM as the style is set to display:none back and forth. DOM manipulations and the corresponding layout changes are expensive.
You can consider accumulating the changes and doing one batch update to the DOM using a function like appendChild
I have created an application where elements from the toolbox can be dragged and dropped onto a canvas and their properties can be set as soon as they are dropped. But, I have an instance where when the "stream ui-draggable" element is dropped on the canvas I disable the canvas and the toolbox and display a properties panel where the user can select a predefined stream for the newly dropped element and also give it another name under the "as : " text field. This name should then replace the currently displayed- disabled name "Element" with the name provided bu the user. Is there a way that I can replace this text in the dropped element.
js function:
drop: function (e, ui) {
var dropElem = ui.draggable.attr('class');
droppedElement = ui.helper.clone();
ui.helper.remove();
$(droppedElement).removeAttr("class");
jsPlumb.repaint(ui.helper);
if(dropElem=="stream ui-draggable")
{
var newAgent = $('<div>').attr('id', i).addClass('streamdrop');
//alert("newAgent ID: "+newAgent.attr('id'));
clickedId = newAgent.attr("id");
alert("clicked ID: "+i);
createStreamForm();
$("#container").addClass("disabledbutton");
$("#toolbox").addClass("disabledbutton");
$(droppedElement).draggable({containment: "container"});
var prop = $('<a class="streamproperty" onclick="doclick(this)"><b><img src="../Images/settings.png"></b></a> ').attr('id', (i));
var finalElement= newAgent.text("Element").append('<a class="boxclose" id="boxclose"><b><img src="../Images/Cancel.png"></b></a> ').append(prop);
//Increment the Element sequence number
i++; r++; q++;
var l = ($(finalElement).attr('id'));
alert("Final elm id: "+finalElement.attr('id'));
var connection = $('<div>').attr('id', l + '-' + q).addClass('connection');
finalElement.css({
'top': e.pageY,
'left': e.pageX
});
finalElement.append(connection);
$('#container').append(finalElement);
jsPlumb.draggable(finalElement, {
containment: 'parent'
});
jsPlumb.makeTarget(connection, {
anchor: 'Continuous'
});
jsPlumb.makeSource(connection, {
anchor: 'Continuous'
});
}
The createStreamForm() function:
var importDiv, iStreamtype, br, istreamlbl, istreamtypelbl, iPredefStreamdiv, istreamDefLineDiv, istreamDefDivx, istreamName, importbtn;
var exportDiv,eStreamtype, estreamlbl, estreamtypelbl, ePredefStreamdiv, estreamDefLineDiv, estreamDefDivx, estreamName, exportbtn;
var streamDiv, streambtn;
var definestreamdiv,inputval;
function createStreamForm()
{
$(".toolbox-titlex").show();
$(".panel").show();
//For the Import Form
importDiv = document.createElement("div");
iStreamtype = document.createElement("div");
br = document.createElement("br");
istreamlbl = document.createElement("label");
istreamtypelbl = document.createElement("label");
iPredefStreamdiv = document.createElement("div");
istreamDefLineDiv = document.createElement("div");
istreamDefDivx = document.createElement("div");
istreamName = document.createElement("input");
importbtn = document.createElement("button");
importDiv.className = "importdiv";
importDiv.id = "importdiv";
istreamlbl.className = "lblfloat-left";
br.className = "br-div";
istreamlbl.innerHTML = "Stream:";
iPredefStreamdiv.id = "PredefinedStream1";
istreamDefDivx.className = "streamDefDiv";
istreamDefDivx.id = "streamDefLineDiv";
istreamName.className = "panel-input-streamName";
istreamName.id = "istreamName";
istreamName.placeholder = "as : ";
importbtn.type = 'button';
importbtn.innerHTML = "Import";
importbtn.className = "btn-import";
importbtn.setAttribute("onclick","storeImportStreamInfo()");
importDiv.appendChild(iStreamtype);
importDiv.appendChild(istreamlbl);
importDiv.appendChild(istreamtypelbl);
importDiv.appendChild(iPredefStreamdiv);
importDiv.appendChild(br);
importDiv.appendChild(istreamDefLineDiv);
importDiv.appendChild(istreamDefDivx);
importDiv.appendChild(br);
importDiv.appendChild(istreamName);
importDiv.appendChild(br);
importDiv.appendChild(importbtn);
importDiv.appendChild(br);
//For the Export Form
exportDiv = document.createElement("div");
eStreamtype = document.createElement("div");
br = document.createElement("br");
estreamlbl = document.createElement("label");
estreamtypelbl = document.createElement("label");
ePredefStreamdiv = document.createElement("div");
estreamDefLineDiv = document.createElement("div");
estreamDefDivx = document.createElement("div");
estreamName = document.createElement("input");
exportbtn = document.createElement("button");
exportDiv.className = "exportdiv";
exportDiv.id = "exportdiv";
estreamlbl.className = "lblfloat-left";
estreamlbl.innerHTML = "Stream:";
ePredefStreamdiv.id = "PredefinedStream2";
estreamDefDivx.className = "streamDefDiv";
estreamDefDivx.id = "streamDefLineDiv";
estreamName.className = "panel-input-streamName";
estreamName.id = "panel-input-streamName";
estreamName.placeholder = "as : ";
exportbtn.type = 'button';
exportbtn.innerHTML = "Export";
exportbtn.className = "btn-export";
exportDiv.appendChild(estreamlbl);
exportDiv.appendChild(estreamtypelbl);
exportDiv.appendChild(ePredefStreamdiv);
exportDiv.appendChild(br);
exportDiv.appendChild(estreamDefLineDiv);
exportDiv.appendChild(estreamDefDivx);
exportDiv.appendChild(br);
exportDiv.appendChild(estreamName);
exportDiv.appendChild(br);
exportDiv.appendChild(exportbtn);
exportDiv.appendChild(br);
//For the Stream Form
streamDiv = document.createElement("div");
streambtn = document.createElement("button");
definestreamdiv = document.createElement("div");
inputval = document.createElement("div");
streambtn.type = 'button';
streamDiv.className = "streamdiv";
streamDiv.id = "streamdiv";
streambtn.innerHTML = "Define Stream";
streambtn.className = "btn-define-stream";
streambtn.setAttribute("onclick","createattribute()");
//inputval.innerHTML = "Provide a Stream name and click to add attribute-type pairs to yours stream.";
streamDiv.appendChild(streambtn);
definestreamdiv.appendChild(inputval);
lot.appendChild(importDiv);
createattr();
lot.appendChild(exportDiv);
lot.appendChild(streamDiv);
lot.appendChild(definestreamdiv);
}
storeImportStreamInfo() Function:
var clickcount=1;
function storeImportStreamInfo()
{
var choice=document.getElementById("streamSelect");
var selectedStream = choice.options[choice.selectedIndex].text;
var asName= document.getElementById("istreamName").value;
var StreamElementID = clickcount;
clickcount++;
createdImportStreamArray[clickedId][0]=StreamElementID;
createdImportStreamArray[clickedId][1]=selectedStream;
createdImportStreamArray[clickedId][2]=asName;
y++;
}
Solved it by passing the newly dropped jsPlumb object to the storeImportStreamInfo() as parameters and set the text within the method. Also this parameter needs to be carried through all the functions through which it progresses before achieving the storeImportStreamInfo() method.
Eg:
function createStreamForm(newAgent,i)
within this function->
importbtn.onclick = function() {
storeImportStreamInfo(newAgent,i);
}
and so on. In the storeImportStreamInfo() function, I've added the lines that append the icons and the text to the dropped Element.
var prop = $('<a class="streamproperty" onclick="doclick(this)"><b><img src="../Images/settings.png"></b></a> ').attr('id', (i));
newAgent.text(asName).append('<a class="boxclose" id="boxclose"><b><img src="../Images/Cancel.png"></b></a> ').append(prop);
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
}