shramee
shramee

Reputation: 5099

Changing CSS properties of elements in iframe

Here is what my typical field looks like...

<input class='live-field' type=color data-el='#header' data-prop='background'>

Every field has class live-field, attribute data-el targetted element(s) selector and data-prop with property to change.

Every time the value in input is changed I want the CSS property data-prop of element(s) selected by data-el to be changed to value of input.

Right now I have this...

$('.live-field').change(function(){
  var $t = $(this);
  $( $t.data('el') ).css( $t.data('prop'), $t.val() )
});

Apparently this wont work coz $( $t.data('el') ) will look for elements in the doc not in iFrame...

Here's my plunker. https://plnkr.co/edit/uJcSwtE2xheJnS1vOdde?p=preview

For example... If I change value of this input...

<input class='live-field' type=color data-el='#header' data-prop='background'>

to #f00, the background color of element #header in iframe should be changed to #f00 (red).

Upvotes: 0

Views: 108

Answers (1)

hootstheowl
hootstheowl

Reputation: 261

You should be able to use jQuery's .contents() method to access the iFrame DOM, so long as the iframe shares the same domain as the interactive content. Changing your onChange event to use the following code should do the trick:

$('.live-field').change(function(){
  var $t = $(this);
  $('#iframe').contents().find( $t.data('el') ).css( $t.data('prop'), $t.val() )
});

Edit for clarification: The iFrame and your inputs must share the same domain, otherwise the browser will not allow this type of functionality. See this article on Same-Origin Policy for more info on why.

Upvotes: 2

Related Questions