简体   繁体   中英

fadeIn() not triggering but everything else is

I have this small snippet that triggers when I use socket.io:

socket.on('wheelspin', function (random) {
    var img = document.querySelector('img');
    $("img").fadeIn();
    console.log('wheelspin!!!');
    console.log('fadeIn');

        img.removeAttribute('style');
        var deg  = 0; 

        console.log('deg = ' + deg);
        console.log('Number = ' + random);
        if(random == 0) {var deg = 15; var css = '-webkit-transform: rotate(' + deg + 'deg);'; }
        img.setAttribute('style', css);
}

Whenever I run this, the webpage console displays the console.logs but it doesn't do the fadeIn. If I do the following outside the socket trigger it works:

$( document ).ready(function() {
    $("img").fadeIn();
 });

Any advice?

Thanks

Probably $("img").fadeIn(); is not working because the img is not yet available and socketio's 'wheelspin' event is being emmited before that. this is evident from the fact that $("img").fadeIn(); works pretty well inside $(document).ready() when the DOM is ready.

suggestion: Use everything when the DOM is ready

$( document ).ready(function() {
    socket.on('wheelspin', function (random) {
          var img = document.querySelector('img');
          $("img").fadeIn();
          console.log('wheelspin!!!');
          console.log('fadeIn');

          img.removeAttribute('style');
          var deg  = 0; 

          console.log('deg = ' + deg);
          console.log('Number = ' + random);
          if(random == 0) {var deg = 15; var css = '-webkit-transform: rotate(' + deg + 'deg);'; }
          img.setAttribute('style', css);
     }
 });

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