Detect which element is moused over and pass to function - javascript

I'm using greensock to animate an svg clippath, and it works great with one clippath, and hardcoded variables. Now I'm needing to add more clippaths, and I need each one to animate independently. So I need to build some sort of function to detect which circle is being moused over/ moused out and then call the timeline, passing it the correct parameters (the clippath and overlay circle). I'm sure I could probably do that with 'this' but I'm still at the point where 'this' makes my brain melt. Here's the codepen I'm working on.
http://codepen.io/kathryncrawford/pen/JYvdzx
HTML
<svg class="svg-graphic" width="500" height="500" xmlns="http://www.w3.org/2000/svg" xlink="http://www.w3.org/1999/xlink" version="1.1">
<defs>
<clipPath id="clippath">
<circle id="clip1" cx="200" cy="200" r="2.5"/>
<circle id="clip2" cx="400" cy="200" r="3.2"/>
</clipPath>
</defs>
<image class="svg-image1" xlink:href="http://lorempixel.com/300/300/" width="300" height="300" x="80" y="80"/>
<circle id="circle1" fill="#CC66FF" cx="200" cy="200" r="30"/>
<image class="svg-image2" xlink:href="http://lorempixel.com/300/300/" width="300" height="300" x="380" y="80"/>
<circle id="circle2" fill="#CC66FF" cx="400" cy="200" r="30"/>
JS
var clip = document.getElementById("clip1");
var circles = document.getElementById("circle1");
circles.addEventListener("mouseenter", expand);
circles.addEventListener("mouseleave", contract);
var tl = new TimelineMax({paused: true});
tl.to(clip, 0.5, {
attr: {
r: 120
},
transformOrigin: "50% 50%",
ease: Power4.easeInOut
})
.to(circles, 0.5, {alpha:0, ease:Power4.easeInOut}, '-0.1');
function expand() {
tl.play();
}
function contract() {
tl.reverse();
}

