scandir
scandir

Reputation: 313

Adding custom data attribute to DOM element

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>

Upvotes: 0

Views: 727

Answers (3)

collab-with-tushar-raj
collab-with-tushar-raj

Reputation: 1287

You can also try this

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

Upvotes: 1

Marcelo Biffara
Marcelo Biffara

Reputation: 831

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);
}

Upvotes: 1

Tiki-Web
Tiki-Web

Reputation: 106

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().

Upvotes: 4

Related Questions