Hello. There was such a question. How can I implement a smooth transition of images (background) on pure Javascript? Thank you in advance

The question is still valid.

    4 answers 4

    Faced with a similar problem. Made myself a Majesty 2 fan site . There, I just had to have a self-titled div, and I was confused to make it transparent without pictures. In general, I think that without a fake-substrate, that is, without a diva, which will be positioned under the background of the site, can not do. Well, there already is opacity.

    You can, of course, create a transition between backgrounds by changing monochromatic or gradient pictures with different transparency, and put them on a container of your level so that the current background is shaded.

      Hmm, I'm afraid without shamanism can not do. The first thing that comes to mind:

      1. Make a div ( position:relative; ), for the entire parent element (the very whose background we want to smoothly change);
      2. Put the current background on it, make it not transparent (if the user starts scrolling with the mouse wheel or poking on the scrollbar, you will have to intercept and scroll the image on this diva too);
      3. Replace the background image in the parent element, and then make the dummy div gradually by opacity.

      Thus we get a smooth change, and the most culminating moment - are these beautiful things worth it? :)

      • In this case, I need and it is important to implement it on pure JS. Pictures (or colors) should change on the timer. Anyway, thanks for the reply - Jet
      • Without CSS you will not achieve anything. And who's stopping you from creating divas on the fly and assigning styles to them right in JS :) - GLAGOLA

      In pure JavaScript this is not hard to implement. But it's pretty easy to do using CSS . Do not forget that styles are needed for that. If you correctly make a preliminary markup, then the background property, and this is your background, can be added to the html element:

       html { background: url(picture.png); } 

      Now you have two html and body blocks with images that overlap (if you set the margin and padding correctly for the body element) on each other. Skillful management of opacity properties gives you the desired effect.

      • Unfortunately, it does not. Opacity affects the descendants, in this case, the body and it turns out that they also become transparent, as a result we have a flickering interface. I personally encountered this in chrome. - GLAGOLA
      • In this case, it is more expedient to make the transition to color, and from it already in the picture. But this is not the same .. - Spirit
      • @Spirit, in my opinion, when moving from a picture to a color, and then from a color to a new picture, a problem may arise if different (and indeed diametrically opposed) colors prevail in the pictures. - GLAGOLA

      A bunch of ready-made options On pure css it is impossible to do, but on JS completely.