How to add a custom right click menu into my bokeh code? - javascript

I obtained a graph in which many nodes are there in the node I have to create a custom menu after clicking right click. SO in my code what should I add so that instead of normal menu my own custom value should come?
Here I have a bokeh code which will generate the nodes. I have included the HTML v=block for my custom right click that is working correctly. So how can I integrate the HTML script into my bokeh code? HTML code is also present under the bokeh code.
MY CODE
'''Bokeh'''
plot_width = 1400
plot_height= 900
#Add the addtributes of the node
nx.set_node_attributes(G, node_size, name='node_size')
nx.set_node_attributes(G, node_color, name='node_color')
nx.set_node_attributes(G, label_name_hover, name='lable_hover')
nx.set_node_attributes(G, label_hover_2, name='label_hover_2')
source = ColumnDataSource(pd.DataFrame.from_dict({k:v for k,v in G.nodes(data=True)}, orient='index'))
plot = Plot(plot_width=plot_width, plot_height=plot_height,
x_range=Range1d(-1.1,1.1), y_range=Range1d(-1.1,1.1),
min_border_bottom=0, min_border_top=0)
#Add Network Graph to bokeh and define the fixed positions
graph_renderer = from_networkx(G, nx.spring_layout, pos = new_pos)
plot.add_tools(TapTool(), BoxSelectTool())
#Lable Hover
# plot.add_tools(HoverTool(tooltips='#lable_hover'))
import jinja2 '''This html code I have to embed under the bokeh code so that it will work'''
from bokeh.embed import components
template = jinja2.Template("""
<!doctype html>
<html>
<head>
<script>
src="http://cdn.pydata.org/bokeh/dev/bokeh-0.13.0.min.js"
var menuDisplayed = false;
var menuBox = null;
window.addEventListener("contextmenu", function() {
var left = arguments[0].clientX;
var top = arguments[0].clientY;
menuBox = window.document.querySelector(".menu");
menuBox.style.left = left + "px";
menuBox.style.top = top + "px";
menuBox.style.display = "block";
arguments[0].preventDefault();
menuDisplayed = true;
}, false);
window.addEventListener("click", function() {
if(menuDisplayed == true){
menuBox.style.display = "none";
}
}, true);
</script>
<style>
.menu
{
width: 150px;
box-shadow: 3px 3px 5px #888888;
border-style: solid;
border-width: 1px;
border-color: grey;
border-radius: 2px;
padding-left: 5px;
padding-right: 5px;
padding-top: 3px;
padding-bottom: 3px;
position: fixed;
display: none;
}
.menu-item
{
height: 20px;
}
.menu-item:hover
{
background-color: #6CB5FF;
cursor: pointer;
}
</style>
</head>
<body>
<div class="menu">
<div class="menu-item">Add Node</div>
<div class="menu-item">Delete Node</div>
<div class="menu-item">Update Node</div>
</div>
</body>
</html>
""")
plot.add_tools(HoverTool(tooltips="""
<div>
</script>
<span id="doc" style="font-size: 12px; font-weight: bold; color:green;">#lable_hover</span>
<br><span style="font-size: 12px; color: blue;">#label_hover_2</span>
</div>
"""))
graph_renderer.node_renderer.data_source = source
graph_renderer.node_renderer.glyph = Circle(size='node_size', fill_color='node_color')
graph_renderer.node_renderer.hover_glyph = Circle(size=15, fill_color='yellow')
graph_renderer.edge_renderer.glyph = MultiLine(line_color="#000000", line_alpha=0.5, line_width=0.5)
graph_renderer.edge_renderer.selection_glyph = MultiLine(line_color='red', line_width=1)
graph_renderer.edge_renderer.hover_glyph = MultiLine(line_color='deeppink', line_width=1)
graph_renderer.selection_policy = NodesAndLinkedEdges()
# graph_renderer.inspection_policy = EdgesAndLinkedNodes()
#Fix layout positions
graph_renderer.layout_provider = StaticLayoutProvider(graph_layout=new_pos)
plot.renderers.append(graph_renderer)
#Below part is to Get node positions
x, y = zip(*graph_renderer.layout_provider.graph_layout.values())
x = list(x)
y = list(y)
x = dict(zip(G.nodes, x))
y= dict(zip(G.nodes, y))
nx.set_node_attributes(G, x, name='x')
nx.set_node_attributes(G, y, name='y')
node_source = ColumnDataSource(pd.DataFrame.from_dict({k:v for k,v in G.nodes(data=True)}))
plot.background_fill_color = 'beige'
plot.background_fill_alpha = 0.5
tab_1 = Panel(child=plot, title = "Lexical Chains")
tabs = Tabs(tabs=[tab_1], sizing_mode = 'stretch_both')
output_file('lexical_graph_2.html')
show(tabs)

