Difficulties arise when trying to implement the jQuery SVG animation plugin on a straight line

After digging through the documentation, it seems a bit lacking on this topic and a few things just don't seem to add up,

My goal is to make a line follow an animated element by using the same animation variables as those of the box element for the X1 coordinate of the line,

Javascript (using the latest jQuery, SVG Plugin + SVG Animation Plugin)

$(function(){
var balloons = [
$("#box1"),
$("#box2"),
$("#box3")
];

var lines = [
$("#line1"),
$("#line2"),
$("#line3")
];

function act(jqObj, lineX, speed, change) {
jqObj
.animate({'left': change}, speed)
.animate({'left': -change}, speed);

lineX
.animate({svgX1: change}, speed)
.animate({sgvX1: -change}, speed, function() {
    act(jqObj, lineX, speed, change);
});
};
for (i = 0; i < balloons.length; i++) {
var speed = 2000 + Math.random() * 501;
var change = 10 + Math.random() * 26;
act(balloons[i], lines[i], speed, change);
}
});

HTML/CSS

<html>
<head>

<title>Proof of Concept Page</title>
<style type="text/css">
 .html .body {position: absolute;}

.box {
 position: absolute;
        width:100px;
        height:100px;
        position: absolute;
        background-color:red;
}
#box1 {
margin-left:300px; margin-top:60px 
}
#box2 {
margin-left:500px; margin-top:20px 
}
#box3 {
margin-left:700px; margin-top:50px 
}
</style>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery.svg.js"></script>
<script type="text/javascript" src="jquery.svganim.js"></script>
<script type="text/javascript" src="main.js"></script>


</head>
<body>
<div  class="box" id="box1">Proj 1</div>
<div  class="box" id="box2">Proj 2</div>
<div  class="box" id="box3">Proj 3</div>

<svg xmlns="http://www.w3.org/2000/svg" version="1.1">
    <line id="line1" x1="350" y1="160" x2="550" y2="500" style="stroke:rgb(255,0,0);stroke-width:2"/>
    <line id="line2" x1="550" y1="120" x2="550" y2="500" style="stroke:rgb(255,0,0);stroke-width:2"/>
    <line id="line3" x1="750" y1="150" x2="550" y2="500" style="stroke:rgb(255,0,0);stroke-width:2"/>
</svg>

</body></html>

There are a few issues here, first off, the current code sets the X1 position all the way to the left because I haven't specified to add to the original value.

I'm avoiding using '+=change' because it somehow breaks the code, even with a simple numerical value.

Lastly, even if I set the first X1 animation value to 500 and the second to 0, only the first one runs, skipping the second animation. This results in the lines flying to the left and then getting stuck without moving further.

It's likely due to my limited knowledge of jQuery and Javascript, so any constructive assistance would be greatly appreciated.

Answer №1

Exploring the world of SVG was quite the challenge for me as I had never ventured into it before.

After experimenting with it for a few days, I finally came up with this solution:

var $boxes = $(".box"),//coded in HTML
    strings = [];//filled with sgv lines

$('#canvas').svg({
    onLoad: function(svg) {
        var g = svg.group({
            stroke: 'red',
            strokeWidth: 2
        });
        $boxes.each(function(i, el) { // create one string per box.
            strings.push(svg.line(g, parseInt($(el).css('left')), 18+parseInt($(el).css('top')), 50, 200));
        });
    }
});

//animate the boxes
$boxes.each(function(i, el) {
    var speed = 2000 + Math.random() * 501,
        change = 10 + Math.random() * 26,
        jqObj = $(el),
        initial_left = parseInt(jqObj.css('left')) || 0;
    (function act() {
        jqObj.animate({
            'left': initial_left + change
        }, {
            duration: speed,
            step: function() { 
                $(strings[i]).animate({
                    svgX1: jqObj.css('left')
                }, 0);
            }
        }).animate({
            'left': initial_left - change
        }, {
            duration: speed,
            step: function() { 
                $(strings[i]).animate({
                    svgX1: jqObj.css('left')
                }, 0);
            },
            complete: act
        });
    })();
});

Check out the DEMO.

This setup is essentially a combination of SVG strings and non-SVG text boxes that are animated to give the appearance of being linked together.

The code may not be the most straightforward to follow but I'm happy to have achieved a functional result. It was a learning experience for me and hopefully, it can serve a purpose for you too.

EDIT - additional explanation:

Your understanding: You're on the right track. I'm utilizing an alternate form of animate which involves using .animate(properties, options), where both properties and options are JavaScript objects. This version of the method allows for a step option to be specified, dictating an operation to occur at each step of the animation – in this case, adjusting the position of the balloon string's top end.

i and 'el': The jQuery .each() methods provide a convenient way to iterate through elements in an array, DOM nodes within a jQuery container, or properties of a plain JavaScript object. Both variations of .each() accept a callback function defining the action to be performed during each iteration. This function also receives two parameters representing either index and value (for arrays and jQuery containers) or key and value (for plain JS objects). By naming these parameters as i (index) and el (element), we can refer to them within the callback function more clearly.

Line animation: While the line does only move slightly before stopping, this movement takes place within the step callback, which is executed once per step of the animation – continuously aligning the line with the object it is connected to.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Incorporating fresh CSS styles through Selenium

I am attempting to showcase all the prices available on this page using Selenium and Chrome in order to capture a screenshot. By default, only 3 prices are visible. Is there a way to disable the slick-slider so that all 5 prices can be seen? I have tried r ...

