Setting min-height automatically with jQuery or Javascript - javascript

I would like to use a script to add min-height or max-height to an element based on the height of the actual element.
So I'm getting the .height() (?) of a div and then using that value to set a min/max-height. Is this possible? It has to be dynamical, so that the div can change height but still have the right min-height or max-height.
I haven't tried anything, only searched for how to do it - I'm really not an expert on jQuery og Javascript. The thing I'm doing now is using console.log to give me the height of an element (a hero section for example) so that I don't need to manually check it in developer. And then I write the value as a min-height in CSS. The reason I'm doing it is because of the new Lighthouse Core Web Vitals (Cumulative Layout Shift (CLS)).
EDIT: So I think I found a solution, and (like I said) I'm not an expert here, but any feedback is very much appreciated.
jQuery(".hero").css("min-height", function(){
return jQuery(".hero").height();
});

this is an example of what you want
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Set a DIV height</title>
<style>
.box{
background: #f2f2f2;
border: 1px solid #ccc;
}
</style>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script>
$(document).ready(function(){
var newHeight = $(".input-height").val();
$(".box").height(newHeight);
});
</script>
</head>
<body>
<form>
<input type="text" class="input-height">
<button type="button" class="set-height-btn">Set Height</button>
<p>Enter the value in input box either as number (e.g. 100, 200) or combination of number and unit (e.g. 100%, 200px, 50em, auto) and click the "Set Height" button.</p>
</form>
<br>
<div class="box">This is simple DIV box</div>
</body>
</html>

Related

How to pass a css value from one html page to another using javascript?

I am trying to pass a circle made with CSS from one HTML page to another. First the circle is green. After clicking a button the circle becomes red. I want the same green circle of the other html page to becomes red like in the first page.
Here is the code of the first HTML page:
<!DOCTYPE html>
<html>
<head>
<meta charset= "utf-8">
<style>
#first{
height:20px;width:20px;
border-radius:50%;
border-width: 5px;
background-color: green;
}
</style>
<script>
function passvalues(){
const first=document.getElementById("first");
localStorage.setItem("firstvalues",first);
return false;
}
</script>
</head>
<body>
<div id="first"></div>
<input type="button" value="click here" onclick="doSomeThing()">
<script>
function doSomeThing(){
document.getElementById("first").style.backgroundColor='red';
}
</script>
<form action="second-page.html">
<input type="submit" value="Click" onclick="passvalues()"/>
</form>
</body>
That's the code of the second HTML page (Second-page.html):
<!DOCTYPE html>
<html>
<head>
<meta charset= "utf-8">
<style>
#first{
height:20px;width:20px;
border-radius:50%;
border-width: 5px;
background-color: green;
}
</style>
</head>
<body>
<div id="first"></div>
<span id="first"></span>
<script>
document.getElementById("first").innerHTML=localStorage.getItem("firstvalues");
</script>
</body>
</html>
When I run this code I get on the second page a green circle and [object HTMLDivElement] inside of it. I think something is wrong with the function innerHTML.
You can avoid to use JavaScript including one single class in your index.css that use :active to change the color of the circle when clicked.
That's a simple example that you can arrange to your needs:
<html>
<body>
<button class="btn">Click me</button>
<style>
.btn{
background:black;
color:white;
border:0;
margin:1rem;
}
.btn:active{
background:red;
}
</style>
</body>
</html>
One good idea is to activate the styling after a button is clicked with JavaScript so you don't have to pass the function to the other page, instead you can activate this class with onother button placed on second page.
In this example I've changed the background of the button,
instead of changing button's style you can apply the class directly to the circle.
I hope this answer is usefull for you, if not, please tell me I would give you mnore help!
Your best.
What you are trying to store here is the div as an object.
Instead try storing the Html itself of that div. Use:
localStorage.setItem("firstvalues", first.outerHTML)
Note:
Ids should be unique to the page. When you put the content of the first page's #first in the second page's #first, you create two elements of the same id. Have different ids in both to avoid conflicts.
You are submitting a form to another page. So why not use the standard method of passing data in a GET parameter?

Repeatedly Toggle Div Background Color On Click Using Inline Vanilla JavaScript on a Webpage

