I have different iframe, but it slows down. I want the iframe to only load, when a button is clicked. And then hide/show iframe with toggle event.
Example of the code:
<script>
$(document).ready(function(){
$("#button2").click(function(){
$("#iframecon").toggle();
});
});
</script>
<input type="checkbox" id="button2" onClick='document.getElementById("iframe2").src="/page1.php";'>
<div id="iframecon">
<iframe id="iframe2" width="100%" height="100%"></iframe>
</div>
How can I do it? Thanks
2
Answers
You can try something like this:
Check the src of the iframe
You probably want the
change
event not the click; jQuery will handle it as "one" event trigger but standard JavaScript will add two event listeners so we should just use one (the change)Note this assumes a hard coded URL in both these BUT I also added some "html" to inject in just for this demo.
Examples:
jQuery example:
Here I hide it initially, then toggle after I set the src value.
Generic JavaScript:
Here I use a class and set that in the HTML so it is initially hidden with that CSS; then I toggle that class if the checkbox is checked to remove it or add it if NOT checked so the hide follows the X/checked shows, unchecked hides.
Alternative to this one would be to set a dataset value on the iframe then put CSS in to reflect the show/hide from that value such as
#iframe2{display:none;} #iframe2[data-showme="true"]{display:block;}
so any value other than "true" or not yet set hides it (order dependency of the CSS matters)