0

I have a div from template like this :

<div class="parallax-container" data-parallax-img="img/index_photos/2.jpg">
//some content
</div>

and I tried to change the div attribute with jQuery like this :

<script type="text/javascript">
    var bgImg = 1;
    window.setInterval(function(){
        yourFunction();
    }, 10000);
    function   yourFunction () {
        ++bgImg;
        if(bgImg === 4){
            bgImg = 1;
        }

        if(bgImg === 1){
            $('.parallax-container').attr('data-parallax-img', "img/index_photos/2.jpg");
        }

        if(bgImg === 2){
            $('.parallax-container').attr('data-parallax-img', "img/index_photos/3.jpg");
        }

        if(bgImg === 3){
            $('.parallax-container').attr('data-parallax-img', "img/index_photos/4.jpg");
        }
    }
</script>

So now in my browser when i click "inspect element" i can see that the attribute of this div is changing every few seconds but image does not showing at all.

j08691
  • 204,283
  • 31
  • 260
  • 272
  • 1
    What image? Changing a `data` attribute by itself will have no other affect on anything in the DOM. – Rory McCrossan Nov 06 '18 at 14:37
  • is there any way to changing it with jquery or javascript ? sorry i'm really new in jQuery as all i want is a very simple "slider" manipulating div attribute. – Kamil Łonowski Nov 06 '18 at 14:42
  • 2
    @KamilŁonowski we don't know what you're trying to do with the `data-parallax-img`. But it will do nothing by itself - it's fine to use it for some purpose of your own (that is what `data-*` attributes are for), but you have to put the code in for that yourself. – Robin Zigmond Nov 06 '18 at 14:43
  • i'm trying to make a simple slider based on changing path to image in "data" attribute. – Kamil Łonowski Nov 06 '18 at 14:52
  • Guess you are using some sort of plugin. You could check the documentation of the plugin to see if you can trigger some custom event to update the pictures based on that data attribute. Or see if they offer some code to handle the change you would like to do. – Mark Baijens Nov 06 '18 at 14:52
  • @MarkBaijens You guessed right i think : plugins = { materialParallax: $( ".parallax-container" ), }; – Kamil Łonowski Nov 06 '18 at 15:02

1 Answers1

0

If you wish to change the source of an image via jQuery you should change the src attribute e.g.,

<script type="text/javascript">
  var bgImg = 1;
  window.setInterval(function(){
    yourFunction();
  }, 10000);
  function   yourFunction () {
    ++bgImg;
    if(bgImg === 4){
        bgImg = 1;
    }

    if(bgImg === 1){
        $('.parallax-container').attr('src', "img/index_photos/2.jpg");
    }  ...

}
</script>

Further information may be found in this closely related question: Jquery change image on click

Ish
  • 71
  • 6