Seb D
Seb D

Reputation: 139

Change X and Y value of SVG elements with JavaScript

I have a tspan element and I want it to move based on mouse position.

$(document).mousemove(function(e) {
  //something that makes it so the x value is the same as e.pageX
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<svg viewBox="0 0 1778.426 150.81301">
<g transform="translate(0 -146.19)">
<rect x="15.368" y="225.71" width="1723.8" height="11.733"/>
<rect id="bar" transform="rotate(90)" x="215.19" y="-15.368" width="32.781" height="11.733"/>
</svg>

How can I do it without using transform?

Upvotes: 1

Views: 2176

Answers (1)

HoldOffHunger
HoldOffHunger

Reputation: 20881

You can set the attribute of it directly with attr(), for instance...

<script>
  $(document).mousemove(function(e) {
  //something that makes it so the x value is the same as e.pageX
    $('#bar').attr('x', e.pageX);
});
</script>

I have put together a small demo sandbox at JSBIN: JSBIN Demo.

You may need to tweak this a bit further, but I am seeing some movement of the #bar element in document mousemove events.

Upvotes: 1

Related Questions