1

I use third-party player which creates dynamically after page load.

I try to add elements to it with jQuery .prepend() but nothing happens.

Initial player look like:

<div id="player"></div>

After page load Player Script modify the player and it become looks like:

<iframe id="player">
  <div id="play_button"></div>
  <div id="settings_button"></div>
</iframe>

Then plugin call event "onPlayerReady" and player starts playback. After this I try to add <div id="ad_icon">AD</div> to div <div id="settings_button"></div> with such code:

function onPlayerReady(){
    console.log($("#settings_button").length); // returns '0'
    $("#settings_button").prepend("<div id='ad_icon'>AD</div>");
}

but nothing happens. Seems like div with id=settings_button doesn't exist for jQuery. Console.log $("#settings_button").length returns 0. I see new elements in the page code but jQuery returns nothing.

Any ideas how can I use .prepend() function with dynamically created elements in iframe (which were created not by me)?

Kir Mazur
  • 997
  • 2
  • 13
  • 27

3 Answers3

1

You should use .contents() to access elements inside the iframe.
So the code will be :

$("#player").contents().find("#settings_button").prepend("<div id='ad_icon'>AD</div>");
Smankusors
  • 377
  • 2
  • 8
  • 21
  • Great, answer! Thanks! Forgot about .contents(). Unfortunately the frame is cross-origin, so I still can't get an info. Do you know some other options? – Kir Mazur Nov 24 '16 at 13:35
  • Well according to the Google results, unfortunately no without change the browser settings ;_; – Smankusors Nov 24 '16 at 14:17
  • maybe you want to read : [another StackOverflow](http://stackoverflow.com/questions/3083112/jquery-cross-domain-iframe-scripting) – Smankusors Nov 24 '16 at 14:18
0

You need to bind events using event delegation,

As your elements are added at runtime, you need to put this event delegation,

$(document).on('click', '#settings_button', function(){
          $(this).prepend("<div id='ad_icon'>AD</div>");
});
ScanQR
  • 3,740
  • 1
  • 13
  • 30
0

Try this code,

 $(document).ready(function () {
    $('#player').bind('DOMNodeInserted', function (event) {
        $("#settings_button").prepend("<div id='ad_icon'>AD</div>");
    });
});   
Vaibhav shetty
  • 372
  • 1
  • 4
  • 15
  • This would prepend a new div **on each** new inserted DOM (whatever it is) and btw, because it will insert a new node using prepend() method, it would throw a stack error (recursive issue). I guess `$('#player').one('DOMNodeInserted', function (event) {...});` would fix it but using observer is bad practice usually. That's said, this is for sure more relevant answer than the two other ones already posted – A. Wolff Nov 24 '16 at 11:34