Change element padding based on element height and parent height with javascript - javascript

I need to change the size of h1's top padding based on the height of h1 and it's parent.
Padding top would be (h1's height - h1's parent height) / 2
I still don't understand why the JavaScript code isn't working.
window.onload = function() {
const h1 = document.getElementsByTagName("h1")[0];
h1.innerHTML = document.title;
h1.style.paddingTop = (((h1.parentElement.clientHeight - h1.clientHeight) / 2).toString());
console.log(((h1.parentElement.clientHeight - h1.clientHeight) / 2).toString());
}
header {
border-bottom: solid 1px black;
position: fixed;
height: 10vh;
width: 100%;
}
h1 {
margin: 0px;
margin-top: auto;
}
<header>
<h1>Text</h1>
</header>

Simply because you have not used a unit to identify the value of evaluated padding. Additionally add display: block to the h1 style. Checkout this JSBin demo.
window.onload = function() {
const h1 = document.getElementsByTagName("h1")[0];
h1.innerHTML = document.title;
h1.style.paddingTop = (((h1.parentElement.clientHeight - h1.clientHeight) / 2).toString())+'vh'; // Use unit.
console.log(((h1.parentElement.clientHeight - h1.clientHeight) / 2).toString());
}
header {
border-bottom: solid 1px black;
position: fixed;
height: 10vh;
width: 100%;
}
h1 {
margin: 0px;
margin-top: auto;
display: block;
}
<header>
<h1>Text</h1>
</header>

Related

Create iframes showing the end of each one as if I had dragged the scrollbar to the end

