Reputation: 1
I'm looking to create an if statement for an svg container to institute a next/back button UI. I am having troubles creating a statement that will if yes (1), perform a particular function.
For example,
if (d3.select("svg").attr("id") == "#chart") function updateData1() {
...
}
Upvotes: 0
Views: 4320
Reputation: 1959
Here is an example of how you could implement such logic. In case your content is very different for each scene, you can remove the svg content. Keep in mind, you always can use the enter update exit pattern https://bl.ocks.org/mbostock/3808218 if you want to modify your svg content.
const width = 200
const height = 200
const svg = d3.select('#app') // add main svg to #app
.append('svg')
.attr('width', width)
.attr('height', height)
let scene = 0 // keep track of scene counter
// button event
d3.select('#nextBtn').on('click', function(){
scene = nextEvent(svg, scene) //call event and update scene
})
function nextEvent(svg, scene){
if(scene === 0){
svg.select('*').remove() // clean svg content
svg.append('rect')
.attr('width', 50)
.attr('height', 50)
.attr('x', 10)
.attr('y', 10)
}
if(scene === 1){
svg.select('*').remove()
svg.append('circle')
.attr('r', 50)
.attr('cx', 85)
.attr('cy', 85)
}
if(scene === 2){
svg.select('*').remove()
svg.append('rect')
.attr('width', 90)
.attr('height', 90)
.attr('x', 50)
.attr('y', 50)
}
return (scene + 1)%3 // return counter up to3 scenes
}
<script src="https://d3js.org/d3.v5.min.js"></script>
<button id="nextBtn"> next </button>
<div id="app"></div>
Upvotes: 0
Reputation: 869
I'm not sure exactly what you mean, but generally I think what you are asking should look like:
if (d3.select("svg").attr("id") == "#chart")
{
updateData1();
}
And have updateData1() defined somewhere else, possibly in the same file as:
function updateData1()
{
...
}
If you post more of your scenario it might be easier to help address your troubles.
Upvotes: 1