简体   繁体   中英

Trying to remove iframe source when element is hidden Jquery

I am trying to remove an iframe source when the element is hidden

  $(document).ready(function() {
    $("#myModal").is(":hidden",function(){
        $('iframe').attr("src","");
    });

    $("#myModal").is(":visible",function(){
            $('iframe').attr("src","http://google.com");
        });
   });

by default, the modal i created has a

style="display:none"

what I would like to happen is to have the iframe source empty if the modal is hidden

<iframe src="">

and load a source when the modal is visible or if

style="display:block;"

I tried several method but nothing works and came up with the one above but still doesn't work.

If you are using Bootstrap modal, you could refer this: Modal#Events

Then, your js code can be edited to:

$(document).ready(function() {
    $("#myModal").on("hidden.bs.modal",function(){
        $('iframe').attr("src","");
    });

    $("#myModal").on("shown.bs.modal",function(){
        $('iframe').attr("src","http://google.com");
    });
});

To make the code clearly, you could write:

$(document).ready(function() {
    var modal = $("#myModal"), iframe = $('iframe');

    var onhidden = function(){
        iframe.attr("src","");
    };

    var onshown = function(){
        iframe.attr("src","http://google.com");
    };

    modal.on("hidden.bs.modal", onhidden)
         .on("shown.bs.modal", onshown);
 });

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