javascript - Swapping out background images for background gifs -
so have 4 li's contain images inside them gifs in li have "display: none;" inline on them. , when hover on li's, images swap realated gif, seen here in jquery wrote:
jquery(".swap").mouseenter(function () { var me = jquery(this); me.attr('src', me.attr('src').replace('.jpg', '.gif')); }); jquery(".swap").mouseleave(function () { var me = jquery(this); me.attr('src', me.attr('src').replace('.gif', '.jpg')); });
and here html:
<li> <img class="swap" src="image-box.jpg" /> <img class="swap" src="image-box.gif" /> </li> <li> <img class="swap" src="image-box2.jpg" /> <img class="swap" src="image-box2.gif" /> </li>
i noticed these gifs still being loaded site on mobile after hiding elements , containers. decided make images background images of div inside li (since links need wrapped around image itself) , it's laid out this:
<li> <a href="#"> <div class="swap" id="imageone"></div> </a> </li> <li> <a href="#"> <div class="swap" id="imagetwo"></div> </a> </li>
and jquery wrote swap out images gifs follows:
jquery("#imageone").mouseenter(function () { jquery(this).css('background-image','url(image-box.gif)'); }); jquery("#imageone").mouseleave(function () { jquery(this).css('background-image','url(image-box.jpg)'); }); jquery("#imagetwo").mouseenter(function () { jquery(this).css('background-image','url(image-box2.gif)'); }); jquery("#imagetwo").mouseleave(function () { jquery(this).css('background-image','url(image-box2.jpg)'); });
so question how can simplify new script wrote make more concise. on actual site there 4 li's jquery looks huge , messy. know there must better way of swapping out
if difference between jpeg , gif filenames file extension (ie file names same), can still reuse original script replace image's reference:
jquery(".swap").mouseenter(function () { var me = jquery(this); me.css('background-image', me.css('background-image').replace('.jpg', '.gif')); }); jquery(".swap").mouseleave(function () { var me = jquery(this); me.css('background-image', me.css('background-image').replace('.gif', '.jpg')); });
html:
<li> <div class="swap" style="background-image:url('image/image-1.jpg');"></div> </li> <li> <div class="swap" style="background-image:url('image/image-2.jpg');"></div> </li>
you can prime gifs on document ready they're in cache when want swap:
jquery(document).on('ready', function(){ jquery('.swap').each(function(){ //create hidden image var $img = jquery('<img>').css({ 'visibility':'hidden', 'position':'absolute', 'z-index:-1' }); //create trigger once image loaded $img.on('load', function(){ jquery(this).remove(); }); //add dom jquery('body').append($img); //set image source call server image $img.attr('src', jquery(this).css('background-image').slice(4, -1).replace('.jpg', '.gif')) }); });
i have not tested this, i'm assuming same swaping logic should still relevant.
Comments
Post a Comment