Issues with Raphael function in a loop with Javascript

Still getting the hang of Javascript, so please be patient...

I've set up two fiddles for comparison. The only variation between them is that one has a text object as a title while the other doesn't. Surprisingly, this tiny detail completely alters the behavior when hovering over the circle objects.

My goal is to replicate the functionality of the second fiddle, even when there's a title like in the first fiddle.

I'm struggling to understand how to extract my function from the loop to prevent JSHint from throwing errors at me... It seems like my confusion surrounding closure, binding, and similar concepts might be causing this issue.

Fiddle 1 with title, strange mouseover behavior

Fiddle 2 no title, normal mouseover interaction

//Code for Fiddle 1: the same code except the part indicated is excluded in Fiddle 2

var rsr = Raphael("holder", '1160', '1400');

// this next section will be removed in the second fiddle
rsr.text(220, 50, 'Title').attr({
    'font-size': 32,
    'text-anchor': 'middle'
});
// end of exclusion in Fiddle 2

var cir = []; // an array to hold circles
var xco = [206, 144.9, 317.4, 317.5]; // x coordinates of circle centers
var yco = [167.7, 231.8, 191.4, 256.8]; // y coordinates of circle centers
var rd = [25.5, 46, 34, 18.5]; // radii of circles
var circcolr = ['#939dac', '#000000', '#ecea5a', '#0da9f2']; // fill colors of circles
for (var i = 0; i < 4; i++) { 
    cir[i] = rsr.circle(xco[i], yco[i], rd[i]);
    cir[i].attr({
        fill: circcolr[i],
            'fill-opacity': 1,
        stroke: 'none'
    });
}

for (var i in cir) {
    (function (st) {
        console.log(st.id);
        st.node.onmouseover = function () {
            st.animate({
                r: rd[st.id] * 1.2
            }, 200);
        };
        st.node.onmouseout = function () {
            st.animate({
                r: rd[st.id]
            }, 100);
        };
    })(cir[i]);
}

Answer №1

The solution lies within the console logs you have already implemented.

  • When you first create 5 objects, the title is assigned id = 0 and the circles are assigned ids 1, 2, 3, and 4 respectively.

  • In the second scenario, only circles are created with ids 0, 1, 2, and 3

If you adjust the code at the end as follows, it resolves the issue...

for (var i in cir) {
    (function (cir, i) {
        console.log(cir[i]);
        cir[i].node.onmouseover = function () {
            cir[i].animate({
                r: rd[i] * 1.2
            }, 200);
        };
        cir[i].node.onmouseout = function () {
            cir[i].animate({
                r: rd[i]
            }, 100);
        };
    })(cir, i);
}

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

Integrating third-party libraries with GWT using JSNI

I am currently working on integrating Opentip into a GWT project. Since some of my widgets are loaded from Java rather than HTML, it seems like I will need to utilize JSNI in order to properly bind those tooltips. Here is the progress I have made so far: ...

Utilizing external clicks with Lit-Elements in your project

Currently, I am working on developing a custom dropdown web component using LitElements. In the process of implementing a feature that closes the dropdown when clicking outside of it, I have encountered some unexpected behavior that is hindering my progres ...

Combining two sets of data into one powerful tool: ngx-charts for Angular 2

After successfully creating a component chart using ngx-charts in angular 2 and pulling data from data.ts, I am now looking to reuse the same component to display a second chart with a different data set (data2.ts). Is this even possible? Can someone guide ...

Unique Dropdown Menu Design with Creative Styling

Currently, I am in the process of developing a small project that requires the use of a drop-down list. During my research, I came across a visually appealing drop-down list that did not have default styling applied to it. I am interested in learning how ...

Tips for organizing an event using AngularJS within a set timeframe

My goal is to compare the current time with a specified start and end time in order to display a message on the page when the current time falls within that range. For example, let's say startTime = 10:30 AM and endTime = 1:30 PM. How can I achieve d ...

Pressing the Button Increases the Counter, However the Counter Resets After

