I have a html element which is displayed when a button is clicked. It‘s kinda like a popup. I want to check if it’s in the ViewPort of the browser and then place it inside the ViewPort . Is there a right way to achieve that?
At the moment I’m checking the height of the ViewPort and pare it to the point where the element will be attached to. So I do something like this:
If(window.innerHeight > yPointWhereElementIsAttachedTo + heightOfElement) //attach element;
But what is the right way to do it?
I have a html element which is displayed when a button is clicked. It‘s kinda like a popup. I want to check if it’s in the ViewPort of the browser and then place it inside the ViewPort . Is there a right way to achieve that?
At the moment I’m checking the height of the ViewPort and pare it to the point where the element will be attached to. So I do something like this:
If(window.innerHeight > yPointWhereElementIsAttachedTo + heightOfElement) //attach element;
But what is the right way to do it?
Share Improve this question edited Aug 2, 2019 at 8:40 str 45.1k18 gold badges114 silver badges134 bronze badges asked Aug 2, 2019 at 8:08 AlexAlex 1832 silver badges16 bronze badges 1- please provide the code of your example, you say you have the html element, make a code section showing your html element. when you say you "do something like this" please show you do that something like this – user254694 Commented Aug 2, 2019 at 8:14
2 Answers
Reset to default 3This can be achieved by using position: fixed;
on an element with positioning.
For example:
.fixed {
position: fixed;
width: 300px;
height: 100px;
background: red;
left: 10px;
top: 40px;
}
.wrapper {
min-height: 4000px;
}
<div class="wrapper">
<div class="fixed">
I am fixed in the viewport
</div>
</div>
You could use scrollIntoView() if a more dynamic approach is required.
var elmnt = document.getElementById("content");
elmnt.scrollIntoView();
https://www.w3schools./jsref/met_element_scrollintoview.asp