简体   繁体   中英

jQuery blur function not working first time

I am currently having a problem on blur() function because it needs the user first to click outside the frame or in page body before it works.

Here is the link for the code:

$(document).ready(function(){
  $( window ).blur(function(){
      alert("you click the IFRAME!");
  });
});

https://jsfiddle.net/gaoj6fzs/15/

What I want is that, the alert will prompt when I click the IFRAME without needing to click first any part outside the frame.

You probably want the click/focus event.

// click
$(document).ready(function(){
  $( window ).click(function(){
      alert("you click the IFRAME!");
  });
});

// focus
$(document).ready(function(){
  $( window ).focus(function(){
      alert("you click the IFRAME!");
  });
});

What you can do is find the contents of the iframe and if the contents match what you wanted then the user clicked on the iframe else did not

Now check it

  $('iframe').load(function(){

  $(this).contents().find("body").on('click', function(event) {     alert('test'); });
});

hope this helps

JavaScript :

$('iframe').load(function(){
  $(this).contents().find("body").on('click', function(event) { alert('test'); });
});
$('iframe').attr("src","JavaScript:'iframe content'");

HTML

<iframe></iframe>

DEMO HERE

Note 1: Both pages are in the same domain.

Note 2: If you have two or more iframes, you must give separate id's for them

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM