user12704057
user12704057

Reputation:

Only load iframe when mouseover

Hey i want want the iframe to only load when the mosue is hovering on it.

I only want it to laod when the mouse is over because i have many of them and the loading speed of the site is very bad.

Any ideas?

i already tried if with a hidden div around it but i dont like that option

$(".text").mouseover(function() {
    $(this).children(".test").show();
}).mouseout(function() {
    $(this).children(".test").hide();
});
.text {
    color: #069;
    cursor: pointer;
    text-decoration: none;
}

.test {
    display: none;
    position: absolute;
    border: 1px solid #000;
    width: 400px;
    height: 400px;
}
<span style="font-size:120%;"><b><a class="text"> &#128065;
 
 <iframe class="test" src="https://www.google.de/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png"></iframe>
</a></b></span>
            
            
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Upvotes: 1

Views: 1209

Answers (1)

vatz88
vatz88

Reputation: 2452

Don't set the src of the iframe. Only set it when the user hovers for the first time.

In the below snippet you can see the page inside of iframe is not loaded initially until you hover over the eye.

I have intentionally commented display: none; so that you can observe that page is not loaded.

$(".text").mouseover(function() {
    var src = $(this).children(".test").attr('src');
    if(!src){
      src = $(this).children(".test").attr('data-src');
      $(this).children(".test").attr('src', src);
    }
    $(this).children(".test").show();
}).mouseout(function() {
    $(this).children(".test").hide();
});
.text {
    color: #069;
    cursor: pointer;
    text-decoration: none;
}

.test {
    //display: none;
    position: absolute;
    border: 1px solid #000;
    width: 400px;
    height: 400px;
}
<span style="font-size:120%;"><b><a class="text"> &#128065;
 
 <iframe class="test" data-src="https://www.google.de/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png"></iframe>
</a></b></span>
            
            
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Upvotes: 3

Related Questions