What i'm trying to do is make the title of a blog post exactly half the width of the blog description and align itself at 50% of the width of the blog description.
This is what i tried in JS:
var post_title_width = document.getElementById("post_desciption").offsetWidth;
var post_title_width = post_description * 0.5;
document.getElementbyId("post_title").style.width = post_title_width;
HTML:
<div class="post">
<span class="post_title">This is a test title, testing some javascript...........</span><br>
<span class="post_description">Hello this is a test description right here, just to test some code im trying to do</span>
</div>
I am not using css because i want to test javascript and learn how to use it efficiently.
If you really want to do it in javascript, you've got a few problems:
You're trying to target class names with getElementbyId
Your variable names are messed up
Spans are not block elements, so setting the width isn't applicable unless you set overflow and change the display to block or inline-block
http://jsfiddle.net/cmweU/
var post_description = document.getElementsByClassName("post_description")[0],
post_description_width = post_description.offsetWidth,
post_title_width = ( post_description_width * 0.5 ) + "px";
document.getElementsByClassName("post_title")[0].style.width = post_title_width;
Try this (example):
HTML
<div id="head"><div id="half"></div></div>
CSS
#head {
width: 300px;
height: 100px;
background: purple;
}
#half {
height: 100%;
background: green;
}
JS
document.getElementById("half").style.width = document.getElementById("head").offsetWidth / 2 + 'px';
JS for margin inner block at the center of it's countainer try to use this (example):
document.getElementById("half").style.marginLeft = (document.getElementById("head").offsetWidth - document.getElementById("half").offsetWidth) / 2 + 'px';
Related
I've got an image on the page (I'll call it the background image) and I've allowed the user to enter some text that is positioned via css over the background image. As well, there are a few other small images that will be automatically position over the background image using css based on the text.
I want to turn what the user setup/created into an actual downloadable image now, essentially "flattening the layers" in photo editing terms.
I'd also ideally like to do this at a very high resolution as the original background image exists in a much larger and higher resolution format than the one the people see when editing.
I'm not sure the best way to do this. I'd be using NodeJS and Lambdas.
One solution I think would be to perhaps have another page exist with the full size background image and have the css reposition and resize everything perfectly and take a screenshot with puppeteer or something, although I don't know if that'll lose the quality of the original image somehow?
Or do I size the overlayed text and images correctly for the background and take screenshots of each of them, somehow add transparency, and then somehow merge the pictures?
Is there a way easier thing I'm missing or some package that can help?
If you create an element which has the full-size image, overlay the users' text and any other required image - both suitably scaled up in size and position, you can save that element on a canvas and then convert that to an image.
Here is some code to give the idea. It's using html2canvas but actually you could just create the canvas and draw the images and write the text to it without needing a library if preferred. (The code runs from my server and on my laptop and on https://codepen.io/rgspaces/pen/RwoNxVQ but does not run in a SO snippet - ??a CORS problem with iframe inside snippet system??).
<head>
<script src="https://ahweb.org.uk/html2canvas.js"></script>
<style>
body {
overflow: hidden;
margin: 0;
padding: 0;
box-sizing: border-box;
--t: 20px; /* distance from top of the user's text in the workspace */
--l: 20px; /* distance from left of the user's text */
--f: 30px; /* fontsize of the user's text in the workspace */
}
#big {
position: absolute;
left: 100vw;
display: none;
width: auto;
height: auto;
}
#workspace {
width: 50vw;
height: auto;
}
#workspace .mainimg {
width: 100%;
height: auto;
}
#workspace .text, #big .text {
position: absolute;
color: white;
}
#workspace .text {
top: var(--t);
left: var(--l);
font-size: var(--f);
}
</style>
</head>
<body>
<div id="big">
<img id="bigimg" src="https://picsum.photos/id/1016/3844/2563.jpg" class="mainimg" crossOrigin = "anonymous">
<div class="text"></div>
</div>
<div id="workspace">
<img src="https://picsum.photos/id/1016/3844/2563.jpg" class="mainimg">
<div class="text">User's text</div>
<!-- other imgs -->
</div>
<p>YOUR IMAGE WILL APPEAR BELOW - RIGHT CLICK TO SAVE IT TO FILE (WINDOWS); PRESS TO SAVE TO PHOTOS (IOS)</p>
<img id="resultimg" style="clear:both;" src=""/>
<script>
function start() {
let big = document.getElementById('big');
let bigImg = document.getElementById('bigimg');
let bigText = document.querySelector('#big .text');
let width = bigimg.width;
let height = bigimg.height;
let workspace = document.getElementById('workspace');
let workspaceText = document.querySelector('#workspace .text');
let props = window.getComputedStyle(workspace, null);
let scaling = width/props.getPropertyValue("width").replace('px','');
bigText.innerHTML = workspaceText.innerHTML;
// just some simple scaling to give an idea for now
bigText.style.fontSize = 'calc(var(--f) * ' + scaling + ')';
bigText.style.top = 'calc(var(--t) * ' + scaling + ')';
bigText.style.left = 'calc(var(--l) * ' + scaling + ')';
big.style.display = 'inline-block';
window.scrollTo(0, 0);
html2canvas(big, {allowTaint: true, useCORS: true, logging: true, width: width, height: height})
.then((canvas) => {
big.style.display = 'none';
document.body.style.overflow = 'visible';
const imgData = canvas.toDataURL('image/png', 1);
const resultImg = document.getElementById('resultimg')
resultImg.src = imgData;
resultImg.style.width = width + 'px';
resultImg.style.height = 'auto';
});
}
window.onload = start;
</script>
</body>
</html>
I am developing a web application using AngularJS. I find myself in a situation where I have a bar (with the css I created a line) that must dynamically lengthen and shorten.
I know that JQuery scripts are sufficient to do this. For example, if my css is like this:
.my_line{
display:block;
width:2px;
background: #FFAD0D;
height: 200px; /*This is the part that needs to dynamically change*/
}
I could in the controller resize the line (of my_line class) simply with:
$(".my_line").css("height", someExpression*100 + 'px');
The thing is, I would like to dynamically resize the line based on the size of another div element (Or, in general, any HTML element of my choice).
I don't know how to get (at run-time) the size of a certain page element in terms of height.
Only in this way I would be able to create a line that dynamically lengthens or shortens as the size of a div (or some other element) changes!
How do you do this? So I will avoid writing hard-coded the measures but I want make sure that they vary as the dimensions of other elements on the page vary
I hope this is helping:
$(".my_line").css("height", $("#referenceElement").height()*5 + 'px');
.my_line{
display:inline-block;
width:2px;
background: #FFAD0D;
}
#referenceElement {
display:inline-block;
background: yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="my_line"></div>
<div id="referenceElement">Hi, I'm 5 time smaller than the orange line!</div>
Here I am using the setInterval to track the div's height (you can do width as well) and storing it in a previousHeight variable and comparing it every interval
Then according to the comparison, it will determine if the height of the div has changed. If it has then it will change the height of the other div according to the height of the first div
You can create multiple variables and track multiple elements in the same setInterval
$(document).ready(function(){
var previousHeight = parseInt($("#my-div").css("height"));
setInterval(function(){ checkHeight(); }, 100);
function checkHeight() {
// Check height of elements here
var currentHeight = parseInt($("#my-div").css("height"));
if(currentHeight != previousHeight) {
previousHeight = currentHeight;
$("#dynamic-div").css("height", parseInt(currentHeight) + "px");
}
}
$("#button").click(function() {
$("#my-div").css("height", parseInt(previousHeight) + 5 + "px");
})
})
#my-div{
background: #000000;
height: 20px;
width: 20px;
}
#dynamic-div{
background: teal;
height: 20px;
width: 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="my-div">
</div>
<button id="button">Increase div height</button>
<div id="dynamic-div">
</div>
I'am developing search engine to my App, and as part of it the user can search multiple phrase here is some example -
When the input line is full like that:
It's height should be adjusted and the text cursor should get to the next line.
The problem is, that it's look like that in the third line my alogrithm is no longer work and it's look like that:
The structure of my the search input is like that
Html:
<div id=s"earchDiv">
<input id="searchInput">
</input>
</div>
JS:
var sDiv = document.getElementById('searchDiv');
var sInput = document.getElementById('searchInput');
var currH = $(sDiv).height();
$(sDiv).css('height', sDiv.scrollHeight + 'px');
var h = 40 - ($(sDiv).height() % 40);
if ($(sDiv).height() % 40 != 0)
$(sDiv).css('height', ($(sDiv).height() + h) + 'px');
which mean that acuttaly the div height is shoud be adjusted.
Someone have some idea or algorithm that can work at that situation?
First of all you have an error in your html:
<div id=s"earchDiv">
<input id="searchInput">
</input>
</div>
should be like this:
<div id="searchDiv">
<input id="searchInput">
</input>
</div>
after that ... i dont see why you use JS to style when you can directly use CSS to style the searchDiv like below:
.searchDiv {
display: block;
width: 100%;
height: auto; // this is important
min-height: 40px; // change this as you wish
}
You can do this via CSS.
#searchDiv{
overflow:hidden; /* the parents of searchdiv should not have fixed height. */
}
I am rendering a series of images on the fly into a container. At the end I want a single image centered and the other images to the left and right of it.
My problem is with centering the image. I made a full fiddle with my entire code which is ironically working as I expect it to be. However when testing it I find that
centered.width()
Returns 0 instead of returning the width of the image that should be centered.
Here centered is an image-tag I previously created on the fly.
What confuses me most is how it works in the fiddle but not when I test it opening the website locally, having exactly the same code in there as in the fiddle.
Here goes the entire page I currently have.
var ashe = JSON.parse('{"id":22,"key":"Ashe","name":"Ashe","title":"the Frost Archer","skins":[{"id":22000,"name":"default","num":0},{"id":22001,"name":"Freljord Ashe","num":1},{"id":22002,"name":"Sherwood Forest Ashe","num":2},{"id":22003,"name":"Woad Ashe","num":3},{"id":22004,"name":"Queen Ashe","num":4},{"id":22005,"name":"Amethyst Ashe","num":5},{"id":22006,"name":"Heartseeker Ashe","num":6},{"id":22007,"name":"Marauder Ashe","num":7}]}');
var currentCha = ashe;
function displaySkins(cha) {
//Clear the display.
var $skinDisplay = $('#skinDisplay');
var $skinSpinner = $('#skinSpinner');
$skinDisplay.html('');
$skinSpinner.html('');
currentCha = cha;
//Add small perviews to spinner
cha.skins.forEach(function(skin) {
var img = $('<img class="small-preview" src="http://ddragon.leagueoflegends.com/cdn/img/champion/loading/' + cha.key + '_' + skin.num + '.jpg">');
$skinSpinner.append(img);
skin.img = img;
})
spinTo(0);
}
function spinTo(index) {
centered = currentCha.skins[index].img;
var left = $('#skinSpinner').width() / 2 - centered.width();
console.log(centered.width());
centered.css('left', left);
}
displaySkins(ashe);
#skinDisplay {
width: 100%;
height: 100%;
}
#skinSpinner {
width: 500px;
height: 200px;
border: 1px solid black;
perspective: 500px;
}
#skinSpinner .small-preview {
position: absolute;
display: block;
height: 100%;
width: auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="overlay">
<div id="skinDisplay">
</div>
<div id="skinSpinner">
</div>
</div>
bind a load checker to spinTo function:
function spinTo(index) {
centered = currentCha.skins[index].img;
$(centered).bind('load', function(){
var left = $('#skinSpinner').width() / 2 - centered.width();
console.log(centered.width());
centered.css('left', left);
});
}
Seems like you are accessing your DOM before loading it.
$( document ).ready(function(){ displaySkins(ashe); });
This will defer execution of your script until the DOM is loaded.
It works in the fiddle as they put include the script in the end of the DOM. So DOM is loaded first and the script is included and finally executed. You do it the other way round (which is also fine) which obviously does not work
I need to know how one can get the maximum possible width of a div. Generally, a <div>'s width is limited by it's parent, meaning that it can not be larger than a certain amount. How that certain amount can be calculated?
I need this to calculate if the text inside the current <div> has overflown, (since the only way to detect a text overflow is to compare it's current width to its current clientWidth).
Thanks!
A couple ways to do this, let's start with your div...
<div id='mr_cleaver'>
<div id='beaver'>Blah</div>
</div>
...and then someJavascript:
//Method One: Find the width of the div's parent
var max_beaver_width = $('mr_cleaver').offsetWidth
//Method Two: Max out the div, find length, return to original size.
var beaver_width = $('beaver').offsetWidth;
$('beaver').style.width = "100%";
var max_beaver_width = $('beaver').offsetWidth;
$('beaver').style.width = beaver_width + 'px';
//Method Three: Check for overflow
$('beaver').scrollWidth > $('beaver').offsetWidth ? alert("Over") : alert("Within")
Thanks Steve!
Your suggestions were very helpful. Although none of them worked for me(probably I didn't explain my situation very well), but using your hints, I could find a way to detect text overflow:
/* specifying the height of 'beaver'*/
var font_size= $('beaver').css("font-size");
font_size = parseInt(font_size.replace(/[a-z]*/gi,''));
var maxHeight = font_size + 4; // 4 is to make sure that the font fits in the maxHeight
/*now calculate current height*/
$('beaver').style.overflow-y:visible;
$('beaver').style.overflow-x:hidden;
var cuurentHeight = $('beaver').clientHeigth;
/* check whether overflow is occured*/
if(cuurentHeight > maxHeight){
//overflow has been occured
}
If you want the div to be 100 % in width with no space between the edges, you can try to add this simpel CSS style to the div:
<style type="text/css">
#FullWidthDiv { // EDIT
position: absolute; // If you use 'fixed' as position, then the div
display: block; // won't become smaller when the screen is at is smallest.
float: left; // The fixed position is good when you for example want the
width: 100%; // menu to stay in place.
background-color: #06F;
height: auto;
left: 0px;
top: 0px
}
</style>
<html>
<body>
<div id="FullWidthDiv"></div>
</body>
</html>
You can append a div into parent element to measure it.
var test = document.querySelector('#test');
var div = document.createElement('div');
div.style.width = '10000px';
test.appendChild(div);
var maxWidth = test.offsetWidth;
test.removeChild(div);
alert(maxWidth);
#test {
display: inline-block;
max-width: 100px;
}
<div id="test"></div>