Related

'backgroundColor' not working with javascript

I'm creating a tab menu like this:
function clear_selected() //sets all columns color black
{
var parent = document.querySelector("#container")
var items = document.querySelectorAll(".item")
var n = items.length;
for (var i = 0; i < n; i++)
items[i].style.backgroundColor = "";
}
function plus(itself) //adds another column
{
var parent = itself.parentElement;
var n = parent.childElementCount;
clear_selected();
var n = parent.querySelectorAll(".item").length;
var page = document.createElement("button");
page.className = "item";
page.style.backgroundColor = "blue";
page.textContent = "column"
page.onclick = function() {
clear_selected();
this.style.backgroundColor = "blue";
};
var temp = document.createElement("span");
temp.className = "del"
temp.innerHTML = "×"
temp.onclick = function() { //it's suppose to remove a column and color default as blue
document.querySelector("#main_item").style.backgroundColor = "blue" //THIS LINE ISN'T WORKING
this.parentElement.remove();
};
page.appendChild(temp);
parent.insertBefore(page, parent.childNodes[n]);
}
function see(el) {
clear_selected();
el.style.backgroundColor = "blue";
}
#container {
display: flex;
width: 100%;
height: 50px;
text-align: center;
background-color: yellow;
}
.item {
background-color: black;
color: white;
border: none;
outline: none;
cursor: pointer;
margin: 0.1rem;
padding: 0.1rem;
max-width: 100%;
}
.del {
background-color: red;
display: inline-block;
cursor: pointer;
border-radius: 50%;
width: 0.7rem;
margin-left: 2rem;
}
<div id="container">
<button class="item" id="main_item" style="background-color:blue;" onclick="see(this)">default column </button>
<button class="item" onclick="plus(this)">+</button>
</div>
but when I press the 'x' to remove a column, I want the default column to color blue, but the line of code which is suppose to achieve that isn't working
document.querySelector("#main_item").style.backgroundColor = "blue"
Before pressing 'x':
After pressing 'x' on the last column:
What it SHOULD look like:
I've losing sleep over this, can someone PLEASE tell me why isn't it working?
When you click on the "X", both of your onclick handlers are getting called, including the one that runs clear_selected, which sets the background color to "".
You can fix this by using stopPropagation on the event passed into the onclick function for the "x". That will stop the click event from going up the chain to the parent element of the "x".
temp.onclick = function(e) {
document.querySelector("#main_item").style.backgroundColor = "blue"
this.parentElement.remove();
e.stopPropagation();
};

How to link HTML Element with Python function in Jupyter notebook?

