The width of the element changes as I type text between its tags. My question that I want some kind of relation of Width with Height. As the width gets longer, the height increases by the same but I don't want the height to exceed 35px nor start with below 5px.
The code I tried:
HTML:
<div class="btn bg-red">This buttons width expands as I write more and more text.</div>
CSS:
.btn {
padding-left: 10px;
padding-right: 10px;
display: inline-block !important;
border-radius: 6px;
color: #ffffff;
padding-top: 10px;
padding-bottom: 10px;
height: relative;
}
.bg-red{background-color:#F55C58;}
.bg-red:hover{background-color:#F44946}
I'm not sure if it is possible in CSS to do this.
Then I tried this:
HTML:
<div class="btn bg-red"><div class="auto">This buttons width expands as I write more and more text.</div></div>
CSS:
.btn {
padding-left: 10px;
padding-right: 10px;
display: inline-block !important;
border-radius: 6px;
color: #ffffff;
padding-top: 10px;
padding-bottom: 10px;
}
.auto {
height: 20%
}
.bg-red{background-color:#F55C58;}
.bg-red:hover{background-color:#F44946}
Javascript:
var cw = $('.auto').width();
$('.auto').css({'height':cw+'px'});
The second code doesn't seem to follow display:inline. It works when you change the code manually.
Find demo for First code here.
Find demo for Second code here.
Edit:
Understood Meaning: When the button/element has less text, the width is small and the same way, the height should act same but 20% less pixels. When the text is increased, the width increases and the height should also increase. The max length of Height can reach up to 35px but the Width is Infinite by default.
I don't know how do you add text on your div. Anyway, on the following snippets the eventlistener trigger is set to input since it's a contenteditable div (the text is added by the user throught keyboard).
Snippet #1:
document.getElementsByTagName("body")[0].onload=function(){equalize()};
var target = document.getElementById("target");
target.addEventListener("input", equalize);
function equalize() {
var x = target.offsetWidth;
target.style.height = x + "px";
}
#target {
display: inline-block;
background: skyblue;
}
<div id=target contenteditable="true">write here</div>
This second snippet is the same as the previous one, but now the height is 20% smaller than the width (it was equal on the previous example) plus have a max-height limit of 100px.
Snippet #2:
var target = document.getElementById("target");
document.getElementsByTagName("body")[0].onload=function(){equalize()};
target.addEventListener("input", equalize);
function equalize() {
var x = target.offsetWidth;
var reducedpart = x / 100 * 20;
var result = x - reducedpart;
if (result > 100) {
var result = 100;
}
target.style.height = result + "px";
}
#target {
display: inline-block;
background: skyblue;
}
<div id=target contenteditable="true">write here</div>
Same as before but using padding instead of height to let the text on center:
Snippet #3:
var target = document.getElementById("target");
document.getElementsByTagName("body")[0].onload=function(){equalize()};
target.addEventListener("input", equalize);
function equalize() {
var x = target.offsetWidth;
var reducedpart = x / 100 * 20;
var result = x - reducedpart;
if (result > 100) {
var result = 100;
}
var secresult = result / 2;
target.style.paddingTop = secresult + "px";
target.style.paddingBottom = secresult + "px";
}
#target {
display: inline-block;
background: skyblue;
padding-left: 15px;
padding-right: 15px;
}
<div id=target contenteditable="true">write here</div>
CSS-only workaround using padding instead of height:
Snippet #4:
.container {
vertical-align: bottom;
display: inline-block;
}
#a {
width: 100%;
padding-bottom: calc(80% - 1em);
background: gold;
}
#b {
width: 100%;
padding-top: calc(40% - 0.5em);
padding-bottom: calc(40% - 0.5em);
background: tomato;
}
<div class=container><div id=a contenteditable="true">write here</div></div>
<div class=container><div id=b contenteditable="true">write here</div></div>
In jquery there's a function .height() that get the current computed height for the html element in the given ID or Class. Getting the height value of your div.auto you can monitor the height increase. Given that, you can make a condition if ($('.auto').height() <= 35px) that limit it up to 35px .
Put this <script type="text/javascript" src="jquery-1.12.2.js"></script> in your <head> and that you have the latest JQuery library.
Here's the full implementation of code. Try it in your localhost, because sometimes it doesn't work on jsfiddle or likewise.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style media="screen">
.btn {
padding-left: 10px;
padding-right: 10px;
display: inline-block !important;
border-radius: 6px;
color: #ffffff;
padding-top: 10px;
padding-bottom: 10px;
}
.auto {
height: 20%
}
.bg-red{background-color:#F55C58;}
.bg-red:hover{background-color:#F44946}
</style>
<script type="text/javascript" src="jquery-1.12.2.js"></script>
</head>
<body>
<div class="btn bg-red"><div class="auto">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</div></div>
<script type="text/javascript">
var cw = $('.auto').width();
if ($('.auto').height() <= 35px) {
$('.auto').css({'height':cw+'px'});
}
</script>
</body>
</html>
Hope this will help
Related
container = document.querySelector('.itemContainer');
for(i = 0; i < 30; i++){
container.innerHTML += '<div class="item"></div>';
if((i % 5) == 0){
document.querySelectorAll('.item')[i].style.setProperty("--width", 4+"px");
}
document.querySelectorAll('.item')[i].style.transform = "rotate(" + i * 6 + "deg)";
}
* {
margin : 0;
padding: : 0;
box-sizing : border-box;
}
body {
width : 100%;
height : 100vh;
display : flex;
justify-content : center;
align-items : center;
}
.mainContainer {
position : relative;
width : 440px;
height : 200px;
display : flex;
justify-content : center;
align-items : center;
justify-content : space-around;
border-radius : 5px;
border : 1px solid black;
background-color : silver;
}
.itemContainer{
position : relative;
width : 130px;
height : 130px;
display : flex;
justify-content : center;
align-items : center;
border-radius : 50%;
}
.item {
position : absolute;
width :2px;
height :100%;
display : flex;
justify-content : center;
}
.item::before {
top : 0px;
content : '';
position : absolute;
background : var(--background, black);
width : var(--width, 2px);
height : 10px;
text-align : center;
}
.item::after {
bottom : 0px;
content : '';
position : absolute;
background : var(--background, black);
width : var(--width, 2px);
height : 10px;
}
<div class="mainContainer">
<div class="itemContainer">H</div>
<div class="itemContainer">M</div>
<div class="itemContainer">S</div>
</div>
I want to use my "Clock Dial" drawn with JS in different Divs.
Couldn't multiply it. I'm confused. Thanks for all efforts to help.
Each div will show the parts of a clock: Hour, Minute, Second.
Thanks for any efforts to help. Hope the code is clear enough.
I have pasted "lorem" text below to send my question? ! :)
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Culpa eum enim optio ut quisquam? Iusto, iure veniam alias, ducimus reprehenderit laboriosam eum aut molestiae dolor esse saepe facilis dolore consequatur autem quaerat illum inventore quia sint libero nesciunt!
You have to create a function and reuse the code like this
Update HTML with:
<div class="mainContainer">
<div id="h" class="itemContainer">H</div>
<div id="m" class="itemContainer">M</div>
<div id="s" class="itemContainer">S</div>
</div>
JS:
function makeCircle(circle) {
container = document.querySelector('#'+circle);
for(i = 0; i < 30; i++){
container.innerHTML += '<div class="item '+circle+' "></div>';
if((i % 5) == 0){
document.querySelectorAll('.item.'+circle)[i].style.setProperty("--width", 4+"px");
}
document.querySelectorAll('.item.'+circle)[i].style.transform = "rotate(" + i * 6 + "deg)";
}
}
makeCircle('h');
makeCircle('m');
makeCircle('s');
I am showing a popup on text highlight using JavaScript. But I’m not able to position it at the center of the highlight,
Same as medium.com text highlight popup. I want the .toolbar at the center of the highlighted text like these images below.
const
getRoot = document.querySelector('.root'),
getTool = document.querySelector('.toolbar');
document.addEventListener('mouseup', e => {
window.getSelection().toString().length ?
(
getTool.style.left = e.clientX + 'px',
getTool.style.top = e.clientY + 'px',
getTool.classList.add('active')
) : null;
});
document.addEventListener('mousedown', () => {
window.getSelection().toString().length < 1 ?
getTool.classList.remove('active') : null;
});
*,
*::before,
*::after {
box-sizing: border-box;
}
body {
margin: 0;
}
.root {
max-width: 500px;
margin: 1rem auto;
font-size: 21px;
line-height: 1.8;
font-family: Times new roman;
}
.toolbar {
display: none;
position: absolute;
height: 45px;
width: 220px;
background-color: #212121;
border-radius: .25rem;
transition: .2s;
}
.toolbar.active {
display: block;
}
<div class="toolbar"></div>
<div class="root">
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Quos dignissimos porro explicabo soluta totam illum. Lorem
ipsum dolor sit amet consectetur adipisicing elit. Architecto, sunt.</p>
</div>
Medium.com
Like in this post you should use selection range and range boundingClientRect
document.addEventListener('mouseup', e => {
s = window.getSelection()
oRange = s.getRangeAt(0); //get the text range
oRect = oRange.getBoundingClientRect();
s.toString().length ?
(
getTool.style.left = ((oRect.left + oRect.width / 2) -110) + 'px', // 110 is toolbox.width/2
getTool.style.top = (oRect.top - 45 - 10) + 'px', //45 is toolbow.height
getTool.classList.add('active')
) : null;
});
I am trying to set a function on jQuery instead of pure JS and I am getting an error:
15 | prev.css('height') = prev.scrollHeight + "px";
^ Expected an assignment or function call and instead saw an expression.
This is the actual code:
function expand(target)
{
let prev = target.previousElementSibling;
prev.style.height = prev.scrollHeight + "px";
target.style.display = "none";
}
#p {
height: 50px;
overflow: hidden;
}
#read-more {
background: linear-gradient(to bottom, rgba(255,0,0,0), rgba(255,255,255,1));
color: blue;
cursor: pointer;
position: absolute;
bottom: -20px;
padding: 15px 0;
text-align: center;
width: 100%;
}
#wrapper {
position: relative;
width: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='wrapper'>
<p id='p'>Pinterest taxidermy et heirloom, ennui enim eu bicycle rights fugiat nesciunt commodo. High Life food truck jean shorts in. Blog asymmetrical cold-pressed photo booth. Neutra chia in, mustache Etsy nostrud plaid kogi. Magna polaroid stumptown aliqua put a bird on it gentrify, street art craft beer bicycle rights skateboard. DIY plaid gentrify, sustainable sapiente seitan mumblecore viral cardigan. Nisi pariatur laborum cornhole kitsch tempor fingerstache Bushwick. </p>
<div id='read-more' onclick="expand(this)">
READ MORE
</div>
</div>
And I am trying to set that here:
var toggleReadMore = function() {
$('#read-more').click(function(e) {
var prev = $(this).prev();
prev.css('height') = prev.scrollHeight + "px";
$(this).hide();
});
};
What am I doing wrong?
You cannot assign the value like that, you need to change it to something like
prev.css('height', prev.scrollHeight)
Where the second argument accepts the scroll height. In case of multiple CSS properties, you can pass an object like
prev.css({
height: 'some height here',
width: 'some width here'
});
** Change 3rd line like below **
var toggleReadMore = function() {
$('#read-more').click(function(e) {
var prev = $(this).prev();
prev.css('height', 50);
$(this).hide();
});
};
I am new to JavaScript and I am trying to do small exercises to practice the concepts. I am facing an issue on this very basic onClick effect: The text is supposed to expand when you click on the button. The effect isn't applied and the console doesn't display any errors.
Here is my code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Test</title>
<link type = "text/css" rel = "stylesheet" href="style.css">
</head>
<body>
<div id="content">
<p>Has autem provincias, quas Orontes ambiens amnis imosque pedes Cassii montis illius celsi praetermeans funditur in Parthenium mare, Gnaeus Pompeius superato Tigrane regnis Armeniorum abstractas dicioni Romanae coniunxit.</p>
<p>Utque aegrum corpus quassari etiam levibus solet offensis, ita animus eius angustus et tener, quicquid increpuisset, ad salutis suae dispendium existimans factum aut cogitatum, insontium caedibus fecit victoriam luctuosam.</p>
<p>Montius nos tumore inusitato quodam et novo ut rebellis et maiestati recalcitrantes Augustae per haec quae strepit incusat iratus nimirum quod contumacem praefectum, quid rerum ordo postulat ignorare dissimulantem formidine tenus iusserim custodiri.</p>
<p>Has autem provincias, quas Orontes ambiens amnis imosque pedes Cassii montis illius celsi praetermeans funditur in Parthenium mare, Gnaeus Pompeius superato Tigrane regnis Armeniorum abstractas dicioni Romanae coniunxit.</p>
<p>Utque aegrum corpus quassari etiam levibus solet offensis, ita animus eius angustus et tener, quicquid increpuisset, ad salutis suae dispendium existimans factum aut cogitatum, insontium caedibus fecit victoriam luctuosam.</p>
<p>Montius nos tumore inusitato quodam et novo ut rebellis et maiestati recalcitrantes Augustae per haec quae strepit incusat iratus nimirum quod contumacem praefectum, quid rerum ordo postulat ignorare dissimulantem formidine tenus iusserim custodiri.</p>
</div>
<a id="show-more">Show More</a>
<script type="text/javascript">
var content = document.getElementById("content");
var button = document.getElementById("show-more");
button.onClick = function() {
if(content.className == "") {
content.className = "open";
button.innerHTML = "Show Less";
} else {
content.className = "";
button.innerHTML = "Show More";
}
};
</script>
</body>
</html>
CSS:
body {
background: #605770;
}
#content {
width: 400px;
max-height: 270px;
background: #EDCB96;
margin: 15px auto;
padding: 0 10px 10px;
font-family: sans-serif;
font-size: 12px;
color: black;
overflow: hidden;
-webkit-transition: max-height 0.7s;
-moz-transition: max-height 0.7s;
transition: max-height 0.7s;
}
#content.open {
max-height: 1000px;
-webkit-transition: max-height 0.7s;
-moz-transition: max-height 0.7s;
transition: max-height 0.7s;
}
#show-more {
width: 90px;
height: 20px;
text-transform: uppercase;
font-family: sans-serif;
font-size: 12px;
font-weight: bold;
color: #605770;
background: #EDCB96;
border: 1px solid #F7C4A5;
margin: 15px auto;
display: block;
text-align: center;
padding: 2px 5px;
cursor: pointer;
}
I have also tried to put my JavaScript in a separated file and link it on the HTML, but it doesn't help.
Change onClick to onclick:
button.onclick = function() {
if(content.className == "") {
content.className = "open";
button.innerHTML = "Show Less";
} else {
content.className = "";
button.innerHTML = "Show More";
}
};
Just you need to change onClick() to onclick(). You can find details here onclick
#askhan. It's very simple to solve the issue.
Practice makes you a good developer :)
Just you add the onclick function in the anchor Tag "a"
Show More
I used textSwap() function name. eg: Show More
Run that below code you get the output:
enter code here
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Test</title>
<link type = "text/css" rel = "stylesheet" href="style.css">
</head>
<body>
<div id="content">
<p>Has autem provincias, quas Orontes ambiens amnis imosque pedes Cassii montis illius celsi praetermeans funditur in Parthenium mare, Gnaeus Pompeius superato Tigrane regnis Armeniorum abstractas dicioni Romanae coniunxit.</p>
<p>Utque aegrum corpus quassari etiam levibus solet offensis, ita animus eius angustus et tener, quicquid increpuisset, ad salutis suae dispendium existimans factum aut cogitatum, insontium caedibus fecit victoriam luctuosam.</p>
<p>Montius nos tumore inusitato quodam et novo ut rebellis et maiestati recalcitrantes Augustae per haec quae strepit incusat iratus nimirum quod contumacem praefectum, quid rerum ordo postulat ignorare dissimulantem formidine tenus iusserim custodiri.</p>
<p>Has autem provincias, quas Orontes ambiens amnis imosque pedes Cassii montis illius celsi praetermeans funditur in Parthenium mare, Gnaeus Pompeius superato Tigrane regnis Armeniorum abstractas dicioni Romanae coniunxit.</p>
<p>Utque aegrum corpus quassari etiam levibus solet offensis, ita animus eius angustus et tener, quicquid increpuisset, ad salutis suae dispendium existimans factum aut cogitatum, insontium caedibus fecit victoriam luctuosam.</p>
<p>Montius nos tumore inusitato quodam et novo ut rebellis et maiestati recalcitrantes Augustae per haec quae strepit incusat iratus nimirum quod contumacem praefectum, quid rerum ordo postulat ignorare dissimulantem formidine tenus iusserim custodiri.</p>
</div>
<a id="show-more" onclick="textSwap();">Show More</a>
<script type="text/javascript">
var content = document.getElementById("content");
var button = document.getElementById("show-more");
function textSwap() {
if (content.className == "") {
content.className = "open";
button.innerHTML = "Show Less";
} else {
content.className = "";
button.innerHTML = "Show More";
}
};
</script>
</body>
</html>
I have modified this jsFiddle http://jsfiddle.net/tV9z9/23/ to work like this jsFiddle http://jsfiddle.net/warmwhisky/N68wX/13/
When the script is first run I call this Level 1. Then you click one of the thumbnails and you move to level 2. I would like to return to the run state (Level 1) with a click. Maybe a close button or a return to first run state?
I have tried using an onclick with js but I cannot make it work.
Should I be using an onlick or can I save a state of the jquery and return to it?
Here is the code
JS...
$(function() {
var content = $('#content'),
services_level2 = $('#services_level2'),
contentHeight = content.height(),
contentWidth = content.width(),
level2Width = services_level2.width(),
nav = $('#nav'),
count = 0;
// on load content height is shorter
content.width(0);
services_level2.width(613);
nav.find('a').on('click', function() {
var $this = $(this),
parent = $this.parent(),
targetElement = $this.attr('href');
//Does the slide animation once
if (count === 0) {
//Slide out and fade away the main copy
services_level2.animate({'width': services_level2 }, function() {
$(services_level2).animate({
'margin-left': '300%',
opacity: 0
}, 900);
});
content.animate({'width': contentWidth }, function() {
parent.addClass('active');
//animate in
$(targetElement).animate({
left: '-=210px',
'margin-left': '30%',
opacity: 1
}, 400);
});
count = 1;
} else {
//only add active class if parent does not have it and then animate it
if ( !parent.hasClass('active') ) {
parent.addClass('active');
//animate in
$(targetElement).animate({
left: '-=210px',
'margin-left': '30%',
opacity: 1
}, 500);
//Gets older clicked element
var oldClickedElement = $('.active').not(parent).removeClass('active').find('a').attr('href');
//only if old click element exists the do the animation
if (oldClickedElement) {
//animate out + reset to start
$(oldClickedElement).animate({
left: 0,
'margin-left': '-50%',
opacity: 0
}, 500, function() {
$(oldClickedElement).css({
'margin-left' : '100%',
left: 0
});
});
}
}
}
return false;
});
});
HTML...
<div id="container">
<div id="services_level2">
<h1>IT Services</h1>
<p>Lorem ipsum dolor sit amet, et mel falli simul platonem, cu consul utroque neglegentur duo. Omnis soluta periculis eu sit.
</p>
<h1>Repairs</h1>
<p>
Sit te habeo neglegentur, nam no dicit intellegat. Epicuri blandit sea eu, eum nibh adhuc mundi eu.
</p>
<h1>Other</h1>
<p>
Pri nihil scaevola salutatus id, esse minimum vis ne. Verear corrumpit vim ex, vim tollit scaevola ea.
</p>
</div>
<div id="content">
<!--<div id="zero"><p>Zero</p></div>-->
<div id="one"><h1>Objective</h1><p>Lorem ipsum dolor sit amet, et mel falli simul platonem, cu consul utroque neglegentur duo.</p><h1>Delivery</h1><p>Sit te habeo neglegentur, nam no dicit intellegat. </p><h1>Performance</h1><p>Pri nihil scaevola salutatus id, esse minimum vis ne. Verear corrumpit vim ex, vim tollit scaevola ea, est id suas delectus deseruisse.</p></div>
<div id="two"><p>Two</p></div>
<div id="three"><p>Three</p></div>
<div id="four"><p>Four</p></div>
<div id="five"><p>Five</p></div>
<div id="six"><p>Six</p></div>
</div>
<ul id="nav">
<!--<li><img src="http://dev3.stellaworld.co.uk/public_html/development/ssl/website/level3/itservices/images/0.jpg">
</li>-->
<li><img src="http://dev3.stellaworld.co.uk/public_html/development/ssl/website/level3/itservices/images/1.jpg">
</li>
<li><img src="http://dev3.stellaworld.co.uk/public_html/development/ssl/website/level3/itservices/images/2.jpg">
</li>
<li><img src="http://dev3.stellaworld.co.uk/public_html/development/ssl/website/level3/itservices/images/3.jpg">
</li>
<li><img src="http://dev3.stellaworld.co.uk/public_html/development/ssl/website/level3/itservices/images/4.jpg">
</li>
<li><img src="http://dev3.stellaworld.co.uk/public_html/development/ssl/website/level3/itservices/images/5.jpg">
</li>
<li><img src="http://dev3.stellaworld.co.uk/public_html/development/ssl/website/level3/itservices/images/6.jpg">
</li>
</ul>
</div>
CSS...
#container {
height:390px;
overflow:hidden;
float:left;
background: #ccc no-repeat;
min-width:918px;
padding: 10px 10px 10px 10px;
}
#services_level2 {
position:fixed;
background:white;
padding:20px;
height: 345px;
}
#content {
width: 650px;
height: 385px;
position: relative;
overflow: hidden;
float: right;
}
#content > div {
display:block;
width:600px;
height:385px;
background:white;
position:absolute;
margin-left:100%;
/*left:-200px;*/
opacity: 0;
padding:10px 20px 0 40px;
}
#nav {
list-style: none;
display: table;
margin: 0px 0 0 0;
position: relative;
width: 260px;
float:right;
}
#nav li {
/* width: 100px; */
/* height: 100px; */
float: left;
margin-right:5px;
/*border: 1px solid black;*/
}
#nav a {
color:#fff;
text-decoration:none;
width:100%;
height:100%;
}
ul {
padding:0;
}
li.active {
opacity:0.4;
filter:alpha(opacity=40);
}
You need to comb your code and make a list off all the values that change on the first click, then when #reset is clicked reverse each value. -=200px will become +=200px and so on.
I found a solution to this (JSFiddle) by adding a button and assigning a click function to it which has 3 actions:
Slide out and fade level2 copy. This forces the thumbnails to move
slide in and fade in level1 copy
deletes the active thumbnail class
Button Code:
$('#moveleft').click(function() {
count = 0;
// Slide Level 2 description back into view
$('#services_level2').animate({
'margin-left': '0%',
'opacity' : "1"
}, 800);
// Slide Level 3 out of view. The thumbnails follow Level 3.
$(level3_content).animate({
'width': '0px',
opacity: 1
}, 400);
// Delete the active class
var oldClickedElement = $('.active').removeClass('active').find('a').attr('href');
console.log(oldClickedElement);
//only if old click element exists the do the animation
if (oldClickedElement) {
//animate out + reset to start
$(oldClickedElement).animate({
left: 0,
'margin-left': '-50%',
opacity: 0
}, 500, function() {
$(oldClickedElement).css({
'margin-left' : '100%',
left: 0
});
});
}
});
Here is the JSFiddle http://jsfiddle.net/warmwhisky/N68wX/24/
It is rather a nice slider with two levels. Unfortunately it is not responsive yet.