is it possible to change the background color of my website when a specific div is in the viewport? And would it be possible to change the background color again (i.e. for the 2nd time) if another DIV is in the viewport?
So something like this:
BLUE BLUE BLUE ... DIV1 (in the viewport = background color RED) RED RED RED ... DIV2 (in the viewport = background color BLUE) BLUE BLUE BLUE
Many thanks in advance!
CodePudding user response:
you can always call that on the media query to change anything you want at particular height or color heres an example if i understand you right
body {background-color:gray;}
.mygridboxes {
display:grid;
}
.box {
height:500px;
width:500px;
background-color:red;
font-size:50px;
text-align:center;
margin:0 auto;
border:10px solid white;
}
@media only screen and (max-width:1024px){
body {
background-color:yellow;
}
.box {
background-color:green;//change background
height:350px; //resize height
width:350px;}
}
@media only screen and (max-width:768px){
body {
background-color:yellow;
}
.box {
background-color:green;//change background
height:300px; //resize height
width:300px;}
}
@media only screen and (max-width:479px){
body {background-color:blue;}
.box {
background-color:pink;//change background
height:200px; //resize the height here
width:200px;
}
}
<body>
<h1>RESIZE ME</h1>
<div >
<div >A</div>
<div >B</div>
<div >C</div>
<div >D</div>
</div>
</body>
CodePudding user response:
Explanation
"When the user scrolls to the TOP of the blue div, the background color of the body changes to red."
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll >= $('#blue').offset().top) {
$('body').css('background-color', 'red');
}
if (scroll >= $('#black').offset().top) {
$('body').css('background-color', 'blue');
}
if (scroll >= $('#black').last().offset().top) {
$('body').css('background-color', 'green');
}
});
#blue {
width: 400px;
height: 800px;
background: blue;
}
#black {
width: 400px;
height: 800px;
background: black;
}
#red {
width: 400px;
height: 800px;
background: red;
margin-bottom: 500px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="blue"></div>
<div id="black"></div>
<div id="red"></div>