Reputation:
Button show has position: fixed
property only inside the second div. When I scroll to the first or last div, button should not be fixed on them, which means the button should be visible only inside the second div, how can I do that?
.one{
height:600px;
width: 100%;
background-color: red;
}
.two{
height:600px;
width: 100%;
background-color: yellow;
}
.three{
height:600px;
width: 100%;
background-color: pink;
}
.mybutton{
width:80px;
height: 20px;
position: fixed;
right:10px;
top:100px;
}
<html>
<head>
<body>
<div class="one">
<button class="mybutton">Click</button>
</div>
<div class="two"></div>
<div class="three"></div>
</body>
</head>
</html>
Upvotes: 2
Views: 1351
Reputation: 26
You should try to use
https://developer.mozilla.org/en-US/docs/Web/API/Window/scroll
With window.scroll() you can attach event on the scroll of the page like eg:
$(window).scroll(function () {
if ($(window).scrollTop() > 100) {
$('.mybutton').css("position": "fixed");
}else if ($(window).scrollTop() > 200 || $(window).scrollTop() < 100){
$('.mybutton').css("position": "static");
}
})`
Upvotes: 0
Reputation: 23664
Here's one way, though I don't know if it's the one you're looking for. Use position:sticky
on the button, and position:relative
on the container (.two
)
.one {
height: 600px;
width: 100%;
background-color: red;
}
.two {
height: 600px;
width: 100%;
background-color: yellow;
position: relative;
}
.three {
height: 600px;
width: 100%;
background-color: pink;
}
.mybutton {
width: 80px;
height: 20px;
position: sticky;
right: 10px;
top: 100px;
}
<div class="one"></div>
<div class="two"><button class="mybutton">Click</button></div>
<div class="three"></div>
Upvotes: 3
Reputation: 3920
Position: fixed places an element relative to the view port. If you want to place an element relative to a parent element, place it inside the parent element with Position:relative
.one{
height:600px;
width: 100%;
background-color: red;
}
.two{
height:600px;
width: 100%;
background-color: yellow;
}
.three{
height:600px;
width: 100%;
background-color: pink;
}
.mybutton{
width:80px;
height: 20px;
position: relative;
right:10px;
top:100px;
}
<html>
<head>
<body>
<div class="one"></div>
<div class="two">
<button class="mybutton">Click</button>
</div>
<div class="three"></div>
</body>
</head>
</html>
Upvotes: 0