Wizard
Wizard

Reputation: 11295

jQuery appending iframe to div without reload

$("#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.

Upvotes: 1

Views: 13666

Answers (3)

mplungjan
mplungjan

Reputation: 178413

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

Upvotes: 3

LazyDeveloper
LazyDeveloper

Reputation: 619

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

Upvotes: 0

DenseCrab
DenseCrab

Reputation: 1313

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

Upvotes: 1

Related Questions