My goal is to create a basic counter with increment and reset buttons. When I click on the increment button, the counter properly goes from 0 to 1 (I can confirm this by checking the console log in Chrome). The issue arises when, after incrementing, the c ...

Ways to protect against form hacking on the client-side

As I contemplate the benefits and drawbacks of utilizing frameworks like VueJS, a question arises that transcends my current coding concerns. Specifically, should form validation be executed on the client side or through server-side processing by a control ...

AngularJS Splice Function Used to Remove Selected Items from List

I previously inquired about a method to remove items from the Grid and received a solution involving the Filter method. However, I am specifically looking for a way to remove items using the Splice Function instead. You can find my original question here: ...

Optimal solution: How can we achieve a fixed header and a scrollable body for a table in the

Is there a better way to achieve this? HTML table with fixed headers? Seeking a solution for creating a table with a scrollable body and a static header. After exploring various options, it seems like most available codes are unreliable, not compatib ...

I am looking to save the data entered in an HTML form directly into a JSON file within the webpage

I am currently storing the value in an array on the server, but I would like to store it only on the client side within the webpage. I want to write the form data from the HTML form into a JSON file that remains on the page itself and is not sent to the ...

Refreshing Facebook comments does not occur when using FB.XFBML.parse()

My JavaScript photo gallery dynamically loads images from an API onto the page when users click on a thumbnail. I want users to be able to leave Facebook comments on each image, so I've included a Facebook comments element on the page containing the g ...

Generating a transient image upon a key press event using JavaScript

I'm currently working on a personal website as a fun project, and I had the idea of adding an easter egg feature where if a user presses the letter "e" anywhere on the site, a small image of a speech balloon will briefly appear and then disappear. Ide ...

Generate a new subprocess and terminate it once the operation has been initiated

Using child processes in the following way: var exec = require('child_process').exec; var cmd = 'npm install async --save'; exec(cmd, function(error, stdout, stderr) { console.log('stdout: ' + stdout); ...

What steps can I take to prevent the [Vue warn]: Potential infinite update loop detected in a component render function issue in my VueJS project?

What are some tips to prevent an infinite update loop in a component render function using VUEJS? I have created a simple show password button with the following structure: <div class="mt-4 switchContainerGenPassword"> <div class="switchGene ...

Transmitting a JSON object and a file simultaneously via FormData in an AJAX request, then retrieving the JSON object in PHP

I need assistance with sending a JSON object along with a file in an AJAX call. Here is my current setup: Javascript $('#btn').on('click', function(){ var file_data = $('#imgFile').prop('files')[0]; var for ...

What purpose do controller.$viewValue and controller.$modelValue serve in the Angular framework?

I'm confused about the connection between scope.ngModel and controller.$viewValue/controller.$modelValue/controller.$setViewValue(). I'm specifically unsure of the purpose of the latter three. Take a look at this jsfiddle: <input type="text" ...

How to retrieve data from a JSON object using JavaScript

Forgive my ignorance, but I'm attempting to showcase the value of content by executing console.log(teams);. Upon inspecting Firebug on Mozilla, this is what I discovered: [Object { id= "50", content= "Team 1 test" , date="Tue Mar 26 2013 12:00:00" ...

Create JavaScript code with PHP

Looking to dynamically generate the column definitions for a Datatable. Here are the columns: "columns": [ { "data": "id", "orderable": false }, { "data": "code" }, { "data": "name" }, { "data": "created", " ...

Build a row within an HTML table that is devoid of both an ID and a class

Creating an additional row in an HTML table is a common task, but it can become tricky when dealing with multiple forms and tables on one page. In my case, I have a form that contains only a table element, and I want to move some columns from the first row ...

Issue arising during reconnection following a disconnection in the node-redis client

I'm struggling to understand why the SocketClosedUnexpectedlyError error is being triggered in the code snippet below: const redisClient = require('redis').createClient(); redisClient.connect().then(function() { return redisClient.disconn ...