I've written JavaScript code that shows a custom right click menu.
I'd like to know how to trigger Python functions upon my menu items being clicked. These menu items are the divs nested under the div with the class of menu, which consequently is the only element in the body section of my HTML.
The environment I'm using is Jupyter Notebook.
notebook.
import jinja2
from bokeh.embed import components
template = jinja2.Template("""
<!doctype html>
<html>
<head>
<script>
src="http://cdn.pydata.org/bokeh/dev/bokeh-0.13.0.min.js"
var menuDisplayed = false;
var menuBox = null;
window.addEventListener("contextmenu", function() {
var left = arguments[0].clientX;
var top = arguments[0].clientY;
menuBox = window.document.querySelector(".menu");
menuBox.style.left = left + "px";
menuBox.style.top = top + "px";
menuBox.style.display = "block";
arguments[0].preventDefault();
menuDisplayed = true;
}, false);
window.addEventListener("click", function() {
if(menuDisplayed == true){
menuBox.style.display = "none";
}
}, true);
</script>
<style>
.menu
{
width: 150px;
box-shadow: 3px 3px 5px #888888;
border-style: solid;
border-width: 1px;
border-color: grey;
border-radius: 2px;
padding-left: 5px;
padding-right: 5px;
padding-top: 3px;
padding-bottom: 3px;
position: fixed;
display: none;
}
.menu-item
{
height: 20px;
}
.menu-item:hover
{
background-color: #6CB5FF;
cursor: pointer;
}
</style>
</head>
<body>
<div class="menu">
<div class="menu-item">Add Node</div>
<div class="menu-item">Delete Node</div>
<div class="menu-item">Update Node</div>
</div>
</body>
</html>
""")
I think you will get clear understanding and clarity on this with below example easily:
// %%javascript
window.executePython = function(python) {
return new Promise((resolve, reject) => {
var callbacks = {
iopub: {
output: (data) => resolve(data.content.text.trim())
}
};
Jupyter.notebook.kernel.execute(`print(${python})`, callbacks);
});
}
// Use it in any Jupyter JS/HTML cell like this
%%javascript
window.executePython("1 + 1")
.then(result => console.log(result)); // Logs 2
// You can access any defined object/method in the notebook
// I suggest writing a function that returns your data as JSON and just calling the function.

Track position of other element

I have an inner circle which tracks the position of my pointer, Now I want the circle color to change when it hovers on the h2 tag.
can anyone help??
I have tried searching few places but all were on "mouseover".
note: only when the inner-circle hovers on h2 not the mouse pointer, the inner circle's color should change.
<!doctype>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Roll Over Eyes</title>
<style>
body
{
display: flex;
align-items: center;
justify-content: center;
height: 900px;
border: 1px solid black;
}
.main-circle
{
display: flex;
align-items: center;
justify-content: center;
position: relative;
height: 350px;
width: 350px;
border: 1px solid black;
border-radius: 10%;
}
#inner-circle
{
position: absolute;
height: 50px;
width: 50px;
border: 1px solid black;
border-radius: 50%;
background: #af4b23;
}
.message
{
display:none;
width: 75%;
}
</style>
</head>
<body>
<div class="main-circle">
<div id="inner-circle">
</div>
<h2 class="message">Your Outside the box</h2>
<h2 class="message">Your inside the box, now move the mouse to move the circle.</h2>
</div>
<script>
(function()
{
var ele= document.getElementById("inner-circle");
var hea= document.getElementsByClassName("message");
var body=document.body;
var height=body.clientHeight;
var width=body.clientWidth;
var move = function(event)
{
var x= event.clientX;
var y= event.clientY;
ele.style.left = ( x/width )*300;
ele.style.top = ( y/height )*300;
}
var display = function()
{
console.log("done");
hea[0].style.display="inline-block";
hea[1].style.display="none";
}
var hide = function()
{
console.log("done hiden");
hea[0].style.display="none";
hea[1].style.display="inline-block";
}
var effect = function()
{
ele.style.backgroundColor= "rgba(0,0,0,0.5)";
}
var deflt = function()
{
ele.style.backgroundColor= "#af4b23";
}
body.addEventListener("mousemove",function(){ move(event) },false);
body.addEventListener("mouseout",display,false);
body.addEventListener("mouseover",hide,false);
hea[1].addEventListener("mouseover",effect,false);
hea[1].addEventListener("mouseout",deflt,false);
})();
</script>
</body>
</html>
You can try this:
(function()
{
var ele= document.getElementById("inner-circle");
var hea= document.getElementsByClassName("message");
var body=document.body;
var height=body.clientHeight;
var width=body.clientWidth;
var move = function(event)
{
var x= event.clientX;
var y= event.clientY;
ele.style.left = ( x/width )*300;
ele.style.top = ( y/height )*300;
var e_pos = ele.getBoundingClientRect();
var h_pos = hea[1].getBoundingClientRect();
if(e_pos.bottom>=h_pos.top && e_pos.top<=h_pos.bottom && e_pos.right>=h_pos.left && e_pos.left<=h_pos.right){
ele.style.backgroundColor= "rgba(0,0,0,0.5)";
}else{
ele.style.backgroundColor= "#af4b23";
};
}
var display = function()
{
//console.log("done");
hea[0].style.display="inline-block";
hea[1].style.display="none";
}
var hide = function()
{
//console.log("done hiden");
hea[0].style.display="none";
hea[1].style.display="inline-block";
}
body.addEventListener("mousemove",function(){ move(event) },false);
body.addEventListener("mouseout",display,false);
body.addEventListener("mouseover",hide,false);
})();
in this answer i set background-color after setting left and top of ele. also i have removed two last eventListeners.
Look at the result online and change it yorself!
the border is added to detect h2's bounds.

