Dylan Thielking
Dylan Thielking

Reputation: 1

Rails JavaScript code isn't executing when page is accessed with link

I'm having a strange problem... I have a page that uses some JavaScript to make an image inside of an SVG draggable and it works. But not when accessing the page with a link from another page. Reloading the page after the initial load works perfectly and even visiting the page directly via the URL bar works. I am at a loss as to what to try.

In my research, I stumbled upon this answer: Rails, javascript not loading after clicking through link_to helper

But upon trying all the solutions, none seemed to fix my problem, though it could easily be that I wasn't applying them to my code correctly. My SVG element as a 'onload' attribute that points to the 'makeDraggable(evt)' function, and most of the solutions on there made it so it couldn't access that function.

Here's the code for the initial link that I generate:

<%= link_to 'Play', canvas_path(:game => @game) %>

Here's my HTML code:

<div id="container">
  <svg id="svg" onload="makeDraggable(evt)" width="50%" height="90%" 
  xmlns="http://www.w3.org/2000/svg">
    <defs>
      <pattern id="grid" width="40" height="40" 
       patternUnits="userSpaceOnUse">
        <rect width="80" height="80" fill="url(#smallGrid)"/>
        <path d="M 80 0 L 0 0 0 80" fill="none" stroke="black" stroke- 
        width="1"/>
      </pattern>
    </defs>
    <%@game_assets.each do |asset| %>
    <image class="draggable" id="<%=asset.id %>" height="536" width="536" 
    xlink:href="<%= url_for(asset.image) %>" x="<%= asset.position_x %>" y=" 
    <%= asset.position_y %>" style="position: relative;" 
    transform="translate(0 0)"></image>
    <% end %>
    <rect width="100%" height="100%"  style="pointer-events: none;" 
    fill="url(#grid)" />
  </svg>
</div>

And here is my JavaScript:

$(document).on('turbolinks:load', function () {
    $('#svg').draggable();
    $('.draggable').draggable();
});

// Makes content inside of SVG draggable
// Source: http://www.petercollingridge.co.uk/tutorials/svg/interactive/dragging/
function makeDraggable(evt) {
    var svg = evt.target;

    svg.addEventListener('mousedown', startDrag);
    svg.addEventListener('mousemove', drag);
    svg.addEventListener('mouseup', endDrag);
    svg.addEventListener('mouseleave', endDrag);
    svg.addEventListener('touchstart', startDrag);
    svg.addEventListener('touchmove', drag);
    svg.addEventListener('touchend', endDrag);
    svg.addEventListener('touchleave', endDrag);
    svg.addEventListener('touchcancel', endDrag);

    var selectedElement, offset, transform,
        bbox, minX, maxX, minY, maxY, confined;

    var boundaryX1 = 10.5;
    var boundaryX2 = 30;
    var boundaryY1 = 2.2;
    var boundaryY2 = 19.2;

    function getMousePosition(evt) {
        var CTM = svg.getScreenCTM();
        if (evt.touches) { evt = evt.touches[0]; }
        return {
            x: (evt.clientX - CTM.e) / CTM.a,
            y: (evt.clientY - CTM.f) / CTM.d
        };
    }

    function startDrag(evt) {
        if (evt.target.classList.contains('draggable')) {
            selectedElement = evt.target;
            offset = getMousePosition(evt);

            console.log("started dragging")

            // Make sure the first transform on the element is a translate transform
            var transforms = selectedElement.transform.baseVal;

            if (transforms.length === 0 || transforms.getItem(0).type !== 
                SVGTransform.SVG_TRANSFORM_TRANSLATE) {
                // Create an transform that translates by (0, 0)
                var translate = svg.createSVGTransform();
                translate.setTranslate(0, 0);
                selectedElement.transform.baseVal.insertItemBefore(translate, 
              0);
            }

            // Get initial translation
            transform = transforms.getItem(0);
            offset.x -= transform.matrix.e;
            offset.y -= transform.matrix.f;

            confined = evt.target.classList.contains('confine');
            if (confined) {
                bbox = selectedElement.getBBox();
                minX = boundaryX1 - bbox.x;
                maxX = boundaryX2 - bbox.x - bbox.width;
                minY = boundaryY1 - bbox.y;
                maxY = boundaryY2 - bbox.y - bbox.height;
            }
        }
    }

    function drag(evt) {
        if (selectedElement) {
            evt.preventDefault();
            console.log("drag triggered")

            var coord = getMousePosition(evt);
            var dx = coord.x - offset.x;
            var dy = coord.y - offset.y;

            if (confined) {
                if (dx < minX) { dx = minX; }
                else if (dx > maxX) { dx = maxX; }
                if (dy < minY) { dy = minY; }
                else if (dy > maxY) { dy = maxY; }
            }

            transform.setTranslate(dx, dy);
        }
    }

    function endDrag(evt) {
        selectedElement = false;
    }
}

If anyone could shed some light on what is happening, I would greatly appreciate it.

Also, forgive me if my formatting of this post isn't quite correct. First time poster :)

Upvotes: 0

Views: 54

Answers (1)

Abhishek Aravindan
Abhishek Aravindan

Reputation: 1482

Remove onload="makeDraggable(evt)" from the #svg element, because the onload function won't work when written inline when you're using turbolinks (as Rails does).

Then add the following to your JS:

$(document).on('turbolinks:load', function () {
 if($('#svg').length == 1){
  makeDraggable($('#svg'));
 }
});

and change var svg = evt.target; to var svg = evt;

Upvotes: 1

Related Questions