All right, this is what I was able to create by forking your pen.
And here is what has changed:
In HTML, I have removed unique IDs set on each of the circle HTML elements present inside the clipPath HTML element i.e. clipPath's children. Instead, I have given all of these circle tags a clip class.
The other circle elements that are siblings of the said clipPath i.e. present on the same level as clipPath element, have been given a circle class.
And as for the image elements, I have done similar thing. Removed unique IDs from them and instead gave them a common svg-image class.
This is HTML done.
In HTML, since the unique IDs have been removed such as #circle1, #circle2, #svg-image1 and #svg-image2, I have removed them from CSS as well and instead applied exactly the same rules they had on the newly created classes i.e. .circle and .svg-image respectively.
In JavaScript, the clip and circle elements as well as the total number of clip elements are first stored in variables clips, circles and numClips respectively.
There is also an empty array of timelines created initially.
Then there is a loop being initiated which goes up till the length of numClips and which does two things:
createTimeline as the name suggests, is supposed to create a TimelineMax instance which looks similar to what you previously had i.e. it adds two tweens, one for animating the opacity on the current circle element (remember, we are inside a loop and we have a reference of current circle element by the use of circles[i]) and the other for animating r of the current clip element.
assignListeners is for listening to mouseenter and mouseleave events on each of the circle elements.
And finally, expand and collapse methods are for playing or reversing the current timeline instance. (again, we have the reference of the timeline that should be playing when hovered or out using timelines[i] reference).
HTML:
<svg class="svg-graphic" width="500" height="500" xmlns="http://www.w3.org/2000/svg" xlink="http://www.w3.org/1999/xlink" version="1.1">
<defs>
<clipPath id="clippath">
<circle class="clip" cx="200" cy="200" r="20" />
<circle class="clip" cx="400" cy="200" r="20" />
<circle class="clip" cx="600" cy="200" r="20" />
</clipPath>
</defs>
<image class="svg-image" xlink:href="http://lorempixel.com/300/300/" width="300" height="300" x="80" y="80" />
<circle class="circle" fill="#CC66FF" cx="200" cy="200" r="20" />
<image class="svg-image" xlink:href="http://lorempixel.com/300/300/" width="300" height="300" x="380" y="80" />
<circle class="circle" fill="#CC66FF" cx="400" cy="200" r="20" />
<image class="svg-image" xlink:href="http://lorempixel.com/300/300/" width="300" height="300" x="680" y="80" />
<circle class="circle" fill="#CC66FF" cx="600" cy="200" r="20" />
</svg>
CSS:
*{
box-sizing: border-box;
}
body{
margin: 0;
padding: 0
}
.circle{
position: absolute;
margin: 0;
z-index: 1;
clip-path: url("#clippath");
}
.svg-image {
z-index: 3;
clip-path: url(#clippath);
}
svg{
overflow: visible;
}
.svg-graphic {
position: absolute;
}
.imgContainer {
position: relative;
width: 800px;
height: 800px;
}
JavaScript:
var clips = document.getElementsByClassName('clip');
var circles = document.getElementsByClassName('circle');
var numClips = clips.length;
var timelines = [];
for (var i = 0; i < numClips; i += 1) {
createTimeline(i);
assignListeners(i);
}
function createTimeline(i) {
var timeline = new TimelineMax({ paused: true });
timeline.to(circles[i], 0.6, { opacity: 0, ease: Expo.easeInOut }, 0);
timeline.to(clips[i], 0.6, {
attr: { r: 120 },
transformOrigin: '50% 50%',
ease: Expo.easeInOut
}, 0.1);
timelines[i] = timeline;
}
function assignListeners(i) {
(function(i) {
circles[i].addEventListener('mouseenter', function(e) { expand(e, i); }, false);
circles[i].addEventListener('mouseleave', function(e) { contract(e, i); }, false);
}(i));
}
function expand(e, i) { timelines[i].play(); }
function contract(e, i) { timelines[i].reverse(); }
Hope this helps.

Related

How to switch position of D3 SVG elements

I have some SVG elements on my page that I created with D3. All are children of one parent SVG. Each contains some other D3 elements like paths and text. On the click of a button, I want two of these child SVGs to switch positions, so they move up or down on the page (all are placed above/below each other).
I already tried creating groups ("g") instead of the child SVGs and accessing/changing their positions. However, I can't seem to access the y position of the element.
I also tried using "insertAfter" but this only works with divs, not with SVGs (however, I'm looking for a similar behaviour).
$(".move_up").click(function() {
var svg = $("#second_child"); //ID is actually retrieved from an attribute of the button
svg.insertBefore(svg.prev()); //does obviously not work
});
HTML for move up button (one per child SVG exists):
<a class="move_up">
<span class="grey glyphicon glyphicon-chevron-up" title="Move up"></span>
</a>
HTML for SVG:
<div>
<svg id="parent">
<svg id="first_child"
<path></path>
<rect></rect>
<text></text>
...
</svg>
<svg id="second_child"
<path></path>
<rect></rect>
<text></text>
...
</svg>
<rect></rect>
<text></text>
...
</svg>
</div>
I want the first and second child SVGs to switch positions, when the move up (or respectively a move down) button is used.
This is what I ended up doing:
let group = $("#first_group");
let next_group = $('#second_group");
let diff = 58; // Height of a group
let translate_y = 0;
let translate_y_next = 0;
if (next_group.offset()) {
if (group.attr("transform")) {
let string = group.attr("transform");
translate_y = parseInt(string.substring(string.indexOf("(")+1, string.indexOf(")")).split(",")[1]);
}
if (prev_group.attr("transform")) {
let string_next = prev_group.attr("transform");
translate_y_next = parseInt(string_next.substring(string_next.indexOf("(")+1, string_next.indexOf(")")).split(",")[1]);
}
group.attr("transform", `translate(0, ${translate_y + diff})`);
next_group.attr("transform", `translate(0, ${translate_y_next - diff})`);
}
Works similar for a "Move up" button. Just make sure to change the sign in the last two lines!
May not be super elegant, but does the job.
You are using an SVG as wrapper and the positions are different to html. In SVG You need to define the X and Y position.
let ids = ['ex1', 'ex2', 'ex3', 'ex4', 'ex5']
let btn = document.getElementById('move')
const sortArrayAsYouWish = (array) => {
array.sort(() => Math.random() - 0.5);
}
const changeOrder = () => {
let posY = 35
sortArrayAsYouWish(ids) // change order
ids.forEach((id, i) => {
let $el = document.getElementById(id)
$el.style.transform = `translate(0, ${posY*i}px)`
})
}
btn.onclick = changeOrder
changeOrder()
svg {
width: 500px;
height: 340px;
border: solid 1px #ccc;
}
g {
transition: transform 0.4s;
}
text {
fill: #fff;
text-anchor: middle;
}
#ex2 rect {
fill: blue;
}
#ex3 rect {
fill: yellow;
}
#ex4 rect {
fill: red;
}
#ex5 rect {
fill: cyan;
}
<div><button id="move">Move</button></div>
<svg>
<g id="ex1">
<rect width="120" height="30" x="0" y="0" />
<text x="60" y="15">Hello example 1</text>
</g>
<g id="ex2">
<rect width="120" height="30" x="0" y="0" />
<text x="60" y="15">Hello example 2</text>
</g>
<g id="ex3">
<rect width="120" height="30" x="0" y="0" />
<text x="60" y="15">Hello example 3</text>
</g>
<g id="ex4">
<rect width="120" height="30" x="0" y="0" />
<text x="60" y="15">Hello example 4</text>
</g>
<g id="ex5">
<rect width="120" height="30" x="0" y="0" />
<text x="60" y="15">Hello example 5</text>
</g>
</svg>

