Julian Hernandez Julian Hernandez - 1 month ago 10
HTML Question

Why doesnt this Jquery cod set ifram src?

I am trying to change the iframe src based on window height but this code doesnt set the src to anything at all...

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>


<script>

if( $(window).width() > 480){
$('#cal').attr('src', "https://teamup.com/ks5fbef7146ebe1a4d?view=m&sidepanel=c&showLogo=0&showTitle=0");
}else {
$('#cal').attr('src', "https://teamup.com/ks5fbef7146ebe1a4d?view=l&sidepanel=c&showLogo=0&showTitle=0");
}

</script>

<iframe id="cal" src="" frameborder="0" width="65%" height="600"></iframe>


What am i missing?

Answer

If your code is in that order when the page loads, the javascript doesn't know about that iframe yet. I suggest wrapping the jQuery in a ready function, like this:

$(document).ready(function(){

   if( $(window).width() > 480){
      $('#cal').attr('src', "https://teamup.com/ks5fbef7146ebe1a4d?view=m&sidepanel=c&showLogo=0&showTitle=0");
    }else {
      $('#cal').attr('src', "https://teamup.com/ks5fbef7146ebe1a4d?view=l&sidepanel=c&showLogo=0&showTitle=0");
   }

});