The Anonymous Koder
The Anonymous Koder

Reputation: 602

Hide iframes using javascript

I am trying to create a browser (I got bored) and I want the user to be able to navigate between tabs.
This would need me to hide one iframe and show another one. I'm not sure how to do this using javascript. I also don't want the iframe to resize (like saying height: 0px;).

Here's my sandbox.

Thanks in advance.

Upvotes: 0

Views: 269

Answers (2)

Amesh Jayaweera
Amesh Jayaweera

Reputation: 226

You can add custom CSS to your iframe dynamically to hide and show.

Refer following code,

<!DOCTYPE html>
<html>
<head>
<style>

.custom-style {
    width: 0; 
    height: 0; 
    position: absolute;
    border: 0;
}

</style>
</head>
<body>

    <iframe id="iframe"
    width="300" height="200" src="https://www.youtube.com/embed/zFZrkCIc2Oc" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
    
   <br/>
    
    <button onclick="onHide();">Hide Me<button>
    
    <button onclick="onShow();">Show Me<button>
    

</body>

<script>

    function onHide() {
        document.getElementById('iframe').classList.add('custom-style');
    }
    
    function onShow() {
        document.getElementById('iframe').classList.remove('custom-style');
    
    }
 
</script>

</html>

Upvotes: 2

Sarkar
Sarkar

Reputation: 1899

wrap your iframe inside a div container and when you need to hide it just add a style or class to it and set it display style to none

html

<div class="hide">

    <iframe></iframe>

</div>

css

.hide{
    display: none;
}

Upvotes: 1

Related Questions