vendredi 29 mai 2015

Cannot set the focus on an iframe after load with jQuery

I am having a button in my page and when I click it I want an iframe to load and set the focus on it. So after loading the iframe I want to be able to push the keyboard arrows and move inside the iframe and not on the whole page.

I have the iframe on html like this:

 <iframe id="myiframe" width="1280" height="720" data-src="" src="about:blank" </iframe>

then on css:

 iframe#myiframe{
    width: 100%;  
    position: absolute;
    top: 0;
 }

and then I am using this jQuery

 var iframe = $("#myiframe");
 $(document).bind('click', function(e) {
      iframe.fadeIn();
      iframe.attr("src", iframe.data("src")); 

      setTimeout(function(){
            iframe[0].contentWindow.focus();
            iframe.contents().find("body").focus(); 
        }, 100);
 });

It loads just fine but when I am using the keyboard the whole page starts moving. The only way I managed to fix it is to set the position to fixed for the whole body.

 $("body").css("position","fixed");

But if possible I would prefer another way that that. Thanks in advance.

Aucun commentaire:

Enregistrer un commentaire