1
$("#div").append('<iframe width="200" height="100" src="https://www.youtube.com/embed/zoMYU_nOGNg?rel=0&amp;showinfo=0&amp;enablejsapi=1" frameborder="0" allowfullscreen=""></iframe>');

By using this example append cause page reload, maybe are some issue to load youtube iframe without reloading page

Demo: https://jsfiddle.net/0uqtn0u5/

My observation is wrong it's not realod the page.

Wizard
  • 10,985
  • 38
  • 91
  • 165

3 Answers3

3

Some browsers will treat <button> as a submit button and submit to the same page regardless of the button being a child of a form or not.

Change to

$('button').on('click', function(e){
  e.preventDefault();
  $("#youtube").append('<iframe width="200" height="100" src="https://www.youtube.com/embed/zoMYU_nOGNg?rel=0&amp;showinfo=0&amp;enablejsapi=1" frameborder="0" allowfullscreen=""></iframe>');
});

or add type="button" to it.

If you DO have a form, instead do make the button a submit button and prevent the default action on the form submit:

$('form').on('submit', function(e){
  e.preventDefault();
  $("#youtube").append('<iframe width="200" height="100" src="https://www.youtube.com/embed/zoMYU_nOGNg?rel=0&amp;showinfo=0&amp;enablejsapi=1" frameborder="0" allowfullscreen=""></iframe>');
});

There is no other reason for the page to reload. Your code should not and indeed does not reload anything in Chrome

mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • I think you pointed the right thing, OP was submiting a form i guess. But that's wrong: `submit to the same page regardless of the button being a child of a form or not` – A. Wolff May 04 '16 at 08:25
  • @wizard: did it solve the problem, or is the page not actually reloading? – mplungjan May 04 '16 at 08:27
  • @mplungjan If you check OP jsfiddle, it is clear his observation is wrong, the page isn't reloaded – A. Wolff May 04 '16 at 08:28
  • @A.Wolff - I agree. It will not reload in most browsers and indeed does not reload in Chrome – mplungjan May 04 '16 at 08:29
1

Take a look: How to prevent an iframe from reloading when moving it in the DOM

"If you're trying to move it visually, you can try modifying the CSS to use absolute positioning or some other adjustments.

However, if you're trying to actually pull it out of the DOM and insert it somewhere else, you won't be able to avoid a reload."

~ John Fisher

Also: https://stackoverflow.com/a/8318401/5444802

"It isn't possible to move an iframe from one place in the dom to another without it reloading."

~ Kevin B

Community
  • 1
  • 1
DenseCrab
  • 1,273
  • 11
  • 22
0

Check the youtube api for iframe embedding https://developers.google.com/youtube/iframe_api_reference#Loading_a_Video_Player

LazyDeveloper
  • 599
  • 3
  • 8