If possible, I need to add hyperlinks to a Plotly Sunburst chart so that a user can click and go to a webpage with more information.
Sunburst chart showing where hyperlinks are needed
I've tried organizing the data two different ways
Here's the data in coffeeURL.csv:
ids,labels,parents
Enzymatic-Flowery,Flowery,
Enzymatic-Fruity,Fruity,
Enzymatic-Herby,Herby,
<a href=Flower-Floral.html>Flowery-Floral</a>,Floral,Enzymatic-Flowery
<a href=Flower-Fragrant.html>Flowery-Fragrant</a>,Fragrant,Enzymatic-Flowery
<a href=Fruity-Citrus.html>Fruity-Citrus</a>,Citrus,Enzymatic-Fruity
<a href=Fruity-Berry-like.html>Fruity-Berry-like</a>,Berry-like,Enzymatic-Fruity
<a href=Herby-Alliaceous.html>Herby-Alliaceous</a>,Alliaceous,Enzymatic-Herby
<a href=Herby-Leguminous.html>Herby-Leguminous</a>,Leguminous,Enzymatic-Herby
Here's the script:
import plotly.graph_objects as go
import pandas as pd
df = pd.read_csv('coffeeURL.csv')
fig = go.Figure()
fig.add_trace(go.Sunburst(
ids=df.ids,
labels=df.labels,
parents=df.parents,
domain=dict(column=1),
maxdepth=2,
insidetextorientation='radial'
))
fig.update_layout(
margin = dict(t=10, l=10, r=10, b=10)
)
fig.show()
you can achieve this is you use dash and a callback
your URLs are not accessible to me so have used results of a Google search with results going into an Iframe
import pandas as pd
import io
import plotly.graph_objects as go
from jupyter_dash import JupyterDash
from dash import html, dcc
from dash.dependencies import Input, Output
from dash.exceptions import PreventUpdate
# Build App
app = JupyterDash(__name__)
df = pd.read_csv(io.StringIO("""ids,labels,parents
Enzymatic-Flowery,Flowery,
Enzymatic-Fruity,Fruity,
Enzymatic-Herby,Herby,
<a href=Flower-Floral.html>Flowery-Floral</a>,Floral,Enzymatic-Flowery
<a href=Flower-Fragrant.html>Flowery-Fragrant</a>,Fragrant,Enzymatic-Flowery
<a href=Fruity-Citrus.html>Fruity-Citrus</a>,Citrus,Enzymatic-Fruity
<a href=Fruity-Berry-like.html>Fruity-Berry-like</a>,Berry-like,Enzymatic-Fruity
<a href=Herby-Alliaceous.html>Herby-Alliaceous</a>,Alliaceous,Enzymatic-Herby
<a href=Herby-Leguminous.html>Herby-Leguminous</a>,Leguminous,Enzymatic-Herby"""))
fig = go.Figure()
fig.add_trace(go.Sunburst(
ids=df.ids,
labels=df.labels,
parents=df.parents,
domain=dict(column=1),
maxdepth=2,
insidetextorientation='radial'
))
fig.update_layout(
margin = dict(t=10, l=10, r=10, b=10)
)
app.layout = html.Div(
[
dcc.Graph(
id="figure",
figure=fig,
),
html.Iframe(
id="details",
src="https://www.google.com/search?igu=1&ei=&q=flowers",
style={"height": "1067px", "width": "100%"},
),
]
)
#app.callback(Output("details", "src"), [Input("figure", "clickData")])
def clickPoint(clickData):
if clickData:
try:
clicked_id = clickData["points"][0]["id"]
clicked_id = clicked_id.split(">")[1].split("<")[0]
return f"https://www.google.com/search?igu=1&ei=&q={clicked_id}"
except IndexError:
raise PreventUpdate
else:
raise PreventUpdate
app.run_server(mode="inline")
JSON
var obj = {
content: "<p class="p1">Sample p tag one.</p> <p class="p1">Also
another paragraph sample.</p> <p><b>sample text</b></p> <p>More info <a
title="" href="https://www.google.com/"
target="_blank" rel="noopener"><em>THE WORK AHEAD: MACHINES, SKILLS AND
U.S. LEADERSHIP</em></a></p>"
};
How would I render this code in react? It shows all of the html tags.
Through dangerouslySetInnetHTML.
const htmlString = '<p>My html</p>';
const innerHtmlObject = {
__html: htmlString,
};
<div dangerouslySetInnerHTML={innerHtmlObject} />
Note: This is a bad practice that can lead to security vulnerability!
You can try this
<div
dangerouslySetInnerHTML={{
__html: this.state.obj.content
}}
/>
You need to parse the HTML.
You can do this through dangerouslySetInnerHTML but it's safer to sanitize it first using something like html-react-parser.
import Parser from 'html-react-parser';
Inside you render function:
<div>{Parser(obj.content)}</div>
I have the following scripts:
<script>
window.onload = function setHref(){
var affglcid = <?php echo json_encode($kws); ?>;
var oldLink=document.getElementById('link').href;
document.getElementById('link').setAttribute('href', oldLink+affglcid);
var oldLink1=document.getElementById('link2').href;
document.getElementById('link2').setAttribute('href', oldLink1+affglcid);
}
</script>
And:
<a id="link" href="oursite.com/">Link</a>
<a id="link2" href="othersite.com/">Link</a>
First, it takes a PHP variable:
var affglcid = <?php echo json_encode($kws); ?>;
Then it appends the variable at the end of a link:
var oldLink=document.getElementById('link').href;
document.getElementById('link').setAttribute('href', oldLink+affglcid);
It should do the same for another link:
var oldLink1=document.getElementById('link2').href;
document.getElementById('link2').setAttribute('href', oldLink1+affglcid);
So, if $kw=xy then the first link should be "oursite.com/xy" and the second one "othersite.com/xy" but it only works on the other site link. The code used for that is the following:
<a id="link" href="oursite.com/">Link</a>
<a id="link2" href="othersite.com/">Link</a
Any ideas what's wrong?
I noticed that your URLs not correct, they should start with "http://" or "https://"
<a id="link" href="http://oursite.com/">Link</a>
<a id="link2" href="http://othersite.com/">Link</a>
Even if you don't want to add protocol, you should atleast use //oursite.com, otherwise it'll be considered as relative URL which will append this URL in front of your current URL and try to open that
I have this strange issue where URL parameter divider & of an IMG SRC gets replaced with the HTML entity.
I need to replace those so this string:
<img src="https://example.com/imagehandler?$PNG%20with%20alpha$&scl=1" alt="">
Returns:
<img src="https://example.com/imagehandler?$PNG%20with%20alpha$&scl=1" alt="">
It should only replace within double quotes — not if in other places like regular HTML entities.
A regex workaround:
var text = `<img src="https://example.com/imagehandler?$PNG%20with%20alpha$&scl=1" alt="">`;
console.log(text.replace(/src="[^"]+/g, function(match) {
return match.replace('&', '&');
}));
A DOM solution:
According to your statement, It's a string, not in the dom..., you should use DOMParser to convert a HTML string into valid DOM. Modifying #prasad's answer it would be something like this:
var HTMLmarkup = `
<img src="https://example.com/imagehandler?$PNG%20with%20alpha$&scl=1" alt="">
<img src="https://example.com/imagehandler?$PNG%20with%20alpha$&scl=1" alt="">
`
var parser = new DOMParser()
var dom = parser.parseFromString(HTMLmarkup, "text/html");
dom.querySelectorAll('img').forEach(function(a){
console.log(a.src)
})
Try with simple regex pattern /&/g .And querySelectorAll used for select the img element
Demo regex
document.querySelectorAll('img').forEach(function(a){
a.src = a.src.replace(/&/g,"")
console.log(a.src)
})
<img src="https://example.com/imagehandler?$PNG%20with%20alpha$&scl=1" alt="">
For completeness, here's a solution that uses regular DOM functions. It diverges from the original requirement in that it extracts the URL because (IMHO) it's a reasonable ultimate goal:
var html = '<img src="https://example.com/imagehandler?$PNG%20with%20alpha$&scl=1" alt=""> <img src="/some/other/location/?one=1&two=2&three=3">';
var aux = document.createElement("div");
aux.innerHTML = html;
var urls = [];
aux.querySelectorAll("img[src]").forEach(function(image){
urls.push(image.getAttribute("src"));
});
console.log(urls);
I'm a begginer with Javascript and I would like to know if there is a better way to write this piece of code:
var images = [],
index = 0;
images[0] = "<a href = 'link' onclick='_gaq.push(['_link', this.href]);return false;'>
<img src='image.jpg'></a>";
images[1] = "<a href = 'link1' onclick='_gaq.push(['_link', this.href]);return false;'>
<img src='image1.jpg'></a>";
index = Math.floor(Math.random() * images.length);
document.write(images[index]);
This code doens´t work, I think is because I'm including the onClick function inside the variable description...
The function would be to print randomically the images, but adding the _gaq.push parameters in the url image link.
Is there any other way the write this code?
Thanks
No need to create the html in javascript. You can do the following:
JavaScript (must be instantiated before the html is rendered):
var pushMe = function(link){
_gaq.push(['_link', link.href]);return false;
};
Html:
<a href = "link" onclick="pushMe(this);">
<img src="image.jpg"></a>