qwerty
qwerty

Reputation: 5246

Run javascript in iframes as well as normal content?

I have the following block of code that clears input fields when you click on them:

$('.clearinputtext').focus(function(){
    if($(this)[0].defaultValue==$(this).val()) $(this).val('');
});
$('.clearinputtext').blur(function(){
    if($(this).val()=='') $(this).val($(this)[0].defaultValue);
});

I need that to run inside of iframes as well, is it possible?

Edit: I forgot to mention that the iframe is loaded dynamically with a lightbox, so it's not there when the page loads.

Solution

I managed to solve it. Might not be the best solution, but it'll do for now. Since the iframe is loaded with a lightbox when i click a link, it's not there when the page loads, so i needed to run the code for the iframe after it is added. I did that by using the afterShow event handler for the lightbox.

Here's the relevant code:

afterShow: function() {
    // First get html content of iframe
    var content = $('.fancybox-inner iframe').contents().find('html');
    //Then just apply same code to the iframe
    $(content).find('.clearinputtext').focus(function(){
        if($(this)[0].defaultValue==$(this).val()) $(this).val('');
    });
    $(content).find('.clearinputtext').blur(function(){
        if($(this).val()=='') $(this).val($(this)[0].defaultValue);
    });
}

Upvotes: 0

Views: 72

Answers (1)

Anton
Anton

Reputation: 32581

var iframe = document.getElementsByTagName('iframe');
innerDoc = iframe[0].contentWindow;

$(innerDoc.document.getElementsByClassName('clearinputtxet')).focus(function(){
if($(this)[0].defaultValue==$(this).val()) $(this).val('');
});

$(innerDoc.document.getElementsByClassName('clearinputtxet')).blur(function(){
    if($(this).val()=='') $(this).val($(this)[0].defaultValue);
});

try this out it should work.

Upvotes: 1

Related Questions