I have a blue square and when I hover over it, two other objects should appear.
So far, only one object (the text) appears and the other one (the red square) remains hidden.
How do I make that on hovering the blue square both, the red square and the text appear?
var canvas = document.getElementById("svg_canvas");
var square = document.createElementNS('http://www.w3.org/2000/svg',"rect");
square.setAttribute('x', 100)
square.setAttribute('y', 100)
square.setAttribute('width', 100)
square.setAttribute('height', 100)
square.setAttribute("fill", "blue");
square.setAttribute("class", "HoveringClass");
canvas.appendChild(square);
var hover_text = document.createElementNS('http://www.w3.org/2000/svg', "text");
hover_text.setAttribute('id','termin_text');
hover_text.setAttribute('x', 200)
hover_text.setAttribute('y', 200)
hover_text.setAttribute("class", "hide");
hover_text.textContent = "hello world";
canvas.appendChild(hover_text);
var square2 = document.createElementNS('http://www.w3.org/2000/svg',"rect");
square2.setAttribute('id','termin_rect' + 1);
square2.setAttribute('x', 50)
square2.setAttribute('y', 50 )
square2.setAttribute('width', 50)
square2.setAttribute('height', 50)
square2.setAttribute("fill", "red");
square2.setAttribute("class", "hide");
canvas.appendChild(square2);
<svg id="svg_canvas" viewBox="0 0 1200 600" width="1200px" height="600px" xmlns="http://www.w3.org/2000/svg"></svg>
2
Answers
To make both the red square and the text appear when you hover over the blue square, you’ll need to add event listeners for mouse events
I’ve added mouseover and mouseout event listeners to the blue square. When you hover over it, both the text and the red square will show, and when you move the mouse out, they’ll hide again.
The hide class uses display: none; to hide elements. The show class uses display: inline; to make elements visible.
I took a slightly different approach by declaring an object for each of the SVG elements. Each object has "attributes" to set.
Key here is I used events to toggle a class, then used that class in CSS to hide the elements with
el.classList.toggle('hide');
Note I used a data attribute on the svg to say what to target, then added that to the class for the targets:
data-toggletargets=".toggle-target"
Note also that I put an "opposite" on the blue box text just by NOT including the
hide
class to that initially – so it goes from showing to hidden when you mouse over the box and mouse out again.This differs in that the "visual" display type is whatever the HTML/SVG says not something like
display:inline;
or some such since we only really care about the hide part.