Reputation: 313
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
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
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
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