简体   繁体   中英

Using a conditional statement so jquery fadeIn/fadeOut only works when viewport >= 480px

I have the following code which fades between an image and a heading:

setInterval(function(){
            $('.fadein-effect > img').fadeOut(2500, function(){
                $('.fadein-effect').append('<h2 class="intro-text">Site Currently Under Construction - Coming Soon!</h2>');
                $('.fadein-effect > h2').hide().fadeIn(2500).fadeOut(2500, function(){
                    $('.fadein-effect > h2').remove();
                    $('.fadein-effect > img').fadeIn(2500);
                });
            });  
        }, 10000);

I want to use this effect in a responsive layout and only want the fade effect to work when the viewport is => 480px. I've tried using the following approach (among many others) but can't get it to work.

function fadeInEffect(){
    var $containerWidth = $(window).width();
    if ($containerWidth <= 480) {

        setInterval(function(){
            $('.fadein-effect > img').fadeOut(2500, function(){
                $('.fadein-effect').append('<h2 class="intro-text">Site Currently Under Construction - Coming Soon!</h2>');
                $('.fadein-effect > h2').hide().fadeIn(2500).fadeOut(2500, function(){
                    $('.fadein-effect > h2').remove();
                    $('.fadein-effect > img').fadeIn(2500);
                });
            });
        }, 10000);

    }
    else {
        $('.fadein-effect > img').replaceWith('<h2 class="intro-text">Site Currently Under Construction - Coming Soon!</h2>');
    } 
}

$(document).ready(function () {
    fadeInEffect();//run when page first loads
});

$(window).resize(function () {
    fadeInEffect();//run on every window resize
});

I'm fairly new to jquery/javascript so could be doing something wrong that's pretty basic. I've been struggling with this for a while so any help would be most appreciated,

Thanks,

Thomas

You could use matchMedia API wich is supported from IE >= 9

if (window.matchMedia("(max-width: 480px)").matches) {
  // code executed once here
}

http://caniuse.com/#feat=matchmedia

Your original code works just fine, you just have the wrong operator in your if statement. Instead of using "less than or equal to" ( <= ), you should use "greater than or equal to" ( >= ).

if ($containerWidth >= 480) {

JSFiddle: http://jsfiddle.net/d5op9bty/

I hope this helps. ^^

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