In short: what I only need is this graphic map and the team symbol, without the other data appearing on the screen, wasting space and without the scrollbar on the right side that covers the end of the graphic.
var myIframe = document.getElementById('iframe');
myIframe.onload = function(){
myIframe.contentWindow.scrollTo(0,500);
};
<iframe id="iframe" src="https://www.sofascore.com/event/9626475/attack-momentum/embed"></iframe>
When creating the iframe, it comes with some unwanted data that only takes up space, as I left circled in the image below:
When I decrease the size of the iframe to take up less space, this happens:
What I would like to happen is that when creating the iframe, it would already scroll to the end, thus automatically:
Is there anything I can put in my HTML or script that can do this automatic scrolling when creating iframes?
I also tried using .style("margin-top","-90px"); but doing so happens that the values exceed the iframe limits getting on top of the previous ones:
If you want to do the complete test, use this code and create a CSV file with the sofascore ids (SofaScore_Live.csv):
<html>
<head>
<style>
{
box-sizing: border-box;
}
.vl {
border-left: 3px solid red;
height: 1000px;
position: absolute;
left: 30.3%;
margin-left: -3px;
top: 0;
}
.vl2 {
border-left: 3px solid red;
height: 1000px;
position: absolute;
left: 10.9%;
margin-left: -3px;
top: 0;
}
.vl3 {
border-left: 3px solid red;
height: 1000px;
position: absolute;
left: 69%;
margin-left: -3px;
top: 0;
}
.matches {
text-align:center;
float: left;
width: 700px;
border: 1px solid white;
border-collapse: collapse;
}
.column {
text-align:center;
float: left;
width: 700px;
border: 1px solid white;
border-collapse: collapse;
}
.grid {
float: left;
width: 100%;
}
.row:after {
content: "";
display: table;
clear: both;
}
.button {
background-color: #33ccff;
color: black;
font-weight: bold;
}
input[type=submit] {
background-color: #33ccff;
color: black;
font-weight: bold;
}
html {
overflow: scroll;
overflow-x: hidden;
}
::-webkit-scrollbar {
width: 0px; /* remove scrollbar space /
background: transparent; / optional: just make scrollbar invisible /
}
/ optional: show position indicator in red */
::-webkit-scrollbar-thumb {
background: #FF0000;
}
</style>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/7.1.1/d3.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/d3-fetch#3"></script>
</script>
</head>
<body style="background-color:black;">
<div class="vl"></div>
<div class="vl2"></div>
<div class="vl3"></div>
<div style="color:white;font-weight:bold" class="grid games" id="jogos-sofascore">
</div>
<script id="script-da-caixa-de-selecao-suspensa-5">
var select_5 = d3.select("#jogos-sofascore")
.append("div")
.attr("id","select-box-5")
.style("width","100%")
function valorparaiframe(iframevalue) {
let link = iframevalue;
return "https://www.sofascore.com/event/" + iframevalue + "/attack-momentum/embed";
}
async function update() {
let data = await d3.csv("./SofaScore_Live.csv");
let update_5 = select_5.selectAll(".matches")
.data(data,d=>d.id);
update_5.exit().remove();
// Enter new divs:
const enter = update_5.enter()
.append("div")
.attr("class","matches");
// Append the children to entered divs:
enter.append("iframe")
.attr("src",d => valorparaiframe(d.id))
.style("width","100%")
.style("height","110");
}
update();
setInterval(update,60000);
</script>
</div>
</body>
</html>
SofaScore_Live.csv CSV example:
id
9576375
9602988
9643997
9944904
9591418
9595065
9595129
9595043
9671970
9698797
9671975
9671974
9578901
iframes loaded from a different origin are protected by the same-origin-policy, which prevents you from accessing/modifying the content of it (which is why you can't use scrollTo etc,.).
As a workaround, if you know the height of the content in the iframe (which you can retrieve by going to the iframe source and getting the body's offsetHeight), you can set the height of the iframe to the height of the content. Then, you can wrap the iframe in a container, set the container's height, and scroll to the bottom of the container.
const container = document.querySelector('.iframe-container')
container.scrollTop = container.scrollHeight;
iframe {
height: 200px;
width: 100%;
border: none;
}
.iframe-container{
height:120px;
overflow:auto;
}
<div class="iframe-container">
<iframe id="iframe" src="https://www.sofascore.com/event/9626475/attack-momentum/embed"></iframe>
</div>
You can use the scroll(x, y) function:
scroll(0, 10000)

Not able to make element stick to the bottom when offscreen in IE 11, just like in css sticky

I am trying to replicate the same behavior as in this
codepen in IE 11 (does not have css sticky)
I am able to detect when the item is offscreen at the start with:
if (
$(".main-content").height() + $(".main-content").offset().top <
$(".main-footer").offset().top
)
but then after it reaches the end of the scroll (in this case the page), I did not manage to check when it goes offscreen again. It is probably something simple as subtracting the scroll to figure out if the element is offscreen, I am just stuck...
Here is a codepen where I stuck am now.
IE doesn't support <main> so you can't use this tag in IE 11. You can monitor the scroll bar changes through JavaScript, and then change its class according to the position of the element.
Here is the code you can refer to:
$(document).scroll(function() {
var scroH = $(document).scrollTop();
var viewH = $(window).height();
var contentH = $(document).height();
$('.main-footer').addClass('main-footer1')
if (scroH > 100) {}
if (contentH - (scroH + viewH) <= 100) { // The height from the bottom is less than 100px
}
if (contentH <= (scroH + viewH + 100)) {
$('.main-footer').removeClass('main-footer1')
$('.main-footer').addClass('main-footer2')
} else {
$('.main-footer').addClass('main-footer1')
$('.main-footer').removeClass('main-footer2')
}
});
body {
color: #fff;
font-family: arial;
font-weight: bold;
font-size: 40px;
}
.main-container {
max-width: 600px;
margin: 0 auto;
border: solid 10px green;
padding: 10px;
margin-top: 40px;
}
.main-container * {
padding: 10px;
background: #aaa;
border: dashed 5px #000;
}
.main-container *+* {
margin-top: 20px;
}
.main-header {
height: 50px;
background: #aaa;
}
.main-content {
min-height: 1000px;
}
.main-footer {
border-color: red;
}
.main-footer1 {
position: fixed;
bottom: 0px;
margin: 0 auto;
width: 570px;
}
.main-footer2 {
position: relative;
margin-top: 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="main-container">
<header class="main-header">HEADER</header>
<div class="main-content">MAIN contentH</div>
<footer class="main-footer">footer</footer>
</div>
Result in IE 11:

Container div doesn't take 100% height no matter what [duplicate]

This question already has answers here:
Position absolute but relative to parent
(5 answers)
Closed 2 years ago.
There are at least 2000 questions about this but in my particular scenario nothing I've tried worked.
My page consists of 2 nested divs (external, contents)
contents is clickable and should cover 100% of the document
there's also a bunch of absolutely positioned divs inside contents: those are draggable by a user and can be in any position.
If there are enough of these divs, scrollbar appears. And my contents is limited by the current browser window height, so when I start to scroll it's cut:
Here's a codepen: https://codepen.io/sergey-kritskiy/pen/qBbqQJv
I've tried...
setting min-height of everything one by one and all together;
adding flex on everything; float like this, float like that;
use %, vh, vmax;
When the scrollbar is made by a bunch of 'normal' divs, min-height works fine, but with these absolute guys I'm not in luck. I probably miss something obvious and I'd appreciate solutions.
Update:
There was an answer from someone that suggested to add position: relative; overflow-y: auto to contents and it worked in my case! But the answer was removed before I was able to ask why exactly that worked.
Solution 1
wrap items in another div called sidebar.
i am appending items in .sidebar instead of #content.
you can use grid in #external like i have used in css
var target = document.querySelector(".sidebar");
for (var i = 1; i <= 30; i++)
{
(function(i)
{
var div = document.createElement('div');
target.appendChild(div);
div.innerHTML = 'el ' + i;
div.className = 'item';
div.style.left = '5px';
div.style.top = 5 + ((i-1) * 105) + 'px';
div.addEventListener('click', function (evt) {
console.log("clicked el " + i);
evt.stopPropagation()
});
})(i);
}
target.addEventListener('click', function () {
console.log("content click");
});
body,
html {
width: 100%;
height: 100%;
margin-right: auto;
margin-left: auto;
vertical-align: middle;
margin: 0px;
background-color: white;
}
.item {
position: absolute;
background-color: blue;
width: 200px;
height: 100px;
border: 1px solid black;
}
#external {
background-color: #5b6f59;
display: grid;
grid-template-columns: 230px 1fr;
}
#content {
background-color: #5b6f59;
position: relative;
}
#external,
#content {
width: 100%;
height: 100%;
}
/** Added CSS **/
.sidebar {
height: 100vh;
overflow-y: auto;
position: relative;
}
<div id="external">
<div class="sidebar"></div>
<div id="content"> </div>
</div>
Solution #2
var target = document.querySelector("#content");
for (var i = 1; i <= 30; i++)
{
(function(i)
{
var div = document.createElement('div');
target.appendChild(div);
div.innerHTML = 'el ' + i;
div.className = 'item';
div.style.left = (Math.random()*100) + 'px';
div.style.top = 5 + ((i-1) * 105 + Math.random()*100 - 50) + 'px';
div.addEventListener('click', function (evt) {
console.log("clicked el " + i);
evt.stopPropagation()
});
})(i);
}
target.addEventListener('click', function () {
console.log("content click");
});
body,
html {
width: 100%;
height: 100%;
margin-right: auto;
margin-left: auto;
vertical-align: middle;
margin: 0px;
background-color: white;
}
.item {
position: absolute;
background-color: blue;
width: 200px;
height: 100px;
border: 1px solid black;
}
#external {
background-color: red;
}
#content {
background-color: #5b6f59;
height: 100vh;
overflow-y: auto;
position: relative;
}
#external {
width: 100%;
height: 100%;
}
<div id="external">
<div id="content">
</div>
</div>

