0

After the page has loaded, I want to use JQuery to grab a data attribute from a div element, which contains a color value. I then want to apply the color value to the SVG images. This works fine in Chrome but not IE/Firefox:

$("div.socialmediaicons svg").load(function(event) { 

  var socialcoloractive = $(this).closest("div").data("socialcoloractive");
  var socialcolorinactive = $(this).closest("div").data("socialcolorinactive");

  TweenMax.to(".iconactive svg", 1.5, {
      fill: socialcoloractive,
  });
  TweenMax.to(".iconinactive svg", 1.5, {
      fill: socialcolorinactive,
  });

});

This closest I've found to a solution is this post: Jquery applying css to load div however I don't know how to modify my code using a callback.

Any help is appreciated, thanks.

Community
  • 1
  • 1
GSimon
  • 347
  • 1
  • 3
  • 14
  • 2
    I was under the impression that `load` took a URL as its first argument. – Andy Feb 17 '16 at 13:43
  • That could be my first mistake. I needed to grab the color value of **this** div, so I chose .load () because actions like .on ("click" , function(event)... didn't apply since I'm not using any action to trigger the event, other than page load. – GSimon Feb 17 '16 at 13:47
  • To find out when the SVG is loaded, see https://stackoverflow.com/questions/337293/how-to-check-if-an-embedded-svg-document-is-loaded-in-an-html-page – neuhaus Feb 17 '16 at 13:49
  • 1
    So these are inline `` elements? Change your code to `$("div.socialmediaicons svg").each(function(){...})` and you'll be fine. – pawel Feb 17 '16 at 13:49
  • 1
    @Andy in this context (a function passed as the first argument) jQuery attaches an `load` event handler: http://api.jquery.com/load-event/ – pawel Feb 17 '16 at 13:52
  • Yes they're inline SVGs, I'm using PHP to grab the SVG from the server and inserting them into the page, it's one big beautiful mess :) And using .each () solved the problem, many thanks! Ugh so rusty with JQuery, forgot all about each... – GSimon Feb 17 '16 at 13:53
  • Huh. I suppose they deprecated it because it was confusing. – Andy Feb 17 '16 at 13:54

1 Answers1

1

Since you have inline SVG elements I don't think you have to wait for them to load, but maybe Chrome fires a load event on them. Anyway, you just want to iterate over these elements and change the colors:

$("div.socialmediaicons svg").each(function() { 

  var socialcoloractive = $(this).closest("div").data("socialcoloractive");
  var socialcolorinactive = $(this).closest("div").data("socialcolorinactive");

  TweenMax.to(".iconactive svg", 1.5, {
      fill: socialcoloractive,
  });
  TweenMax.to(".iconinactive svg", 1.5, {
      fill: socialcolorinactive,
  });

});

Simplified demo: https://jsfiddle.net/zs0meqsh/

pawel
  • 35,827
  • 7
  • 56
  • 53