How do I get an internal SVG element's position relative to the viewport of an outer SVG element?

Say I have an SVG element containing some stuff:
<div style="margin-left:50px; width: 100%; min-height: 400px;">
<svg>
<g transform="translate(34.34,47.5) scale(0.345)" height="100%" width="100%">
<svg x="20" y ="50" style="overflow: visible">
<circle cx="0" cy="0" r="35" stroke="red" fill="blue">
<text>a bunch of text</text>
</svg>
<line />
</g>
<svg>
<div>
I'm trying to find the center position of the <g> relative to the viewport of the outer <svg> element, so that I can translate the <g> to be centered within the outer <svg>, and scale it to fit.
I was able to get it working using getBoundingClientRect() and adjusting for the transform scale, but this does not work in Firefox because the <svg> elements inside the <g> container are not constrained to the bounding box of the displayed section of their contents (rather it's the same size as the outer <svg>, with some scaling).
There is probably a solution using createSVGPoint() and getScreenCTM() or getCTM() but frankly I'm not sure what I should be using.
An SVG without a viewBox attribute has a width of 300px and a height of 150px. I've added a viewBox="0 0 300 150". You can remove it.
Also I've added a rectangle to be able to see the position and the size of the <g> element. You can remove it as well.
How I would center the <g> element: Since the <g> element is transformed the easiest way to get it's size and position would be wrapping the <g> element in another one, in this case <g id="wrap"> Next I can get the bounding box of the wrap: wrap.getBBox()
In order to center the wrap I need to know the center of the main svg canvas: x = 300/2; y=150/2. Now I can translate the wrap into the center
let c = {x:150,y:75}//the center of the main svg element
let bb = wrap.getBBox()//the bounding box of the wrap
let transformation = `translate(${c.x - bb.x - bb.width/2},
${c.y - bb.y - bb.height/2})`
wrap.setAttributeNS(null,"transform",transformation)
svg{border:1px solid;width:100vh;}
text{fill:black;}
path{fill:none;stroke:black}
<div style="margin-left:50px; width: 100%; min-height: 400px;">
<svg id="main" viewBox="0 0 300 150" >
<g id="wrap">
<rect x="29.165" y="47.5" width="45.03" height="29.325" fill="gold" fill-opacity=".5" />
<g transform="translate(34.34,47.5) scale(0.345)" height="100%" width="100%">
<svg x="20" y ="50" style="overflow: visible">
<circle cx="0" cy="0" r="35" stroke="red" fill="blue"/>
<text>a bunch of text</text>
</svg>
<line />
</g>
</g>
<path d="M0,0L300,150M0,150L300,0" />
<svg>
<div>
I hope this is what you were asking.
I managed to figure out a solution using one of the d3.zoom transform methods (we're using d3.zoom to manage the translate/scale transform), and SVGElement.getBBox(). I originally was using this method but had messed up the calculation; this way it works though.
const selection = d3.select(group);
const zoomBehavior = d3.zoom().on('zoom', () => {
selectionTransform = d3.event.transform;
});
selection.call(zoomBehavior);
const scaleAndTransformTo = () => {
selection.call(zoomBehavior.translateBy, Math.random() * 100, Math.random() * 150);
group.setAttribute("transform", selectionTransform.toString());
}
scaleAndTransformTo();
reset.addEventListener('click', scaleAndTransformTo);
run.addEventListener('click', () => {
const { width: containerWidth, height: containerHeight } = container.getBoundingClientRect();
const containerCenter = [containerWidth / 2, containerHeight / 2];
const { height, width, x, y } = group.getBBox();
const nodeBBoxCenter = [x + (width / 2), y + (height / 2)];
// Apply the current interpolated translate/scale to the BBox center to get the actual position
const groupCenterCoords = selectionTransform.apply(nodeBBoxCenter);
const translationOffset = [
(containerCenter[0] - groupCenterCoords[0]) / selectionTransform.k,
(containerCenter[1] - groupCenterCoords[1]) / selectionTransform.k,
];
selection.call(zoomBehavior.translateBy, ...translationOffset);
group.setAttribute("transform", selectionTransform.toString());
});
#page {
display: flex;
flex-direction: column;
position: relative;
align-items: stretch;
margin-left: 100px;
}
#container {
background-color: grey;
flex-grow: 1;
flex-shrink: 0;
min-height: 500px;
border: 1px solid red;
}
#group > svg {
overflow: visible;
}
#group > svg > circle {
overflow: visible;
}
text {
fill: black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<div id="page">
<div>
<button id="run">Run</button>
<button id="reset">Reset</button>
</div>
<svg id="container">
<g x="0" y="0" id="group" width="100%" height="100%">
<line x1="20" y1="50" x2="150" y2="150" stroke="brown" />
<svg x="20" y ="50">
<circle cx="0" cy="0" r="35" stroke="red" fill="blue">
<text x="35" y="0" height="100%" width="100%">a bunch of text</text>
</svg>
<line x1="100" y1="350" x2="160" y2="340" stroke="brown" />
<svg x="100" y ="350">
<circle cx="0" cy="0" r="35" stroke="red" fill="blue">
<text x="35" y="0" height="100%" width="100%">a bunch of text 3</text>
</svg>
</g>
<svg>
<div>

How do I style one of the parameters in a circle inside an SVG?

I have a SVG with circles inside it. And I want them to be increasing and decreasing in radius for ever (like a pulsating circle).
My problem is, can I do it with #keyframes? Or do I need jquery? And if so, how?
Here is my code:
<div class="mapa">
<svg (svg code here......)
<circle opacity="0.3" cx="842" cy="451.814" r="25.582" id="1"/>
<circle opacity="0.3" cx="542" cy="405.814" r="25.582" id="1"/>
</svg>
</div>
How do I style the 'r' parameter?
I read I cannot style the 'r' parameter, but this worked:
<circle cx="168" cy="179" r="59"
fill="white" stroke="black"
onmouseover="evt.target.setAttribute('r', '72');"
onmouseout="evt.target.setAttribute('r', '59');"
/>
However, I want to do it with continuous increase and decrease in radius? And not on mouseover/mouseleave. Something like (r=25, then r=30, then back to 25, and goes on forever). How do I do this?
Thanks for your time, if you can give me any tips I'd apreciate it a lot!
Try to use svg smil animate
<svg width="150" height="150">
<circle opacity="0.3" cx="84%" cy="45%" r="3" id="1">
<animate attributeName="r" values="3; 10; 3" keyTimes="0; 0.5; 1" dur="1s" repeatCount="indefinite" />
</circle>
<circle opacity="0.3" cx="50%" cy="50%" r="10" id="2">
<animate attributeName="r" values="10; 3; 10" keyTimes="0; 0.5; 1" dur="1s" repeatCount="indefinite"/>
</circle>
</svg>
The easiest solution in CSS with a little hack around SVG containers. You change the container, not the svg. The circle element just fills 100% of the container. And the container artificially makes a circle with a border-radius.
svg {
border-radius: 50%;
transition: all 1s;
}
svg:hover {
width: 200px;
height: 200px;
}
<svg width="100" height="100">
<circle cx="50" cy="50" r="100%"
fill="green" />
</svg>
You can figure out how to implement your own keyframes, if this solution works for you.
And just to be clear, JQuery is a framework. You shouldn't bring up JQuery unless this question is about JQuery's framework. The language you're looking for is "Javascript" and it's in all major browsers by default. You can use Javascript to do this.
const grow = function(radius) {
var circle = document.getElementsByTagName("circle")[0];
circle.setAttribute('r', radius);
}
setTimeout(function() {
grow(100);
setTimeout(function() {
grow(40);
}, 2000);
}, 2000);
circle {
transition: all 1s;
}
<svg width="200" height="200">
<circle cx="100" cy="100" r="40"
fill="green" />
</svg>

Adding Javascript events to SVG <def> elements instead of directly on the children?

I know that it is possible to attach plain-old Javascript event handlers to elements within an SVG tag. I am looking to duplicate very many instances of an object, so I am planning to use the <def> and <use> tags to simplify things a bit. However each of my children items will need to handle "click" and other events. I could define those events for each child, but it would be nice if I could somehow define them ONCE in the initial items, and then just "reuse" that click event. Is this possible?
https://jsfiddle.net/khyp1o0w/
<svg width="400" height="400" viewBox="0 0 400 400">
<defs>
<rect id="someDef" x="0" y="0" width="60" height="30" fill="#f00" />
<!-- ^^ would like to define an event here... -->
</defs>
<use x="150" y="150" xlink:href="#someDef" />
<use x="250" y="250" xlink:href="#someDef" />
<!-- ^^ ... that is used by these guys -->
</svg>
EDIT: Adding example SVG.
IIRC elements targeted by a use element should be internally copied into the <use> element just like if the <use> were an iframe, and the content were cloned.
So this means that events attached on the original node won't be copied onto the copies, unless this event is part of the node markup (inlined). But chrome don't really follow specs here and won't even make it work... So here is an example for FF :
// this won't work
document.getElementById('someDef').addEventListener('click', function() {
this.setAttribute('stroke', randomColor());
});
<svg width="400" height="400" viewBox="0 0 400 400">
<defs>
<script type="application/javascript">
function randomColor() {
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++) {
color += letters[~~(Math.random() * 15)];
}
return color;
}
</script>
<!-- this will work in FF -->
<rect id="someDef" onclick="this.setAttribute('fill',randomColor())" x="0" y="0" width="60" height="30" fill="#f00" />
</defs>
<use x="150" y="150" xlink:href="#someDef" />
<use x="250" y="250" xlink:href="#someDef" />
</svg>
You could of course use event delegation by listening for click events on your root svg element, but this would work only for direct target elements, not for nested ones :
var svg = document.querySelector('svg');
svg.addEventListener('click', function(e) {
var usedTargetID = e.target.getAttributeNS("http://www.w3.org/1999/xlink", 'href');
switch (usedTargetID) {
case '#direct':
clickDirect(e);
break;
case '#nested':
clickNested(e);
break;
default:
return;
}
});
function clickDirect(e) {
// what you seem to want
e.target.setAttribute('fill', randomColor());
}
function clickNested(e) {
// will set both nested...
e.target.setAttribute('fill', randomColor());
}
function randomColor() {
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++) {
color += letters[~~(Math.random() * 15)];
}
return color;
}
<svg width="400" height="400" viewBox="0 0 400 400">
<defs>
<rect id="direct" x="0" y="0" width="60" height="30" />
<g id="nested">
<!-- you can only access this -->
<!-- not its content individually -->
<rect x="80" y="0" width="60" height="30" />
<rect x="20" y="70" width="60" height="30" />
</g>
</defs>
<use x="150" y="50" xlink:href="#direct" />
<use x="250" y="150" xlink:href="#nested" />
</svg>
Or you could also add an event per element, but this would have the same limitations as delegation...

