Integrate javascript into a Wordpress loop while specifying which class to target

Seeking assistance on integrating category icons with animations using snap.svg in a Wordpress page.

  • I have inserted a div containing an svg within the loop that generates the page (index.php). The divs display correctly with the appropriate size of the svg, but they appear blank.
  • The svg has a class targeted by the js file.
  • The js file is functioning correctly independently, however, the animation only displays in the first div of that class and replicates based on the number of posts within that category present on the page.

I attempted to use "each()" function at the start of the js script, but it does not position the animations correctly. I also experimented with adding double "each()" for svg location and including the snap object in the svg itself without success.

I tried assigning unique ids to each svg using the post-id, but couldn't figure out how to pass the id from the loop to the js file due to my limited php and js skills.

If you have a solution to this issue, please provide your insights. Thank you!

// Below is a snippet of the js code (trimmed for brevity):

jQuery(document).ready(function(){ 

jQuery(".d-icon").each(function() {

var dicon = Snap(".d-icon");

var dfirepath = dicon.path("M250 377 C"+ ......+ z").attr({ id: "dfirepath", class: "dfire", fill: "none", }); 

function animpath(){  dfirepath.animate({ 'd':"M250 377 C"+(Math.floor(Math.random() * 20 + 271))+ .....+ z" }, 200, mina.linear);};

function setIntervalX(callback, delay, repetitions, complete) { var x = 0; var intervalID = window.setInterval(function () { callback(); if (++x === repetitions) { window.clearInterval(intervalID);  complete();} }, delay); }

var dman = dicon.path("m136 ..... 0z").attr({ id: "dman", class:"dman", fill: "#222", transform: "r70",  }); 

var dslip = dicon.path("m307 ..... 0z").attr({ id: "dslip", class:"dslip", fill: "#196ff1", transform:"s0 0"});

var dani1 = function() { dslip.animate({ transform: "s1 1"}, 500, dani2); }
var dani2 = function() { dman.animate({ transform: 'r0  ' + dman.getBBox().cx + ' ' + dman.getBBox(0).cy, opacity:"1" }, 500, dani3 ); }
var dani3 = function() { dslip.animate({ transform: "s0 0"}, 300); dman.animate({ transform: "s0 0"}, 300, dani4); }
var dani4 = function() { dfirepath.animate({fill: "#d62a2a"}, 30, dani5); } 
var dani5 = function() { setIntervalX(animpath, 200, 10, dani6); }
var dani6 = function() { dfirepath.animate({fill: "#fff"}, 30); dman.animate({ transform: "s1 1"}, 100); } 

dani1();  });  });

Answer №1

It seems like the issue lies right here:

let icon = Snap(".d-icon");

The problem is that you are passing a query selector to the Snap constructor, causing it to always target the first DOM element with that class. This results in the animations appearing in the wrong place.

To resolve this, there are two possible solutions:

  1. Specify the width and height within the constructor, for example let icon = Snap(800, 600);

  2. Since jQuery is being used, you can refer to the current element inside the .each() function using $(this). In your case, you could use jQuery(this) instead of just $().

Keep in mind that Snap might require a DOM object rather than a jQuery object. To access the DOM object in jQuery, append [0] after this. If let icon = Snap(jQuery(this)); doesn't work, try

let icon = Snap(jQuery(this)[0]);

Furthermore, if you have multiple elements with the same ID attribute like .attr({id : '...' in your code, consider adding a numerical value to avoid duplicate IDs. Although this may not cause issues currently as they are within an SVG element, it's a good practice to prevent potential conflicts in the future.

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

Managing the state of dynamically changing forms in React

I am dealing with a dynamic form that expands in an unpredictable manner based on user input. I'm able to capture all the user inputs from the form as React State. When the form is submitted, I convert the State (JSON) into a YAML file. The JSON stru ...

The valueChanges event of a Reactive Form is activated whenever options from a datalist are selected

Whenever a user types into the input field, I am making an API call to retrieve and display data in a datalist for autocompletion (typeahead). control.get('city').valueChanges.pipe( map((searchText) => searchText.trim().toLowerCase()), fi ...

The ul cannot be hidden if there are no li elements within it

Currently, I am attempting to hide the unordered list (ul) on a specific page using AJAX due to certain sections of the site being Ajax-based. <ul class="sub-nav-20-m" id="filtersList_m"> </ul> Below is the code that I hav ...

Why isn't the ag-grid appearing within the function?

As a newcomer to using agGrid, please excuse any mistakes I may make. Previously, I worked with Kendo Grid on AngularJS, but we decided to switch to a different grid, so we're currently exploring agGrid. Below is a sample of agGrid that is functionin ...

Retrieve and utilize the dynamically produced values from the application's app.js in a script that is accessed using

In my Express.js Node web app, I generate a string in app.js during initialization: // app.js var mongourl = /* generated based on process.env.VCAP_SERVICES constant */; There is a script that I import into app.js using require(): // app.js var db = req ...

Issue with Vue class binding failing to update when state is modified

I'm attempting to utilize Vue class binding depending on the index within the v-for loop. While I can see that the state in Vue dev tools is changing correctly, the class name itself isn't being updated. <div class="group" v-for= ...

Utilizing a material-ui button within a React application as the trigger for a Popup using MuiThemeProvider

I want to trigger a Popup in React using a button with a custom theme: <PopUp modal trigger={ <MuiThemeProvider theme={buttonTheme}> <Button variant="contained" color="secondary">Excluir& ...

Custom hooks in Next.js do not have access to the localStorage object

I've encountered an issue with my custom useLocalStorage hook. It works perfectly fine with create-react-app, but when I try to use it with Next.js, the value in the initial state on line 3 returns undefined. Is there a way to bypass server-side rend ...

There seems to be an issue with Affix functionality in Bootstrap 4 (alpha version)

As detailed in the Bootstrap 3 documentation, I have included the following attributes in a navbar: <nav class="navbar no-margin-bottom" data-spy="affix" data-offset-top="90" > ... </nav> Unfortunately, when scrolling down the page with Boots ...

How can I ensure that my function only returns a value once the ajax call has finished?

Using mootools, I have a function that triggers an ajax script to retrieve a value. However, the function seems to return before the AJAX call is completed! What could be causing this issue... function getCredits() { var loadGlobalTab = new Request.J ...

Attempting to retrieve and save data in a variable using React Native

click here for image referenceI am a beginner in react-native and I recently attempted to use fetch to access an API. While I successfully managed to print the result on the console, I encountered difficulty in displaying it on a mobile screen. Below is a ...

Verifying child attributes within a collection using AngularJS expressions

Is there a way to write an angular expression that can check each child item in a list and return true if any child has a specific property value? My issue involves a chart legend generated by an ng-repeat expression. I want the wrapping element to be sho ...

Visual Verification

I'm currently working on a NestJS application that serves images with authentication requirements. I have implemented JWT for authentication, but I encountered an issue when trying to display the image in an img tag because I cannot attach the Authori ...

Ways to efficiently transfer multiple files from a server to a client using Express in NodeJS

I am working on a NodeJS server to transfer various files, such as images, css files, and js files, to clients. Currently, I have the following code snippet for sending individual files: app.get('/js/client.js', function (req, res) { res.sendF ...

The function `splitPinCodes.split(',')` is causing a malfunction

I am encountering an issue with validating the input data. The input text area should contain 6-digit zip codes separated by commas. I have implemented the ng-change="convertToArray()" method in Angular for the input text area. If I enter more than 6 digi ...

Tips for clearing an input value in WordPress using the Ultimate Member plugin before sending it

I'm facing a challenge with removing an input value before submitting a profile form on Wordpress using the Ultimate Member plugin. I've been stuck on this issue for a week now. The problem arises from having conditional fields in the profile fo ...

Chipped bricks (possibly a vintage piece)

Although I thought the setup was straightforward, it seems like I am missing something... Here is the HTML structure with a simple fixed-width 2-column layout: <div class="container_12"> <div class="grid_masonry"> ... </div> <d ...

Grabbing <object> HTML using jQuery

One example on my webpage is the presence of the following <object>: <object id="obj1" data="URL"></object> Could you please suggest a method to access this html object using jQuery? ...

Create a mechanism in the API to ensure that only positive values greater than or equal to 0 are accepted

My goal is to process the API result and filter out any values less than 0. I've attempted to implement this feature, but so far without success: private handleChart(data: Object): void { const series = []; for (const [key, value] of Object.e ...

Navigating between pages using React-router-dom

Just implemented a simple navigation using react-router-dom. Managed to get it working with this.props.history.push('/pathName'); But I'm not entirely sure if my understanding and approach are correct. Any advice on correcting my mistakes wo ...