Dynamic background URL

Asked

Viewed 417 times

0

It is possible to create a dynamic array of images and call them within the background-image:url() ?

With the tip that was passed by @hugocsl earlier, I would like to reuse this instruction line because it is part of a page download to which I use and it is very useful to me,

#carrega_imagem {
        position: relative;            
        background-image: linear-gradient(rgba(0, 0, 0, .75) 0%, 
                                          rgba(102, 0, 0, .50) 100%),  
                                          url("images/casa_linda.jpg");
        background-size: cover;
        height: 100%;
        width: 100%;
        top: 100%;
        left: 100%;
}

Where is the code snippet url("images/casa_linda.jpg"), it is possible to create an array via javascript ?

I saw this in Jquery, but what kills is the structure I use for this Download.

  • Dude, you just want the image to alternate all the time in the background? If that’s all you can do with CSS and make an animation with the background changing the images... If you want a simple example, just say the word.

2 answers

3

Yes possible. Just create a variable to store the values (photo link) and then use for to go through these values, for example:

/* Gradiente padrão */
const gradient = "linear-gradient(rgba(0, 0, 0, .75) 0%, rgba(102, 0, 0, .50) 100%)";

/* Link das imagens */
const images = [
  'https://www.grammy.com/sites/com/files/styles/news_detail_header/public/news/lindsey_stirling_still_01.jpg?itok=cDdUKxXi',

  'https://upload.wikimedia.org/wikipedia/commons/6/65/Evanescence_at_The_Wiltern_theatre_in_Los_Angeles%2C_California_04_%28cropped%29.jpg',

  'http://images.virgula.com.br/2018/03/63a8d811-2814-4cdf-9c9f-aeb31559854f.jpg'
];

/* Função para alterar as imagens */
(async () => {
    for (let image of images) {

      /* Aplica o gradiente com a URL da imagem */
      document.body.style.setProperty("background-image", `${gradient}, url('${image}')`);
      
      /* Define o tempo de 5 segundos para alternar */
      await new Promise(resolve => setTimeout(resolve, 5000))

    }
})();
body {
  background-size: cover;
}

With jQuery is the same thing. To change the property just use

$("element").css("background-image", `${gradient}, url('${image}')`);
$("element").delay(5000);

If you want a random image only (no toggle), then you can use Math.random to capture the image randomly, for example:

/* Gradiente padrão */
const gradient = "linear-gradient(rgba(0, 0, 0, .75) 0%, rgba(102, 0, 0, .50) 100%)";

/* Link das imagens */
const images = [
  'https://www.grammy.com/sites/com/files/styles/news_detail_header/public/news/lindsey_stirling_still_01.jpg?itok=cDdUKxXi',

  'https://upload.wikimedia.org/wikipedia/commons/6/65/Evanescence_at_The_Wiltern_theatre_in_Los_Angeles%2C_California_04_%28cropped%29.jpg',

  'http://images.virgula.com.br/2018/03/63a8d811-2814-4cdf-9c9f-aeb31559854f.jpg'
];

const slider = document.querySelector("#slider");

/* Função para capturar e aplicar uma imagem aleatória */
slider.style.setProperty("background-image", `${gradient}, url('${images[ Math.floor(Math.random() * images.length) ]}')`);
img {
  background-size: cover;
  height: 100vh;
  width: 100vw;
}
<img id="slider">


If you want to have an alternate image with animation, follow example:

const slider = document.querySelector("#slider");

const images = slider.querySelector("img");

(async() => {
  for (;;) {

    await new Promise(resolve => setTimeout(resolve, 5000))

    let elementCurrent = slider.querySelector(".active")
    let elementNext;

    if (elementCurrent.nextElementSibling) {
      elementNext = elementCurrent.nextElementSibling;
    } else {
      elementNext = images[0];
    }

    elementCurrent.classList.remove("active")
    elementNext.classList.add("active")
  }
})();
#slider,
#slider .overlay {
  height: 500px;
  position: relative;
  overflow: hidden;
  width: 500px;
}

#slider img {
  opacity: 0;
  transition: all 1s linear;
}

#slider img,
#slider .overlay {
  left: 0;
  position: absolute;
  top: 0
}

#slider .overlay {
  background: linear-gradient(rgba(0, 0, 0, .75) 0%, rgba(102, 0, 0, .50) 100%);
}

#slider img.active {
  opacity: 1
}
<div id="slider">
  <img src="https://picsum.photos/500/500/?image=845" class="active" />
  <img src="https://picsum.photos/500/500/?image=844" />
  <img src="https://picsum.photos/500/500/?image=843" />
  <img src="https://picsum.photos/500/500/?image=842" />
  <img src="https://picsum.photos/500/500/?image=841" />

  <div class="overlay"></div>
