Reputation: 3
jquery scrollLeft not working. Why this code doesn't work? Background must change if div will scroll left. contentcontentcontentcontentcontentcontentcontentcontentcontent
$(function() {
scrollLeft = $('.page').scrollLeft();
if (scrollLeft > 12) {
$('.main-header').addClass('notleft');
} else {
$('.main-header').addClass('left');
}
});
.page {
width: 600px;
overflow-x: scroll;
}
.wrap {
width: 1000px;
}
.notleft {
background: red;
}
.left {
background: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="page">
<div class="wrap">
<header class="main-header">
dnjdksvnkjsdvdjskv
</header>
</div>
</div>
Upvotes: 0
Views: 1334
Reputation: 337550
Your code has two issues. Firstly, you need to execute it within the scroll
event handler for the .page
element. Running it on load means that nothing will change. Secondly, you need to make the .notleft
CSS rule more specific so that it overrides the .left
rule and changes the background. Try this:
$(function() {
$('.page').scroll(function() {
scrollLeft = $('.page').scrollLeft();
if (scrollLeft > 12) {
$('.main-header').addClass('notleft');
} else {
$('.main-header').addClass('left');
}
}).scroll();
});
.page {
width: 600px;
overflow-x: scroll;
}
.wrap {
width: 1000px;
}
.left {
background: green;
}
.left.notleft {
background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="page">
<div class="wrap">
<header class="main-header">
dnjdksvnkjsdvdjskv
</header>
</div>
</div>
Upvotes: 1