Aldridge1991
Aldridge1991

Reputation: 1367

Jquery not changing image

First I must say I'm quite new to JQuery. I'm following the tutorial at w3schools. I have a website with an image and some text (h1). I want to change the background image after some time. I've used the jquery below but it's not working (nothing happens)

My code is this:

<div class="fullscreen-bg">
        <img src="~/Content/Images/Portada2.png" class="fullscreen-bg__img" id="cover">
</div>

<div class="container page-header text-center">
        <h1 class="animated zoomIn" style="font-size:5em">Pizzeria Britannia</h1>
</div>

 <script>
        $(document).ready(function(){
            var urlArray = [
                '~/Content/Images/Portada2.png', '~/Content/Images/retina_wood_2X.png',
            ];
            var slideShowTimings = 2000;
            var i = 0
            setInterval(function () {
                var $img = $('img');
                $img.hide(slow, function () {
                    $img.attr('.src', urlArray[++i % urlArray.length]);
                    $img.show(fast)
                });
            }, slideShowTimings);
        });
</script>

Do you have any idea?

Upvotes: 0

Views: 47

Answers (1)

Luke
Luke

Reputation: 23680

  • You don't need any $ in front of your variables in JavaScript
  • You had a . in front of your 'src' in your attr change
  • Missing semi-colons
  • You were using % modulus symbol in there, but I'm not sure why so I replaced it with a ternary if that resets to 0
  • fast and slow needed quotes in order to work, cause they are strings and not variables

Maybe other issues?

<script>
        $(document).ready(function(){
            var urlArray = [
                '~/Content/Images/Portada2.png', '~/Content/Images/retina_wood_2X.png',
            ];
            var slideShowTimings = 2000;
            var i = 0;
            setInterval(function () {

                // Increase i
                i++;

                // Set the value of i and loop back to 0 if desired
                i = (i > urlArray.length) ? i : 0;

                var img = $('img');
                img.hide('slow', function () {
                    img.attr('src', urlArray[i]);
                    img.show('fast');
                });
            }, slideShowTimings);
        });
</script>

Upvotes: 3

Related Questions