1

I currently have some Javascript that looks a bit like this:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
function changeSource(newSource) {
  document.getElementById('preview').src = newSource;
}
});
</script>

Then I have some HTML that looks like this:

<table border=0 class="colors">
  <tbody>
    <tr>
      <td><a onclick="changeSource('http://www.test.com')"><img width="40" src="test.png"/></a></td>
    </tr>
  </tbody>
</table>

Then the Iframe section:

<table border=0>
  <tbody>
    <tr>
      <td><iframe id="preview" width="125" height="303" src="test.php" scrolling="no" frameborder="0" marginwidth="0" marginheight="0" hspace="0" vspace="0"></iframe></td>
    </tr>
  </tbody>
</table>

However click on the image in the tags the Iframe's source won't change. Why is it like this?

2 Answers 2

2

You are getting an error because the function is a local method since you hid it in the onready function. There is no need for the onready call with that example.

<script>
$(document).ready(function(){
function changeSource(newSource) {
  document.getElementById('preview').src = newSource;
}
});
</script>

needs to be

<script>
  function changeSource(newSource) {
      document.getElementById('preview').src = newSource;
  }
</script>

Better yet, no JavaScript is needed! Use HTML like it is supposed to be used. Use the target attribute.

<td><a href="http://www.example.com" target="preview"><img width="40" src="test.png"/></a></td>
Sign up to request clarification or add additional context in comments.

1 Comment

Worked perfectly, thank you so much. I will accept your answer once the time runs out.
0

You are using jquery. Better make a perfect use.

$(document).ready(function(){
    // selecting anchor tag for table with class colors
    $("table.colors a").click(function(e){
        e.preventDefault();
        var newSource = $(this).attr("href");
        $("#preview").attr({"src" : newSource});
    });
});

No need of messing with html by adding onclick attribute or target attribute. But html's target attribute is most preferable.

<table border=0 class="colors">
  <tbody>
    <tr>
      <td><a href="http://www.test.com"><img width="40" src="test.png"/></a></td>
    </tr>
  </tbody>
</table>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.