Arya
Arya

Reputation: 8995

Changing iframe src with jquery

I am trying to change my iframe src and reload the iframe with the following code

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<script>
  $('#changeframe').click(function () {
  $('#declinedframe').attr('src', 'http://stackoverflow.com');
  });
</script>


<input type="button" id="changeframe" value="Change">

<iframe id="declinedframe" class="embed-responsive-item" src="http://forgezilla.com" height="585" width="100%" ></iframe>

When I click "Change" on the button nothing happens. What I am doing wrong?

Upvotes: 4

Views: 14783

Answers (2)

mplungjan
mplungjan

Reputation: 178403

  1. If the code is as it is in your example, you need to wrap the jQuery in
    $(function() { ... }); or move it below the html since the button does not exist when the script runs
  2. Look in the console. You MAY not be allowed to change the src of an iframe containing a url from another domain - some browsers like IE can throw a security exception. You could have access denied in the console
  3. Some websites do not allow their pages to be framed. It is not the case in your example but would for example give errors if you try to load google in a frame

$(function() {
  $('#changeframe').click(function() {
    $('#declinedframe').attr('src', 'http://stackoverflow.com');
  });
});
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>


<input type="button" id="changeframe" value="Change">

<iframe id="declinedframe" class="embed-responsive-item" src="http://forgezilla.com" height="585" width="100%"></iframe>

Using a link - no need for jQuery (same if the button above was submitting a form, target iframename):

<a href="http://stackoverflow.com/" target="declinedframe">Change</a>

<iframe name="declinedframe" id="declinedframe" class="embed-responsive-item" src="http://forgezilla.com" height="585" width="100%"></iframe>

If you MUST use jQuery for the link give it the ID of changeframe use

$(function() {
  $('#changeframe').on("click",function(e) {
    e.preventDefault(); // cancel the link
    $('#declinedframe').attr('src', this.href );
  });
});

Upvotes: 0

Noobit
Noobit

Reputation: 431

The order does matter.

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<input type="button" id="changeframe" value="Change">

<iframe id="declinedframe" class="embed-responsive-item" src="http://forgezilla.com" height="585" width="100%" ></iframe>

// Go Last since changeframe hasn't exist yet.
<script>
  $('#changeframe').click(function () {
      $('#declinedframe').attr('src', 'http://stackoverflow.com');
  });
</script>

Upvotes: 7

Related Questions