Reputation: 201
I have a problem with my code. I am trying to add a background color to div if data attribute is true. This is my HTML code:
<html data-highcontrast-applied="true">
<head>
</head>
<body>
<div class="row-centered">
<p>
Helllllllooooooooooo
</p>
</div>
</body>
</html>
This is jQuery code
$(document ).ready(function() {
if(typeof $("html").attr('highcontrast-applied') == 'true')
{
$(".row-centered").css({"background-color": "red"});
}
});
Can somebody help me with this? Also this is a jsfiddle link: https://jsfiddle.net/dmv9o3ep/2/
Upvotes: 1
Views: 771
Reputation: 7949
You can try with .addClass().It's working.
$(document ).ready(function() {
var temp = document.getElementsByTagName("html")[0].getAttribute("data-highcontrast-applied");
if(temp === 'true')
{
$(".row-centered").addClass("intro");
}
});
.intro{
background-color : red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html data-highcontrast-applied="true">
<head>
</head>
<body>
<div class="row-centered">
<p>
Helllllllooooooooooo
</p>
</div>
</body>
</html>
Upvotes: 0
Reputation: 569
You can use native javascript to achieve
$(document ).ready(function() {
var temp = document.getElementsByTagName("html")[0].getAttribute("data-highcontrast-applied");
console.log("temp==", temp);
if(temp === 'true')
{
$(".row-centered").css({"background-color": "red"});
}
});
https://jsfiddle.net/tyfg6ezv/
Upvotes: 0
Reputation: 807
try to remove typeof and get the value of this attribute like string then compare it with 'true'
$(document ).ready(function() {
if($("html").attr('data-highcontrast-applied').toString() == 'true')
{
$(".row-centered").css({"background-color": "red"});
}
});
Upvotes: 2
Reputation: 10219
The problems with your code are:
You are not properly getting the value of the html attribute;
typeof
on $("html").attr('data-highcontrast-applied')
will return boolean
not the value of the html attribute;
I would set the data-* attribute to either 1
or 0
and then use parseInt
and check if it's equal to 1
and apply the background (or any other css properties you want):
$(document).ready(function() {
if (parseInt($("html").attr('data-highcontrast-applied')) === 1) {
$(".row-centered").css({
"background-color": "red"
});
}
});
https://jsfiddle.net/eht9faoz/
You can read more about jQuery .data()
and .attr()
:
https://stackoverflow.com/a/7262427/867418
Upvotes: 1
Reputation: 129
You should use
if($("html").attr('data-highcontrast-applied')){}
or
if($("html").data('highcontrast-applied')){}
Upvotes: 0
Reputation: 938
You dont need to use typeof
there
$(function() {
if($("html").data('highcontrast-applied') == true) {
$(".row-centered").css({"background-color": "red"});
}
});
this works like this
Upvotes: 0
Reputation: 164
You misspelled the attribute name, try this:
$(document).ready(function() {
if(typeof $("html").attr("data-highcontrast-applied"))
{
$(".row-centered").css({"background-color": "red"});
}
});
Upvotes: 0