Home > Mobile >  I want to add css class dynamically to body when that page has <iframe> and want to remove tha
I want to add css class dynamically to body when that page has <iframe> and want to remove tha

Time:11-03

I want to hide scrollbar of parent website and show iframe scrollbar only. But when i apply overflow hidden property to body it will be applied globally but i want to apply only that page where is available. How can i do that? can anyone can help me please?

CodePudding user response:

Use JavaScript to determine the existence of iframe element and then remove or add class to body tag accordingly. Here's how:

if(!document.querySelector('iframe')){
   document.querySelector('body').classList.add = "newClass";
} else{
   document.querySelector('body').classList.remove = "newClass"; //In case class was already added
}

Hope this solves your question.

CodePudding user response:

For adding/remove class to body you can write js code like:

If you use jQuery:

jQuery(document).ready(function ($) {
  if ( $('iframe').length ) {
    $(body).addClass('is-iframe');
  } else {
    $(body).removeClass('is-iframe');
  }
});

Pure js:

window.addEventListener("load", function(event) {
  if ( document.querySelector('iframe') ){
    document.querySelector('body').classList.add('is-iframe')
  } else {
    document.querySelector('body').classList.remove('is-iframe')
  }
});

I think you can also set some styles for body.is-iframe and for iframe element:

body.is-iframe {
  position: relative;
  width: 100vw;
  height: 100vh;
}

body.is-iframe iframe {
  position: aboslute;
  width: 100%;
  height: 100%;
  overflow-y: auto;
}

I didn't test this code yet, but I guess it should work.

  • Related