0

I'm working on a brief quiz that is going to be built with an iFrame in HTML and JavaScript/jQuery. I've been trying to figure out why my buttons and onclick events aren't working.

Here's what I have in HTML:

<iframe id="iframe">

</iframe>

And JS:

$(document).ready(function() {

  function getDog() {
    alert("Dogs are great!");
  }

      var $iframe = $('#iframe');
      var $dogButton = "<button id=\'dog\'>Dog</button>";

      $iframe.contents().find("body").append("What is your favorite animal?");
      $iframe.contents().find("body").append($dogButton);
      document.getElementById("dog").addEventListener("click", getDog());
    })

For some reason this won't work in a snippet, so here's my CodePen: https://codepen.io/anfperez/pen/agRVKE

I know this is written in "old" JS, but I'm working with a legacy backend.

I haven't really worked with iFrames before. Can anyone give some suggestions on why this wouldn't be working?

2 Answers 2

2

You need to find the dog button inside the Iframe contents, just like you have appended the button.

$iframe.contents().find(".dog").addEventListener("click", getDog());

Note: As said, it won't work with CORS (cross-origin). Only works if the iframe URL is in the same domain

Sign up to request clarification or add additional context in comments.

Comments

1

Try this $iframe.contents()[0].getElementById("dog").addEventListener("click", function() { getDog() });

But this only works in iframes hosted in the same domain.

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.