0

I am trying to fade in my iframe smoothly with JavaScript. I have seen links online and most of the answers were related to jQuery. Why must I use jQuery for a simple fading? Can anyone explain?

Also I do not mind using JQuery, after all its a part of javascript. I am just looking for a simple solution. Since I am using the below fadeIn() function, does jQuery perform better than the below function?

 <iframe id="iframe" style="
            position: fixed;
            opacity: 0;
            height: 100%;
            width: 100%;
            overflow: hidden;
            z-index: 10;
            display: none;
          ">
    </iframe>

<script>
//Creation of button before this code

button_01.onPointerUpObservable.add(function () {
                let iframe = document.getElementById("iframe");
                iframe.src = "LINK";
                fadeIn(iframe, 2000);
                iframe.style.display = 'Block';
            });

function fadeIn(el, duration) {

            /*
             * @param el - The element to be faded out.
             * @param duration - Animation duration in milliseconds.
             */

            var step = 10 / duration;
            var opacity = 0;
            function next() {
                if (opacity >= 1) { return; }
                el.style.opacity = (opacity += step);
                setTimeout(next, 10);
            }
            next();
        }
</script>
Mitch
  • 41
  • 5
  • First of all, jQuery is JavaScript. Secondly, you don't have to use jQuery for anything. You just need to learn how jQuery does it, and write that code. I'll tell you one thing for free; it's going to be a lot easier if you use stylesheets rather than inline styles... – Heretic Monkey May 11 '21 at 13:07
  • For example, [How to make fadeOut effect with pure JavaScript](https://stackoverflow.com/q/29017379/215552) – Heretic Monkey May 11 '21 at 13:09

1 Answers1

0

Some people suggest jQuery because there's a function called x.fadeIn(300) which causes it to animate pretty nicely, you don't actually need this and it can be accomplished by adding a class or using vanilla animations and removing it later
Both:

Option 1: Class

.shown {
    opacity: 1;
}

iframe {
    transition: .3s opacity;
}
iframe.classList.add('shown');

Option 2: JS only

iframe.style.transition = '.3s';
iframe.style.opacity = '1';
// remove it after it's done
setTimeout(() => {
    iframe.style.transition = '';
}, 300); 
Spectric
  • 30,714
  • 6
  • 20
  • 43
Robyn
  • 161
  • 1
  • 8