1

My problem is that i want to add the parallax effect (rellax class) to the class home-content when the screen size is above 810 px and remove it when its below. Plus, if possible i want to be able to add data-rellax-speed = "-4" when rellax is enabled.

The problem is that i have the error : rellax.js:141 Rellax: The elements you're trying to select don't exist. Surelly because it does not find .relax in HTML

Here is the HTML code of the section with .home-content

<section class="home content" id="home">
        <div class="max-width">
            <div class="home-content">
                <div class="text-1 stagger1">&#128075; Bonjour, je suis</div>
                <div class="text-2 stagger1">Eric</div>
                <div class="text-3 stagger1">Et je suis un <span class="crimson" id="typing"></span></div>
                <a class="stagger2" href="#contact">Me contacter</a>
            </div>
        </div>
</section>

Here is the JS so far (i am using Rellax.js in order to achieve parallax):

$(document).ready(function(){
 // Parallax
    var rellax = new Rellax('.rellax');

    if(window.innerWidth < 810){
        $('.home-content').removeClass('rellax');

    }
})

$(window).resize(function(){
    if(window.innerWidth < 810){
        $('.home-content').removeClass('rellax');
    }else{
        $('.home-content').addClass('rellax');
    }
});

Bob
  • 87
  • 11

1 Answers1

1

Check for relax class or element before referencing:

var rellax;

$(document).ready(function(){
    if ($('.rellax').length) rellax = new Rellax('.rellax');

    if(window.innerWidth < 810) {
        $('.home-content').removeClass('rellax');
    }
})

$(window).resize(function(){
    if(window.innerWidth < 810) {
        rellax.destroy(); 
        $('.home-content').removeClass('rellax');
        
    } else {
        $('.home-content').addClass('rellax');
        rellax = new Rellax('.rellax')
    }
});
tom
  • 9,550
  • 6
  • 30
  • 49
  • Ok thanks, it works initially, but when i resize the window above 810px and come back to below 810px, the `.relax` dissapears as expected but the `style = "transform"...` that comes with the class `relax` stays which is not wanted. how can i also get rid of this attribute? – Bob Jan 08 '21 at 10:57
  • See the updated answer `rellax.destroy();` – tom Jan 08 '21 at 11:01
  • Nevermind, how can i achieve this : `
    ` using jquery? The element i want to know how to add is `data-rellax-speed = "-4"`
    – Bob Jan 08 '21 at 11:08
  • You can remove the style attribute: `$(".rellax").removeAttr("style")` or add any attribute `$(".rellax").attr("data-rellax-speed", "-4");` https://stackoverflow.com/questions/5394951/adding-and-removing-style-attribute-from-div-with-jquery – tom Jan 08 '21 at 11:09