Search code examples
c#cssbackground-image

making a background image dynamic and change every few seconds


What my code is doing:

  • creates an img tag that changes the image every 3 seconds.
  • background image is static
  • currently, we have a dynamic img tag that's changing every 3 seconds on top of a static background. reason being it was a test to see I could make it dynamic

What I want to do:

  • background-image inside the script tag to change and somehow make the URL() dynamic. Background image should change very 3 seconds

<div class="text-center background">

    <p>come content</p>

    <img id="image" src="~/images/baseball.jpg">
    
    <script type = "text/javascript">
        var image = document.getElementById("image");
        var currentPos = 0;
        var images = ["/images/baseball.jpg", "/images/basketball.jpg", "/images/football.jpg", "/images/soccerball.jpg"], i = 0;

        function changeimage()
        {
            if (++currentPos >= images.length)
                currentPos = 0;

            image.src = images[currentPos];
        }
        setInterval(changeimage, 3000);
    </script>

</div>

<style>
.background{
    background-image: url(/images/basketball.jpg); //<<<-----this line needs to be dynamic
    background-repeat: no-repeat;
    background-size: cover;
    height: 1000px;
}
</style>

I understand I may need to restructure my code a little. I just don't know how to go about doing it with a background. with a normal image tag it's easy because I simply reassign a new image path to the old Id.

Additional information:

framework: .netcore-mvc

bootstrap: 4.6


Solution

  • Just set the style of the background element, its practically the same as your current solution:

    There's a good solution for this on SO: [Changing background-image with JavaScript]

    <div id="background" class="text-center background">
    
        <p>come content</p>
            
        <script type = "text/javascript">
            var background = document.getElementById("background");
            var currentPos = 0;
            var images = ["/images/baseball.jpg", "/images/basketball.jpg", "/images/football.jpg", "/images/soccerball.jpg"], i = 0;
    
            function changeimage()
            {
                if (++currentPos >= images.length)
                    currentPos = 0;
    
                background.style.backgroundImage = "url(" + images[currentPos] + ")";
            }
            setInterval(changeimage, 3000);
        </script>
    
    </div>
    

    This solution is pure HTML Javascript, there are image carousel controls and component based solutions that will help if you want to run the timing logic on the server, but this javascript is a very simple solution to the problem.