*To the reader looking from help: Each of the first 4 solutions worked for me, and the suggested question shows potential. I picked Hunsnul Amand's code because it allows for easy expansion of colors in a JavaScript string, and toggles through all three colors mentioned in the problem below. I like the way this sets up the possibility of additional or random colors later. The other three solutions on this page rely on various snippets of JavaScript toggling between additional classes made in CSS. Ranjeep and Keith's snippets use this in very simple and clean code that's easy to follow. Jateen makes use of the .toggle and ++> elements, which are useful as well. His code was also easy to follow. *
Thank You for checking this out. I'm trying to do something that seems like a very basic skill, but am having trouble finding the specific syntax or code that will cause a webpage to repeatedly toggle the background color of a circular div on a click rather than on a button using Vanilla JavaScript. I've tried too many iterations to post here, and received various effects from trying to modify similar projects to my needs, but haven't been able to get the div's background color to toggle.
background: I started with a sample project that lets you cause a div shaped in a circle with a red background to disappear by setting the background color to "none." I'd like to change the code to something that will instead allow a repeated toggle of the circular div's background color between either red to blue, or at least from red to none and back again.
<!-- This document should let you toggle a circle's color between
red and blue using vanilla JavaScript, HTML, and CSS.
The circle is an HTML div shaped and colored in CSS,
and given the toggle function that changes the div's color
in JavaScript.
Biggest need: A JavaScript toggle funciton that alternates
the color of a div when the user clicks on the div.-->
Mini Challenge: Disappearing Circles
minichallenge.html!
<!doctype html>
<html>
<head>
<title>Learning Javascript</title>
<meta charset="utf-8" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style>
#circle {
width:200px;
height:200px;
border-radius:100px;
background-color:red;
}
</style>
</head>
<body>
<div id="circle"></div>
<script type="text/javascript">
/*original JavaScript Project*/
document.getElementById("circle").onclick=function() {
document.getElementById("circle").style.display="none";
}
/* New JS: Purpose: A JavaScript toggle funciton that alternates
the color of a div when the user clicks on the div.-
var userClick = document.getElementById("circle").onclick=function() {
var noDiv = document.getElementById("circle").style.display="blue";
var redDiv = document.getElementById("circle").style.display="red";
-Pseudocode-:
if userClick
noDiv
else redDiv; */
</script>
</body>
</html>
Thanks Again.
Here is one of many solutions. In your script try this.
let i = 0;
const colors = ["blue", "red", "transparent"];
document.getElementById("circle").onclick = function () {
document.getElementById("circle").style.backgroundColor = colors[i];
i++;
if (i == colors.length) i = 0;
};
This way you can add as many colors as want to the colors array and it will work.
You can create a .bg-none class in you css. Then toggle that class onclick of the element. I have updated the code, please chekc
<style>
.bg-none{
background-color: transparent !important;
}
</style>
<script>
document.getElementById("circle").onclick=function() {
document.getElementById("circle").classList.toggle("bg-none");
}
</script>
Using CSS here, and the classList toggle method is the simplest way.
eg.
document.getElementById("circle").onclick=function() {
document.getElementById("circle").classList.toggle('toggle');
}
#circle {
width:200px;
height:200px;
border-radius:100px;
background-color:red;
}
#circle.toggle {
background-color:blue;
}
<div id="circle"></div>
I have moved your background-color CSS to 2 new classes, which would toggle as you click on the div. I hope this resolved your query.
<!doctype html>
<html>
<head>
<title>Learning Javascript</title>
<meta charset="utf-8" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style>
#circle {
width:200px;
height:200px;
border-radius:100px;
}
.bg-red {
background-color: red;
}
.bg-blue {
background-color: blue;
}
</style>
</head>
<body>
<div id="circle" class="bg-red"></div>
<script type="text/javascript">
const circleDiv = document.getElementById("circle");
circleDiv.addEventListener('click', () => {
circleDiv.classList.toggle('bg-red');
circleDiv.classList.toggle('bg-blue');
});
</script>
</body>
</html>

jqLite: elm.css("width") is returning an empty string

This appears to be an issue with jqLite, which I came across while working with angular.js. To see the problem, open the console tab and click "run with js" in this jsbin. left.css("width") is returning an empty string when it shouldn't be.
HTML
<!doctype html>
<html ng-app>
<head>
<meta name="description" content="Angular Template" />
<script src="http://code.angularjs.org/1.0.6/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<div class="container">
<div class="left"><span id="test">left</span></div>
<div class="right">right</div>
</div>
</body>
</html>
CSS
.container {display:table; width:100%;}
.left {border: 1px dashed purple; display:table-cell; overflow:hidden; width: 66%; height: 20px;}
.right {display:table-cell; background:green; width: 34%; height: 20px;}
JS
var innerSpan = document.getElementById("test");
var left = angular.element(innerSpan);
console.log(left.css("width"));
When I inspect the element using the chrome dev tools panel, the computed width is definitely not the empty string? What am I missing here?
You can't use .css('width') to get the width of an element. You use it to get the styled width. Since you didn't define the width in the element's style attribute, you get no value.
Try .prop('offsetWidth') instead.
Also, when using jsbin.com, your script is automatically included. Including script.js is just throwing a 404.

