Isabella
Isabella

Reputation: 11

Make a div clickable when there is iframe inside

I want to add onclick function to div, but when there is a facebook plugin iframe inside of the div, the onclick function not work.

there is code:

<div onclick="alert('123)">
  <iframe 
    src="https://www.facebook.com/plugins/page.php?..." 
    width="470" 
    height="160" 
    style="border:none;overflow:hidden" 
    scrolling="no" 
    frameborder="0" 
    allowTransparency="true">
  </iframe>
</div>

Upvotes: 1

Views: 1895

Answers (2)

Rajesh
Rajesh

Reputation: 24945

You can try something like this:

Logic:

  • On parent window, search all iframes
  • Navigate to their parent node.
  • Attach event to this node.

window.addEventListener('load', registerEvent)

function registerEvent(){
  var divs = document.querySelectorAll("iframe");
  for(var i = 0; i< divs.length; i++){
    divs[i].parentNode.addEventListener("click", clickHandler)
  }
}

function clickHandler(){
  console.log(this.innerHTML);
}
div{
  background: #ddd;
  min-height: 100px;
}

iframe{
  background: #fff;
}
<div>
  <iframe 
    src="https://www.facebook.com/plugins/page.php?..." 
    width="470" 
    height="160" 
    style="border:none;overflow:hidden" 
    scrolling="no" 
    frameborder="0" 
    allowTransparency="true">
  </iframe>
</div>

Upvotes: 2

blurfus
blurfus

Reputation: 14031

Your onclick event was mismatched quotes (i.e. missing the closing quote)

I also went and added some margin and padding to the div (and some borders too) to illustrate the onclick event firing when the div is clicked (as it should). Keep in mind that it is attached to the div not the iframe.

You can either use JS (or JQuery) to attach the click-handler to the iframe programmatically or, add another onclick to the iframe itself (dunno, if you can modify it)

div {
  width: 470px;
  height: 160px;
  border: 1px solid gray;
  margin: 15px;
  padding: 15px;
}

div:hover {
  cursor: pointer;
}
<div onclick="alert('123')">
  <iframe src="https://www.google.ca" 
          width="470" height="160" 
          style="border:1px solid green;overflow:hidden"
          scrolling="no" 
          frameborder="0" allowTransparency="true">
  </iframe>
</div>

Upvotes: 0

Related Questions