JavaScript script that only work on chrome, not working in Firefox. (Script for dragging div)

May be this is small question. But I couldn't found reason for this. I made a script to change a position of div by dragging it. the code is working fine with chrome browser. but when I trying to test it on Firefox it is not working.
var h = window.innerHeight|| document.documentElement.clientHeight || document.body.clientHeight;
window.onload = function () {
// ------------------lock the div with mouse pointer--------------
// variable dragged is for identified that you are click on the button or not
var dragged = false,
y = 0,pointerDis = 0,
boxElement = document.getElementById('drag'),
drgElement = document.getElementById('titl');
if (boxElement) {
// -----------------check whether the title div is holding by the mouse to lock it with mouse-------
drgElement.addEventListener('mousedown', function() {
dragged = true;
pointerDis = event.clientY - parseInt(window.getComputedStyle(boxElement, null).getPropertyValue("top"));
});
//------------------check whether the title div is released to drop the div-------------------------
document.addEventListener('mouseup', function() {
dragged = false;
});
document.addEventListener('mousemove', function () {
y = event.clientY;
if(dragged == true)
{
y = y -pointerDis;
if(y<0)
{
y = 0;
}
else if(y > window.innerHeight - boxElement.offsetHeight)
{
y = window.innerHeight - boxElement.offsetHeight;
}
boxElement.style.top = y + 'px';
}
});
}
};
.drg {
position: absolute;
top:0;
right: 0;
background: red;
border-top-left-radius: 45px;
border-bottom-left-radius: 45px;
}
#titl{
background: blue;
width: 50px;
text-align: center;
color: white;
font-size: 30px;
border-top-left-radius: 10px;
}
#det{
background: #f9c500;
width: 50px;
border-bottom-left-radius: 10px;
text-align: center;
}
<!DOCTYPE html>
<html>
<head>
<title>test 4</title>
</head>
<body>
<div class = "drg" id="drag">
<div id="titl" unselectable="on" onselectstart="return false;">....</div>
<div id="det">this is the details menu</div>
</div>
</body>
</html>
You can drag it through Y axis by click and drag from blue div. I don't know the reason or I couldn't find a way to fix this work on Firefox. Please help me!
You have to catch the (mousemove or mousedown) events as the input of wrapped functions
drgElement.addEventListener('mousedown', function(event)...
var h = window.innerHeight|| document.documentElement.clientHeight || document.body.clientHeight;
window.onload = function () {
// ------------------lock the div with mouse pointer--------------
// variable dragged is for identified that you are click on the button or not
var dragged = false,
y = 0,pointerDis = 0,
boxElement = document.getElementById('drag'),
drgElement = document.getElementById('titl');
if (boxElement) {
// -----------------check whether the title div is holding by the mouse to lock it with mouse-------
drgElement.addEventListener('mousedown', function(event) {
dragged = true;
pointerDis = event.clientY - parseInt(window.getComputedStyle(boxElement, null).getPropertyValue("top"));
});
//------------------check whether the title div is released to drop the div-------------------------
document.addEventListener('mouseup', function() {
dragged = false;
});
document.addEventListener('mousemove', function (event) {
y = event.clientY;
if(dragged == true)
{
y = y -pointerDis;
if(y<0)
{
y = 0;
}
else if(y > window.innerHeight - boxElement.offsetHeight)
{
y = window.innerHeight - boxElement.offsetHeight;
}
boxElement.style.top = y + 'px';
}
});
}
};
.drg {
position: absolute;
top:0;
right: 0;
background: red;
border-top-left-radius: 45px;
border-bottom-left-radius: 45px;
}
#titl{
background: blue;
width: 50px;
text-align: center;
color: white;
font-size: 30px;
border-top-left-radius: 10px;
}
#det{
background: #f9c500;
width: 50px;
border-bottom-left-radius: 10px;
text-align: center;
}
<!DOCTYPE html>
<html>
<head>
<title>test 4</title>
</head>
<body>
<div class = "drg" id="drag">
<div id="titl" unselectable="on" onselectstart="return false;">....</div>
<div id="det">this is the details menu</div>
</div>
</body>
</html>

DOM Exception 18 while Detecting pixel color on a canvas

I am trying to finish HTML5/javascript game and testing it in crome.
Whever i am pointing over the image for detecting pixel color There an error display in console.
Unable to get image data from canvas because the canvas has been tainted by cross-origin data. e001-4.html:27
Uncaught Error: SecurityError: DOM Exception 18
Please tell me what is it and what'wrong in the code.
Here is the code.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Canvas Example 4 (Detecting Colors)</title>
<script>
window.onload = function () {
var preview = document.getElementById('preview');
var r = document.getElementById('r');
var g = document.getElementById('g');
var b = document.getElementById('b');
var a = document.getElementById('a');
var mx = document.getElementById('mx');
var my = document.getElementById('my');
var canvas = document.getElementById('myCanvas');
canvas.addEventListener('mousemove', move, false);
var c = canvas.getContext('2d');
var building = new Image()
building.src = "img/sprite1.png";
draw();
function draw () {
c.drawImage(building, 0, 0, canvas.width, canvas.height);
}
function move (e) {
mx.innerHTML = e.clientX;
my.innerHTML = e.clientY;
var img = c.getImageData(e.clientX, e.clientY, 1, 1);
var idata = img.data;
var red = idata[0];
var green = idata[1];
var blue = idata[2];
var alpha = idata[3];
r.innerHTML = red;
g.innerHTML = green;
b.innerHTML = blue;
a.innerHTML = (alpha > 0) ? alpha : 'Transparent';
var rgba='rgba(' + red + ', ' + green + ', ' + blue + ', ' + alpha + ')';
preview.style.backgroundColor =rgba;
}
}
</script>
<style type="text/css" media="screen">
body { margin: 0px; padding: 0px; }
canvas {
border: 1px solid black;
float: left;
}
ul {
list-style: none;
margin: 10px 10px 10px 10px;
padding: 0px;
float: left;
}
ul li { font-weight: bold; }
ul li span { font-weight: normal; }
ul li #preview { width: 50px; height: 50px; border: 1px solid black; }
</style>
</head>
<body>
<canvas id="myCanvas" width="300" height="300">
Your browser doesn't include support for the canvas tag.
</canvas>
<ul>
<li><div id="preview"></div></li>
<li>Red: <span id="r">NULL</span></li>
<li>Green: <span id="g">NULL</span></li>
<li>Blue: <span id="b">NULL</span></li>
<li>Alpha: <span id="a">NULL</span></li>
<li>Mouse X: <span id="mx">NULL</span></li>
<li>Mouse Y: <span id="my">NULL</span></li>
</ul>
</body>
</html>
A local web server is a very useful development tool.
But, if you just want to test images while satisfying CORS requirements then check out dropbox.com.
If you sign up and put your images in your public folder, then you can satisfy CORS restrictions by applying building.crossOrigin="anonymous";
Try to use a local Web server and serve the page from it.
Example use apache and put the file in htdoc folder and look for the result.

Categories

Resources