</div>

  • I used the background-image, but it has no animation effect (https://www.w3.org/TR/css-transitions-1/#animatable-properties). If you want this, you need to use another method.

  • Putz is what I need! But my case is very specific, I use a Loader called Queryloader, and I made an adaptation where I load 2 images at the same time + the gradient, #qLoverlay voltar position: relative; background-image: linear-gradient(rgba(0, 0, 0, 75) 0%, rgba(102, 0, 0, 50) 100%), url("images/honeycomb.jpg"); background-size: cover; height: 100%; width: 100%; top: 100%; left: 100%; } #qLoverlay::after { position: Absolute; content: url(images/Greetings.png); top: 50%; left: 50%; margin-left: -600px; margin-top: -600px; }

  • I would need to call the javascript function created where the background-image URL is

  • I wanted something like this function, but I don’t know how to instantiate the script variable within the background-image URL. <script type="text/javascript"> window.onload = Function(){ var imgr = Math.round(Math.Random()*4); var imgsrc = [ 'imagem1.jpg', 'imagem2.jpg', 'imagem3.jpg', 'imagem4.jpg', 'imagem5.jpg']; Document.getElementById('eximg'). src = imgsrc[imgr]; } </script> <img id="eximg"/>

  • I also have this other script here that could be adapted ... <script language="Javascript"> window.onload = Function() { var randnum = Math.Random(); var inum = 5; var rand1 = Math.round(randnum * (inum-1)) + 1; images = new Array images[1] = "imagem1.jpg" images[2] = "imagem2.jpg" images[3] = "imagem3.jpg" images[4] = "imagem4.jpg" images[5] = "imagem5.jpg" var image = images[rand1] Document.getElementById('img'). src=image; } </script> <img id="img" />

  • @Eitaehnoiz You want it to be a random image or it has to go alternating?

  • Yes, I found your example very nice! But I’m tied to a css structure, which I use pseudo-elements (:before and ::after) and which help me a lot and which my friend @hugocsl helped to structure, and precisely in the background-image=url(../images/my.imagem.jpg) is that I can’t put an array. I use a Loader called Queryloader2 to open the page, and each time the page is reloaded, I would like the background image to be swapped randomly. And it’s precisely in this background-image=url(), that I can’t / I don’t know how to instantiate the Javascript variable inside the url ();

  • #qLoverlay { position: relative; background-image: linear-gradient(rgba(0, 0, 0, 75) 0%, rgba(102, 0, 0, 50) 100%), url("images/honeycomb.jpg"); background-size: cover; height: 100%; width: 100%; top: 100%; left: 100%; } #qLoverlay::after { position: Absolute; content: url(images/logo.png); top: 50%; left: 50%; margin-left: -600px; margin-top: -600px; }

  • The above structure was an add-on I got thanks to @hugocsl. The problem is at the #qLoverlay url, where background-image:url("images/honeycomb.jpg) loads the image. The last code I passed found mass! Very good, but I don’t know how to instantiate the variable javascript inside this url () ... It would be something like background-image:linear-gradient(rgba(0, 0, 0, 75) 0%, rgba(102, 0, 0, 50) 100%), url( variavel_javascript_here ?). I need to study more javascript, because I know very little. :(

  • The randomized example got mass ! @Valdeir Psr, I need it in my structure, you know ?

Show 5 more comments

1

<div id="qLoverlay" class="preloader"></div>

<script type="text/javascript">
    /* Gradiente padrão */
    const gradient = "linear-gradient(rgba(0, 0, 0, .75) 0%, rgba(102, 0, 0, .50) 100%)";

    /* Link das imagens */
    const images = [
      'images/building.jpg', 
      'images/honeycomb.jpg',
      'images/space.jpg'];

    const slider = document.querySelector("#qLoverlay");

    /* Função para capturar e aplicar uma imagem aleatória */
    slider.style.setProperty("background-image", `${gradient}, url('${images[ Math.floor(Math.random() * images.length) ]}')`);
</script> 


<style type="text/css">

    /* ATENÇÃO = PSEUDO-ELEMENTOS - Exige o "::" */
    #qLoverlay {
        position: relative;            
        background-size: cover;
        height: 100vh;
        width: 100vw;
    }

    #qLoverlay::after {
        position: absolute;
        content: url(images/logo.png);
        top: 50%;
        left: 50%;
        margin-left: -600px;
        margin-top: -600px; 
    }
</style>

Here the important thing is in the div where the background image is shown for my case, Queryloader2, just put a #ID, then eh just point the const slider=Document.querySelector("#qLoverlay") and last adjust the class / ID #qLoverlay in CSS style.

  • 1

    Many thanks to friend @hugocsl for the css tip !

  • Thanks also to the friend @Valdeir Psr who made available the JS script and the way to make the image’s Random ! Thanks !!!!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.