1

Here is a scenario: From create.jsp, I am creating a play button and an audio tag as follows:

//play button
out.write("<input type=\"button\" id=\"playButton\" value=\"Play Now\" >");
out.write("");

//audio element
out.write("<audio id=\"sound\" preload=\"auto\">");
//out.write("<source src=\"sfl\" type=\"audio/ogg\" />");
out.write("<source src=\"sfl\" type=\"audio/mpeg\" />");
out.write("Your browser does not support the audio element.");
out.write("</audio>");

I used a frame to bring this to home.jsp as follows:

<iframe id='bgframe' style='display:compact;' src='create.jsp' width="400" height="200"></iframe>

In my jquery code, I have

    $("#playButton").click(function(){
    alert("Play button clicked");
    }

But nothing happens when I click the playButton.

Question: How can I use jquery or javascript to capture click event on playbutton deployed via a frame?

bdfios
  • 657
  • 6
  • 17
  • 29

3 Answers3

0

By design, JavaScript from a parent frame cannot act on elements contained within an iframe.

ehdv
  • 4,483
  • 7
  • 32
  • 47
  • oh really? So what can I do now? – bdfios Apr 12 '13 at 19:09
  • 2
    I don't think this is true. If the page in the frame is on the same domain (i.e. there's no cross-domain security issues), you should be able to access the DOM of the page in the iFrame. See [here](http://stackoverflow.com/questions/251420/invoking-javascript-in-iframe-from-parent-page). – Richard Marskell - Drackir Apr 12 '13 at 19:14
  • I stand corrected. I must've never tried same-domain before, and assumed it was the same as cross-domain. However, @bdfios, you should consider using the JSP equivalent of partial views over an iframe here; it looks like that would fit your use case and would 1) make your life easier, and 2) reduce HTTP requests. – ehdv Apr 12 '13 at 19:21
  • @Richard - Thanks for the link. I am getting some information there – bdfios Apr 12 '13 at 19:35
  • @ehdv - sorry, can you explain what you mean by "JSP equivalent of partial views over an iframe"? I am definitely open to trying out your suggestion once I understand it. – bdfios Apr 12 '13 at 19:35
  • In C# / ASP.NET, there is a notion of a partial view, which the server renders inline in the page before sending it to the client. This means that there isn't a second HTTP request, and your JS is much easier. – ehdv Apr 16 '13 at 16:54
0

try this

out.write("<script>function(){//your code here}</script>");
out.write("<input type=\"button\" onclick=\"demo()"\ id=\"playButton\" value=\"Play Now\" >");

or

out.write("<script src="file name where code is placed"></script>");
out.write("<input type=\"button\" id=\"playButton\" value=\"Play Now\" >");
Harshit Tailor
  • 3,261
  • 6
  • 27
  • 40
0

you need to use contents()

$("#bgframe").contents().find("#playButton").click(function(){
    alert("Play button clicked");
}
TheBrain
  • 5,528
  • 2
  • 25
  • 26