jQuery events not working within iframe?

Braydon Batungbacal picture Braydon Batungbacal · Nov 23, 2011 · Viewed 12.7k times · Source

I am having some issues with focus(function(){}) and blur(function(){}) within a script that is nested within a dynamically loaded iframe..

Below is the script tag WITHIN the iframe being dynamically loaded. Any event I throw into the script markup is not working, simple things like a $('input').click(function(){alert('fired')}); will not even run. I am not sure what is going on.

Yes, jQuery is being loaded into the iframe in the head.

<script type="text/javascript">
// <![CDATA[
    $(document).ready(function() {

        $('.form .field-content').find('input, select, textarea').focus(function() {
            $(this).closest('.field').addClass('focused');
        });

        $('.form .field-content').find('input, select, textarea').blur(function() {
            $(this).closest('.field').removeClass('focused');
        });

        $('.form .field-content').find('input, select').keypress(function(e) {
            if (e.which == 13) {
                e.preventDefault();
                $(this).closest('.form').find('.button').first().click();
            }
        });

        $('.form .button').focus(function() {
            $(this).addClass('focused');
        });

        $('.form .button').blur(function() {
            $(this).removeClass('focused');
        });

        // focus on first field
        $('.form .field-content').find('input, select, textarea').first().focus();

    });
// ]]>
</script>

Answer

JuLy picture JuLy · Nov 30, 2011

Maybe the problem is the iframe content haven't been loaded, try

$("#Your-Iframe-Id").load(function (){
    // write your code here
});