Changing background position with Javascript?

Though I can see this question has been asked before I really need a solution without the use of JQuery, its for an embedded web interface and I don't want the overhead of loading jQuery. I need to be able to manipulate sprites using just the JS on the single page, the state of the sprite is dependent on certain JS variables. I'm sure this must be possible, but can't find anything without the use of JQuery.
The easiest way (I think) is to define your own css classes and change those clasess on certan events. i.e.
<style type="text/css">
.bg1{
/* Some attributes set here */
background-position:cen‌​ter;
}
.bg2{
/* Some attributes set here */
background-position:left;
}
</style>
and then you put your javascript like this
document.getElementById("some_id").class = "bg2";
I think you can use Object.style.backgroundPosition="position" to change your desired background position .
Try this code
<!DOCTYPE html>
<html>
<head>
<style>
div
{
background-image: url('example.png');
background-repeat: no-repeat;
width: 400px;
height: 400px;
border: 1px solid #000000;
}
</style>
<script>
function displayResult()
{
document.getElementById("div1").style.backgroundPosition="center bottom";
}
</script>
</head>
<body>
<button type="button" onclick="displayResult()">Position background image</button>
<br>
<div id="div1">
</div>
</body>
</html>
Reference

Javascript Target link state

I've got a bit of javascript that toggles two divs with two separate links, I wanted to add a little image next to the selected link say for instance if you select div 1 to be viewed the link would have a litle bullet next to it and if you select div 2 the div 2 would have a bullet on it. Heres the script can anyone help please :)
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<style type='text/css'>
</style>
<script type='text/javascript' src='http://code.jquery.com/jquery-1.6.2.js'></script>
<script type='text/javascript'>//<![CDATA[
$(window).load(function(){
$(function(){
$('a[id^="link"]').click(function(){
var vid_id = $(this).attr("id").replace("link", "#testVid");
$('div[id^="testVid"]').hide();
$(vid_id).show();
});
$('span[id^="close"]').click(function(){
var vid_id = $(this).attr("id").replace("close", "#testVid");
$(vid_id).hide();
});
});
});//]]>
</script>
</head>
<body>
<div>
Click Link 1<br />
Click Link 2<br />
<div id="testVid1" style="background:pink; height:300px">Test Vid Div 1<br /><br /><span id="close1">CLOSE 1</span></div>
<div id="testVid2" style="display:none;background:pink; height:300px">Test Vid Div 2<br /><br /><span id="close2">CLOSE 2</span></div>
</div>
</body>
</html>
You can do this in various ways. I can think of three off the top of my head, and I'm sure there are more.
Background images and padding
content:before
Altering the DOM dynamically (not recommended)
The idea in #1 and #2 is to change the CSS style of the selected element. For #1, you would define styles something like this:
.selected {
background-image: url(myselectedimage.png);
background-repeat: no-repeat;
background-position: left center;
padding-left: 20px; /* or whatever the size of your image is */
}
For #2, you would use the following:
.selected:before {
content: "\u2219"; /* bullet */
}
Then, you can do something like this to remove the .selected class from everything, and add it to the selected link, when a link is clicked:
$('a[id^="link"]').click(function(e){
$('a[id^="link"]').removeClass('selected');
$(e.currentTarget).addClass('selected');
...
});
$('span[id^="close"]').click(function(){
$('a[id^="link"]').removeClass('selected');
...
});
The advantage to approach #1 is that almost all modern browsers support it without trouble. The advantage to #2 is that it's more flexible -- you can add text, images, attributes, all kinds of things, but be warned that browser support can be inconsistent. Since you're already using CSS3 selectors (^=), you're probably OK. See CSS Tricks for more info.
Approach #3 involves inserting and removing HTML from before the link. It's possible, but clunky. It's how we used to do things before CSS2 and 3 came along. :) I wouldn't recommend it, but occasionally it's the only way to get things done in a reliably cross-browser fashion (probably not in this case). In order to do that, insert a <span> tag before each link, with an ID that is computable from the link ID (or you could use CSS selectors to find the sibling). Then use JQuery's .html() method to insert HTML into it, e.g.:
<span id="bullet-link1"></span>Click Link 1<br />
...
<script lang="text/javascript">
$('a[id^="link"]').click(function(e) {
$('span[id^="bullet-"]').html('');
$('#bullet-' + e.currentTarget.id).html('•');
...
});
</script>

Categories