How to get a-link (a href) background image in css to resize with javascript code

I've been racking my brain trying to get two problems figured out. One is an image cropping and the other is and image resizing one. Here is a overview of the code I have:
HTML code:
<script src="main.js"></script>
<div class="mainDiv">
<div class="columnDiv1">
<!-- a div here a div there -->
</div>
<div class="columnDiv2">
<div class="iconDiv1">Icon 1</div>
<div class="iconDiv2"><img src="/images/div2Icon.png" id="div2IconImg" width="1" /></div>
</div>
<div class="columnDiv3">
<!-- a div here a div there -->
</div>
<div class="bottomRowDiv">
<!-- a div here a div there -->
</div>
</div>
CSS code:
<style type="text/css">
.mainDiv {
z-index: 2;
float: left;
width: 1112px;
position: relative;
overflow: hidden;
}
.columnDiv1 {
z-index: 20;
position: absolute;
width: 33.36%;
padding: 0px;
float: left;
border: 0px solid;
}
.columnDiv2 {
z-index: 20;
position: absolute;
width: 30.31%;
padding: 0px;
float: left;
border: 0px solid;
}
.columnDiv3 {
z-index: 20;
position: absolute;
width: 36.33%;
padding: 0px;
float: left;
border: 0px solid;
}
.bottomRowDiv {
z-index: 20;
position: absolute;
width: 100%;
padding: 0px;
float: left;
border: 0px solid;
}
/* stuff in here for columnDiv1 */
.iconDiv1 {
z-index: 20;
position: absolute;
width: 100%;
left: 0px;
top: 0px;
padding-top: 0px;
padding-left: 0px;
padding-bottom: 75px;
padding-right: 0px;
float: left;
border: 0px solid;
}
.iconDiv2 {
z-index: 20;
position: absolute;
width: 100%;
left: 0px;
top: 0px;
padding: 0px;
float: left;
border: 0px solid;
}
/* stuff in here for columnDiv3 */
/* stuff in here for bottomRowDiv */
#iconDiv1_link {
display:block;
text-indent: -10000px;
background: url(/images/div1.png) no-repeat;
background-position: center top;
}
#iconDiv1_link:hover {
background-image: url(/images/div1hover.png);
}
</style>
JavaScript code:
_spBodyOnLoadFunctionNames.push('sizeImageMap()');
function sizeImageMap()
{
// get screen information
var currentScreenWidth = screen.width;
var currentScreenHeight = screen.height;
// get images' information
//define Image Icon Hash keys
var imgIconHash = {};
imgIconHash['image1_link'] = {};
...
...
imgIconHash['iconDiv1_link'] = {};
imgIconHash['div2IconImg'] = {};
...
...
for (var imgLinkName in imgIconHash){
var imgLink = document.getElementById(imgLinkName);
if (imgLink.nodeName === "A") {
imgLinkStyle = imgLink.currentStyle || window.getComputedStyle(imgLink, false);
imgIconHash[imgLinkName]['src']=imgLinkStyle.backgroundImage.replace(/url\((['"])?(.*?)\1\)/gi, '$2').split(',')[0];
} else if (imgLink.nodeName === "IMG") {
imgIconHash[imgLinkName]['src']=imgLink.getAttribute('src');
} else {
// not A or IMG nodes
}
// get image width and height
var tmpImg = new Image();
imgIconHash[imgLinkName]['width']=tmpImg.width;
imgIconHash[imgLinkName]['height']=tmpImg.height;
}
// initialize scaling factors
var imgScale = 1;
//set scaling factors
if(currentScreenHeight >= /*given amount*/ ) // set scale
{
imgScale = 0.5676; // reset image scale
} else {
imgScale = 0.3784; // reset image scale
}
//resize images
for (var imgLinkName in imgIconHash){
var imgLink = document.getElementById(imgLinkName);
if (imgLink.nodeName === "A") {
imgLink.style.background.width = imgIconHash[imgLinkName]['width'] * imgScale + "px";
imgLink.style.background.height = imgIconHash[imgLinkName]['height'] * imgScale + "px";
} else if (imgLink.nodeName === "IMG") {
imgLink.style.width = imgIconHash[imgLinkName]['width'] * imgScale + "px";
imgLink.style.height = imgIconHash[imgLinkName]['height'] * imgScale + "px";
}
}
}
Note, this is a webpage content part in SharePoint, hence the "_spBodyOnLoadFunctionNames.push('sizeImageMap()');" to perform an operation similar to document.onload.
So, two problems I am having:
The image in the 'columnDiv2' of 'iconDiv1' seems to be being cropped. It's size is 322px width and 128px height. The left and top don't appear to be being cropped, but the bottom and right do appear, or more so, don't appear, as though they have been cropped. I have seven other images in my code that are handled the same way, and have no problems with them, but this one appears to have the problem. It's not noticeable on the first loaded image, but on the image that shows after a 'hover', you can see the cropping.
I can get the IMG's width and height, but not the a-href link's background width and height. Any direction for this would be helpful. Also, I am doing this so that the images can be resized. Note the links are id's and not class's, as I was unable to find an easy way to access the existing images width and height, before loading, and then how to resize the a-href link's size after getting it. As said, the IMG works fine, just the A doesn't want to cooperate.
Thank you in advance.

Resize Div whilst maintaining ratio

I'm trying to create a page where a centrally placed div resizes to fit in the page both horizontally and vertically whilst retaining the ratio.
Currently I'm using a combination of JS and CSS although I'm not sure it's particularly efficient - it also seems a little hacky.
How would I either clean up this code or rewrite it to achieve this?
Javascript
function changesize(){
var $width = $(".aspectwrapper").height();
var $changewidth = $width * 1.5;
var $doc = $(document).width();
var $height;
if ($doc <= $changewidth){ $changewidth = ( $doc - 100 );
$height = ( ($doc - 100) / 1.5 );
$(".aspectwrapper").css('height', "" + $height + "");
};
$(".content").css('width', "" + $changewidth + "");
$(".aspectwrapper").css('width', "" + $changewidth + "");
};
$(document).ready(function(e) {
$(changesize);
});
$(window).resize(function(e) {
$(changesize);
});
CSS
html, body {
width: 100%;
height: 100%;
padding: 0;
margin: 0;
}
.aspectwrapper {
display: inline-block;
position: relative;
margin: 0 auto;
height: 90%;
border: #F00 1px solid;
background-color: #F00;
}
.content {
position: absolute;
top: 0;
bottom: 0;
right: 0;
margin-top: 60px;
outline: thin dashed green;
overflow: hidden;
background-color: #09C;
}
#wrapper {
width: 100%;
height: 100%;
text-align: center;
background-color: #0F3;
float: left;
}
HTML
<div id="wrapper">
<div class="aspectwrapper">
<div class="content"> CONTENT GOES HERE</div>
</div>
<div style="clear:both;"></div>
</div>
I'd personally position my center div horizontally and vertically using positioning/margin combinations with a specific liquid width and height. It would resize based on page width without the use of javascript. Here's an example.
http://jsfiddle.net/9Aw2Y/

Categories

Resources