When there are multiple elements within the parent container, the CSS hover margin-top alteration fails to take effect

I am currently working on creating a dynamic menu bar that has elements which smoothly move upwards on hover. However, I have encountered an issue where this movement effect only works when the parent container contains exactly one element (such as in titl ...

Uploading Images Dynamically with Ajax and jQuery in PHP

[Resolved Previous Issue] Recently, I obtained an image upload script that utilizes Ajax and jQuery. My goal is to restrict the maximum number of uploads to just 8 images. Any suggestions or advice would be greatly appreciated. Source of Download: ...

Enhancing Game Security through PHP and jQuery

I am currently developing a game using PHP and jQuery, but I am facing some security issues. The game involves typing combinations correctly, and when the player does so, jQuery sends an ajax request to PHP which then adds 10 points to their session. Below ...

Implement a Horizontal view feature in the FullCalendar API

In my project, I am utilizing the full-calendar API to create a vertical resource view. Everything works perfectly when I have around 10 resources. However, once I increase the number of resources in my project, the view becomes distorted. https://i.sstat ...

The issue of jQuery's .last() function triggering multiple times with just a single click on the last

I currently have a set of tabs containing radio buttons and I need to trigger an event when the last option is selected (meaning any radio button within the final tab, not just the last radio button). Below is the HTML code: <div id="smartwizard" clas ...

What is the method for utilizing the value component as the key for the second component?

In my JSON data below: [{"id":19,"text":"A-Z CLI 19/03/2015"},{"id":36,"text":"Wavetel Retail1"},{"id":37,"text":"Wavetel A2Z Platinum"},{"id":38,"text":"Wavetel A2Z Gold"},{"id":40,"text":"mysql test2"},{"id":63,"text":"inbound test"},{"id":137,"text": ...

Incorporating PHP script within a stylesheet

Is it possible to include php code within a css file for adding conditions to css properties? styles.css <?php if($suserid == 2) { ?> .proverb { border:0px solid blue; margin-left:34px; width:250px !important; margin-top:6px; } <?php } e ...

I'm having trouble making Jquery's $.get function work

I've been attempting to use the $.get function to retrieve a response from a PHP script, but I'm not having any luck. Nothing seems to be happening. Here is the jQuery code I am using: $(document).ready( function(){ $('#button').c ...

Best practice is to include the script on a page that is being loaded through ajax

I currently have a webpage named index.php. This page contains a form that takes input numbers and uses ajax to process the form, displaying the result on the same page. <!DOCTYPE html> <html> <head> <meta charset="utf-8"> ...

There is no data in the $_POST array

Currently, I am developing a simple application running locally with XAMPP and PHPStorm v9. The issue I am facing is that the server handler for my AJAX request is returning an empty $_POST array. This problem has left me puzzled, and I cannot figure out w ...

The fixed table header is covering the navigation bar

Currently, I am building a website using Bootstrap and the DataTables library. The problem I am encountering is that the sticky table header is working fine, but it overlaps with the sticky nav bar. Is there a way to make the navbar "push down" the table h ...

Why is my console showing a SyntaxError with JSON.parse and an unexpected character?

I am facing an issue. When I attempt to call a PHP page for some data with specific requested parameters using AJAX asynchronous call, I encounter the following error: SyntaxError: JSON.parse: unexpected character var jsonData = $.ajax({ u ...

Trouble accessing JSON file on FileZilla/FTP server

When I transfer my project to the FTP server, the JSON file I am using for data is not functioning properly. However, when I run the program on XAMP, my local server, it works perfectly. Upon inspecting the element on the FTP server, I noticed that the JSO ...

Implementing Canvas Offset in a jQuery Mobile Environment

I have positioned a pen ready for use at this location. http://codepen.io/prantikv/pen/LEbRKY Currently, I am utilizing a canvas to track mouse movements or touch input. It performs as expected when jQuery or jQuery mobile is not included. However, upon ...

The CSS method for changing the content URL is experiencing difficulties in Firefox

Css: .woocommerce-placeholder.wp-post-image { content: url("DSC0926-1.jpg"); } /*for firefox*/ .woocommerce-placeholder.wp-post-image::before { content: url("DSC0926-1.jpg"); } HTML <img src="placeholder.png" alt="Placeholder" class="woocomm ...

The .map() function in jQuery produces an array as output, not a collection of matched elements (jQuery object)

I am facing an issue when utilizing the .map() method, as it is returning an array with what seems to be two nodes (not a jQuery object/matched set). I have tried applying a class to this set but nothing seems to happen. $('input#substance, input[nam ...

The Materialize CSS tabs are aligning vertically below each other, but functioning correctly upon refreshing the page

When using materialize css tabs, all the divs load one below the other on the initial page load. If I refresh the page, it starts behaving properly. <div class="row"> <div class="col s12"> <ul class="tabs"> <li class="tab col s ...

Using jQuery .animate() leading to erratic input movements

I am currently utilizing jQuery's .animate() feature to create a smooth animation effect on the width of a <div> element when a child <input> is in focus. Nevertheless, I'm encountering an issue where the input field jumps up and down ...

Executing Javascript in Python Environment

I'm currently working on developing an HTML document parser using Python. Since I have a strong understanding of jQuery, I am interested in leveraging its traversal capabilities to parse these HTML files and then send the gathered data back to my Pyth ...