Move element to front without breaking events

I'm trying to fix some event code that I'm working on. In this particular case I need to be able to subscribe to a click event on an svg:circle. However there is also a need to move the circle to the top of the z-index on mousedown such that the element can be dragged over the top of other elements.
The way this is done is to take the element out of the DOM and re-insert it in the correct place using a helper function that I'm using from http://bl.ocks.org/eesur/4e0a69d57d3bfc8a82c2 . The problem with doing this is that the event chain seems to have broken taking the element out of the dom preventing the click event firing.
I'm wondering if anyone can come up with a better way of doing this which will ensure click fires correctly yet still allows changing of the z-index somewhere during the drag lifecycle?
This small example shows how the z-index changes, but the click events don't fire in the console. Clicking on the element again once it's on top does then fire the click correctly.
d3.selectAll("circle")
.on("mousedown", function() {
d3.select(this).moveToFront();
})
.on("click", function() {
var fill = d3.select(this).style("fill");
console.log("You clicked on : " + fill);
});
d3.selection.prototype.moveToFront = function() {
return this.each(function() {
this.parentNode.appendChild(this);
});
};
.red {
fill: red;
}
.blue {
fill: blue;
}
.green {
fill: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.3.13/d3.min.js"></script>
<svg width="600" height="600">
<circle class="red" cx="50" cy="50" r="50" />
<circle class="blue" cx="100" cy="100" r="50" />
<circle class="green" cx="150" cy="150" r="50" />
</svg>
I've managed to come up with a slightly wacky idea, which seems to work, although I'm a little anxious about the performance if there are many elements within the DOM.
The idea is essentially, instead of moving the selection (on mousedown) to the top, to move everything else (of the same type, in this case svg:circle) behind the element that was mouse-downed upon.
d3.selectAll("circle")
.on("mousedown", function() {
var that = this;
d3.select(this.parentNode)
.selectAll("circle")
.filter(function() { return this !== that; })
.moveBehind(that);
})
.on("click", function() {
var fill = d3.select(this).style("fill");
console.log("You clicked on : " + fill);
});
d3.selection.prototype.moveToFront = function() {
return this.each(function() {
this.parentNode.appendChild(this);
});
};
d3.selection.prototype.moveBehind = function(element) {
return this.each(function() {
this.parentNode.insertBefore(this, element);
});
};
.red {
fill: red;
}
.blue {
fill: blue;
}
.green {
fill: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.3.13/d3.min.js"></script>
<svg width="600" height="600">
<circle class="red" cx="50" cy="50" r="50" />
<circle class="blue" cx="100" cy="100" r="50" />
<circle class="green" cx="150" cy="150" r="50" />
</svg>
I wondered if the problem was with d3 so I wrote the equivalent in pure JS and had exactly the same result on Chrome as you did with d3. I was able to get it to work by replacing click with mouseup and comparing it with the mousedown element, like in my comment. You stated in your comment that this solution was not possible in your case, due to other project restrictions. I thought that I'd post my solution anyway, as it was mentioned that behaviour was different in FF and IE.
const circles = Array.from(document.getElementsByTagName('circle'));
let mousedown;
for (let circle of circles) {
circle.addEventListener('mousedown', (e) => {
mousedown = e.target;
e.target.parentNode.appendChild(e.target);
}, false);
circle.addEventListener('mouseup', (e) => {
if (mousedown === e.target) {
console.log('You clicked on : ' + window.getComputedStyle(e.target).fill);
}
mousedown = null;
}, false);
}
.red {
fill: red;
}
.blue {
fill: blue;
}
.green {
fill: green;
}
<svg width="600" height="600">
<circle class="red" cx="50" cy="50" r="50" />
<circle class="blue" cx="100" cy="100" r="50" />
<circle class="green" cx="150" cy="150" r="50" />
</svg>

Categories

Resources