0

I want to add data attribute to the DOM elements with jQuery but only when the $(window).width is greater that 800px. So right now I have this code and it's not working.

Note: Chrome Developer Tools doesn't report any issues in the code.

Code:

<div id="wallpaper"></div>
<div id="wallpaper-right"></div>
<div class="container"></div>

jQuery

var width = $(window).width(),
    wallpapers = $("#wallpaper, #wallpaper-right"),
    container = $(".container");

if ( width > 800) {
    wallpapers.data("stellar-ratio") === 0.1;
    container.data("stellar-ratio") === 1;
}

Desired result in HTML after adding the data attributes:

<div id="wallpaper" data-stellar-ratio="0.1"></div>
<div id="wallpaper-right" data-stellar-ratio="0.1"></div>
<div class="container" data-stellar-ratio="1"></div>

3 Answers 3

4

To set a value to a data attribute, you should pass it as the 2nd parameter in .data() method :

wallpapers.data("stellar-ratio", 0.1);
container.data("stellar-ratio", 1);

What you have written here is comparing values and type between data-stellar-ratio and 0.1 or 1.

Here's the doc for .data().

Sign up to request clarification or add additional context in comments.

Comments

1

You can also try this

   if ( width > 800) {
        wallpapers.attr({"data-stellar-ratio":"0.1"});
        container.attr({"data-stellar-ratio":"1"});
    }

Comments

1

to set a data value, you need to pass it as the second parameter of the method

var width = $(window).width(),
    wallpapers = $("#wallpaper, #wallpaper-right"),
    container = $(".container");

if ( width > 800) {
    wallpapers.data("stellar-ratio",0.1);
    container.data("stellar-ratio",1);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.