How to use the preventDefault function in an event click in an iframe?

Asked

Viewed 1,139 times

2

I manipulate the iframe DOM as follows: (http://api.jquery.com/contents/)

$('iframe').contents().find('a').função();

We usually use the preventDefault function like this:

$( "a" ).click(function( event ) {
  event.preventDefault();
});

Doubt:

How to use the function preventDefault() in an event click for all link tags $('a') within iframe? Basically I need no link to be clickable inside iframe.

I’ve tested it as follows, but it doesn’t work:

$('iframe').contents().find('a').click(function (e) { 
   e.preventDefault();
});
  • I think you can mark one of the answers as right :)

3 answers

2

If the iframe is in a different domain your jQuery solution will not work because it violates a security rule and browsers do not allow it.

One solution I see is to block the iframe with a div on your page, above the iframe, and so "cover" the interaction with the iframe.

Another option, even better (for modern browsers) is the Renan’s solution with Pointer Events.

Example:

(Note that I have a border on the blocking div just to be visible)

#bloqueador {
    position: absolute;
    top: 0px;
    border: 2px solid #ccf;
    height: 300px;
    width: 300px;
}
<iframe src="http://www.cnn.com" frameborder="0"></iframe>
<div id="bloqueador"></div>

  • 1

    @Gustavopiucco I will delete the comments here to clean. If you do the same would be great and save time of moderators

2

A CSS-only solution would be to use the property pointer-events in the <iframe>. You just need to watch out for which browsers support.

iframe {
  pointer-events: none
}
<iframe src="http://tympanus.net/codrops/" frameborder="0"></iframe>

MDN

0


To solve the problem, if the iframe is from the same domain as the parent page, you need to add the event .ready() to iframe, as it must be fully loaded before applying the event .click(). Being as follows:

$(document).ready(function() {
    $("#id_do_iframe").ready(function () {
        $('#id_do_iframe').contents().find('a').click(function (e) { 
             e.preventDefault();
        });
    });
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.