creating multiple vertical lines in HTML using loops - javascript

I'm new to JS and would like to create 10 vertical lines in my webpage. I have written my HTML code as
<div id="verticle-line"></div>
and in my CSS I have
#verticle-line {
width: 1px;
min-height: 400px;
background: red;
margin:15px;
float:left
}
How Can I create 10 such lines in my webpage using JavaScript?

There are many ways to do this but the easiest would probably be this:
for(var i=0; i<10; i++) {
document.write('<div class="verticle-line"></div>');
}
Use a for loop to write 10 divs on your page. I also changed id to class, because you should not have more than one element with the same id on your page. Make sure you change your CSS to match a class.

See this -
for(x=0; x<9;x++) {
var vertical = document.createElement('div');
vertical.className = "verticle-line";
document.getElementById('wrapper').appendChild(vertical);
}
.verticle-line {
width: 1px;
min-height: 400px;
background: red;
margin: 15px;
float: left
}
<div id="wrapper">
<div class="verticle-line"></div>
</div>

Related

Inconsistent behavior of inline-block elements when created via JavaScript

I have a bunch of the same divs whose display property is set to inline-block. I know that inline-block elements have, by default, some margin around them so without any modification, I would expect some free space surrounding these elements (this question is not about removing them).
If I simply hard-code them into html file, then they behave as I expect them to.
* {
margin: 0;
padding: 0;
}
div.box {
width: 100px;
height: 40px;
background: red;
display: inline-block;
}
<div tabindex="1" class='box'></div>
<div class='box'></div>
<div class='box'></div>
But if I start adding them via JavaScript, the top and bottom margins stays the same, but left and right seems to disappear.
In this code, if I tab into the first element and then hit enter, the new div is created and added into DOM but as mentioned above, margins are gone when I start adding more of them (hitting enter multiple times).
const btn = document.querySelector('div.box');
btn.addEventListener('keypress', event => {
if (event.key === 'Enter') {
const box = document.createElement('div');
box.className = 'box';
document.body.appendChild(box);
}
});
* {
margin: 0;
padding: 0;
}
div.box {
width: 100px;
height: 40px;
background: red;
display: inline-block;
}
<div tabindex="1" class='box'></div>
Anyone knows why there is a difference in how these divs are rendered when hard-coded vs added programmatically? Is there something wrong with the JavaScript code?
You're confusing white space with margins. Inline elements are sensitive to white space in your code, so when you generate them via JS, that whitespace doesn't exist unless you manually add it. The easiest way to see this is in your first example by putting all your divs on the same line with no spaces or carriage returns.
* {
margin: 0;
padding: 0;
}
div.box {
width: 100px;
height: 40px;
background: red;
display: inline-block;
}
<div tabindex="1" class='box'></div><div class='box'></div><div class='box'></div>

Vertical gaps between inline-block elements for big amounts of elements

I am currently doing the JS/jQuery Project for The Odin Project and i think my solution is performing really well.
The problem i have with it tho, is that for bigger amounts of elements (in JSFiddle it starts to break around 40-45 elements per line, in my Chrome Browser around 50-52), there will be a vertical gap between the elements of two adjacent rows. I initially set vertical-align: top to remove the gaps, which works up to the mentioned 40-50 elements per row.
Here is the JSFiddle.
If you raise the amount of elements per row in the JS file (set it to 50 or higher), you will see what i mean.
This is not the behavior i am looking for. I want a connected grid with no gaps between the cells on either side. Any idea what breaks the vertical-align: top?
Edit: I think it has to do with the percentage-width/height, as it also breaks on numbers below 40, if the result of the division is a "difficult fraction".
Inline boxes inherit inheritable properties from their block parent box. therefore your grids are taking line-height of .container. When .container is overflowed vertical-align: top; stops working, so it's better to use line-height:0; to parent element (.container).
Source: https://www.w3.org/TR/CSS2/visuren.html#inline-boxes
$(document).ready(function() {
createGrid(48);
$(".cell").mouseenter(function() {
$(this).css("background-color", "green");
});
$(".cell").mouseleave(function() {
$(this).css("background-color", "white");
});
});
function createGrid(n) {
var container = $(".container");
container.empty();
var sizeP = 100 / n;
var cell = $('<div/>', {
class: 'cell',
style: 'width: ' + sizeP + '%; height: ' + sizeP + '%;'
});
for(i = 0; i < n*n; i++) {
container.append(cell.clone());
}
}
.container {
border: 5px solid black;
border-radius: 5px;
padding: 10px;
margin: 10px;
width: 800px;
height: 800px;
line-height:0;
}
.cell {
display: inline-block;
box-sizing: border-box;
border: 1px solid black;
vertical-align: top;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<body>
<div class="container"></div>
</body>

How to make nested divs resize based on user input

I am doing a project from The Odin Project. Basically this.
Here is the code:
HTML
<!DOCTYPE html>
<html>
<head>
<script src="js/jQuery.js"></script>
<link type="text/css" rel="stylesheet" href="css/sketch.css">
<script src="js/sketch.js"></script>
</head>
<body>
<div class="grid_controls">
<button class="clear">Clear</button>
</div>
<div class="container">
</div>
</body>
</html>
CSS
/*=================
General
=================*/
body {
background: aqua;
}
/*=================
Sketchpad Holder
=================*/
.container {
width: 500px;
height: 400px;
background-color: orange;
overflow: hidden;
margin: auto;
position: relative;
top: 20px;
}
.box {
width: 16px;
height: 16px;
background: yellow;
display: inline-block;
margin: 1px 1px 1px 1px;
left: 0.5%;
right: auto;
position: relative;
}
.clear {
position: relative;
margin: auto;
text-align: center;
}
Javascript/Jquery
var default_grid_num = 435;
var div_limit = prompt("How large would you like your grid to be?");
var button_prompt = "Would you like to redraw the grids?";
/*var div_limit = prompt("number")*/
$(document).ready(function() {
for(var i = 1; i <= div_limit; i++)
$(".container").append("<div class='box'></div>");
$(".container > div").hover(function() {
$(this).css("background-color", "red");
});
$("button").click(function() {
$(".box").fadeOut();
if(confirm("Would you like to redraw the grid?"));
{
boxes_per_row = prompt("Define width of grid.");
}
});
});
What I want to do is get user input(.div_limit) and resize the divs(.box) based on the users input(.div_limit) So if the user only typed in the number one, the one div would take up the whole container box.
Here is what I have so far: http://codepen.io/zappdapper/full/epdPKb/
I know I can do this, but how?
I've made a jsfiddle that uses the mod operator % and some math to determine a percentage for the boxes.
I've included max_per_row as well to determine how many should show in a row.
UPDATE
I've taken another look at your example and your comment and come up with this:
http://jsfiddle.net/xw4cbo5n/
I edited the example slightly so that instead of asking two questions, only one is asked: "How many boxes per row of grid" (this is similar to your example).
It then goes on to draw out a grid where each row contains that number and sets each bow width and height accordingly. I also edited your CSS styles slightly.
Is that closer to what you're looking for?
I've created a JSFiddle which displays two prompts when run:
1) How many boxes would you like?
2) How many boxes should take up one row?
http://jsfiddle.net/5vg6n232/
After the responses are given, the grid is drawn.
I've edited your CSS slightly but the main functionality is driven by a couple of functions:
function drawBoxes(){
takes care of adding the correct number on divs to the page. After this is done it calls:
function restyle(numberofBoxesPerRow){
which simply reset's the CSS width of each box based on how may boxes per row the user specified.
Does this answer your question?

Javascript show hide css/html/js problem

Some code when I call a showhide method in html is not working correctly. The method shows then hides some html content on this webpage, however, the html or css is not functioning correctly. For example, when the page is loaded in a browser, the space where the div will be shown is just empty space, when there shouldn't be space at all, but when the div is shown it just fills that space. The I think it could be something to do with the css, however I am not to sure. Here is the CSS id I am using to show and hide.
#showAndHide {
text-align: justify;
height: auto;
width: 700px;
margin: auto;
position: relative;
padding-top: 10px;
padding-bottom: 10px;
padding-left: 20px;
padding-right: 10px;
visibility: hidden;
}
and here is a small sample of the html that this is being applied to.
<div id="showAndHide">
<div id="physicalAdress">
<div class="h4">
<h4> What is your physical address? </h4>
</div>
<p> Property name (if you have one) </p>
<input type="text" name="propertyName" /><br/>
that html is within the showandhide div, then within a user input div which is:
.userinput {
text-align: justify;
height: auto;
width: 700px;
margin: auto;
position: relative;
border-collapse: collapse;
padding-top: 10px;
padding-bottom: 10px;
padding-left: 20px;
padding-right: 10px;
border-right-style: solid;
border-left-style: solid;
}
here is the Javascript method.
function showHideDiv()
{
var divstyle = new String();
divstyle = document.getElementById("showAndHide").style.visibility;
if(document.getElementById("yesPrint").checked == true)
{
document.getElementById("showAndHide").style.visibility = "visible";
}
if(document.getElementById("noPrint").checked == true)
{
document.getElementById("showAndHide").style.visibility = "hidden";
}
}
Basically when I run the page, and show the content the styling is becoming skewed and the positioning of the html that is not with the show and hide content is also becoming skewed.
Any ideas/help would be appreciated.
use display:none instead of visibility: hidden;.
visibility: hidden; reserves space for element
Change visibility:hidden to display:none to prevent the element from taking up space when hidden.
You may need to change your JavaScript slightly, but I can't say for sure as you haven't posted it, but you're going to need something like this:
element.style.display = "block"; //Show the element
function toggle_show(id) {
var el = document.getElementById(id);
if (el && el.style) {
el.style.display = el.style.display == 'none' ? 'block' : 'none';
}
}
http://webdesign.about.com/od/css/f/blfaqhidden.htm
Quoting webdesign:
"visibility: hidden hides the element, but it still takes up space in the layout.
display: none removes the element completely from the document. It does not take up any space, even though the HTML for it is still in the source code."

How do I achieve equal height divs (positioned side by side) with HTML / CSS ?

I have two divs inside of a container. One on the left, one on the right, side by side. How am I able to make each one be of equal height, even though they have different content.
For example, the right div has a lot of content, and is double the height of the left div, how do I make the left div stretch to the same height of the right div?
Is there some JavaScript (jQuery) code to accomplish this?
You could use jQuery, but there are better ways to do this.
This sort of question comes up a lot and there are generally 3 answers...
1. Use CSS
This is the 'best' way to do it, as it is the most semantically pure approach (without resorting to JS, which has its own problems). The best way is to use the display: table-cell and related values. You could also try using the faux background technique (which you can do with CSS3 gradients).
2. Use Tables
This seems to work great, but at the expense of having an unsemantic layout. You'll also cause a stir with purists. I have all but avoided using tables, and you should too.
3. Use jQuery / JavaScript
This benefits in having the most semantic markup, except with JS disabled, you will not get the effect you desire.
Here's a way to do it with pure CSS, however, as you'll notice in the example (which works in IE 7 and Firefox), borders can be difficult - but they aren't impossible, so it all depends what you want to do. This example assumes a rather common CSS structure of body > wrapper > content container > column 1 and column 2.
The key is the bottom margin and its canceling padding.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Equal Height Columns</title>
<style type="text/css">
<!--
* { padding: 0; margin: 0; }
#wrapper { margin: 10px auto; width: 600px; }
#wrapper #main_container { width: 590px; padding: 10px 0px 10px 10px; background: #CCC; overflow: hidden; border-bottom: 10px solid #CCC; }
#wrapper #main_container div { float: left; width: 263px; background: #999; padding: 10px; margin-right: 10px; border: 1px solid #000; margin-bottom: -1000px; padding-bottom: 1000px; }
#wrapper #main_container #right_column { background: #FFF; }
-->
</style>
</head>
<body>
<div id="wrapper">
<div id="main_container">
<div id="left_column">
<p>I have two divs inside of a container. One on the left, one on the right, side by side. How am I able to make each one be of equal height, even though they have different content.</p>
</div><!-- LEFT COLUMN -->
<div id="right_column">
<p>I have two divs inside of a container. One on the left, one on the right, side by side. How am I able to make each one be of equal height, even though they have different content.</p>
<p> </p>
<p>For example, the right div has a lot of content, and is double the height of the left div, how do I make the left div stretch to the same height of the right div?</p>
<p> </p>
<p>Is there some JavaScript (jQuery) code to accomplish this?</p>
</div><!-- RIGHT COLUMN -->
</div><!-- MAIN CONTAINER -->
</div><!-- WRAPPER -->
</body>
</html>
This is what it looks like:
you can get it working with js:
<script>
$(document).ready(function() {
var height = Math.max($("#left").height(), $("#right").height());
$("#left").height(height);
$("#right").height(height);
});
</script>
I've seen many attempts to do this, though none met my OCD needs. You might need to dedicate a second to get your head around this, though it is better than using JavaScript.
Known downsides:
Does not support multiple element rows in case of a container with dynamic width.
Does not work in IE6.
The base:
red is (auxiliary) container that you would use to set margin to the content.
green is position: relative; overflow: hidden and (optionally, if you want columns to be centered) text-align: center; font-size: 0; line-height: 0;
blue display: block; float: left; or (optionally, if you want columns to be centered) display: inline-block; vertical-align: top;
So far nothing out of ordinary. Whatever content that blue element has, you need to add an absolutely positioned element (yellow; note that the z-index of this element must be lower than the actual content of the blue box) with this element and set top: 0; bottom: 0; (don't set left or right position).
All your elements now have equal height. For most of the layouts, this is already sufficient. My scenario required to have dynamic content followed by a static content, where static content must be on the same line.
To achieve this, you need to add padding-bottom (dark green) eq to the fixed height content to the blue elements.
Then within the yellow elements create another absolutely positioned (left: 0; bottom: 0;) element (dark blue).
Supposedly, if these boxes (yellow) had to be active hyperlinks and you had any style that you wanted to apply to the original blue boxes, you'd use adjacent sibling selector:
yellow:hover + blue {}
Here is a the code and demo:
HTML:
<div id="products">
<ul>
<li class="product a">
<a href="">
<p class="name">Ordinary product description.</p>
<div class="icon-product"></div>
</a>
<p class="name">Ordinary product description.</p>
</li>
<li class="product b">
<a href="">
<p class="name">That lenghty product description or whatever else that does not allow you have fixed height for these elements.</p>
<div class="icon-product"></div>
</a>
<p class="name">That lenghty product description or whatever else that does not allow you have fixed height for these elements.</p>
</li>
<li class="product c">
<a href="">
<p class="name">Another ordinary product description.</p>
<div class="icon-product"></div>
</a>
<p class="name">Another ordinary product description.</p>
</li>
</ul>
</div>
SCSS/LESS:
#products {
ul { position: relative; overflow: hidden; text-align: center; font-size: 0; line-height: 0; padding: 0; margin: 0;
li { display: inline-block; vertical-align: top; width: 130px; padding: 0 0 130px 0; margin: 0; }
}
li {
a { display: block; position: absolute; width: 130px; background: rgba(255,0,0,.5); z-index: 3; top: 0; bottom: 0;
.icon-product { background: #ccc; width: 90px; height: 90px; position: absolute; left: 20px; bottom: 20px; }
.name { opacity: 1; }
}
.name { position: relative; margin: 20px 10px 0; font-size: 14px; line-height: 18px; opacity: 0; }
a:hover {
background: #ddd; text-decoration: none;
.icon-product { background: #333; }
}
}
}
Note, that the demo is using a workaround that involves data-duplication to fix z-index. Alternatively, you could use pointer-events: none and whatever solution for IE.
here is very simple solution with a short css display:table
<div id="main" class="_dt-no-rows">
<div id="aside" contenteditable="true">
Aside
<br>
Here's the aside content
</div>
<div id="content" contenteditable="true">
Content
<br>
geht's pellentesque wurscht elementum semper tellus s'guelt Pfourtz !. gal hopla
<br>
TIP : Just clic on this block to add/remove some text
</div>
</div>
here is css
#main {
display: table;
width: 100%;
}
#aside, #content {
display: table-cell;
padding: 5px;
}
#aside {
background: none repeat scroll 0 0 #333333;
width: 250px;
}
#content {
background: none repeat scroll 0 0 #E69B00;
}
its look like this
Well, I don't do a ton of jQuery, but in the CSS/Javascript world I would just use the object model and write a statement as follows:
if(leftDiv.style.height > rightDive.style.height)
rightDiv.style.height = leftDiv.style.height;
else
leftDiv.style.height = rightDiv.style.height)
There's also a jQuery plugin called equalHeights that I've used with some success.
I'm not sure if the one I'm using is the one from the filament group mentioned above, or if it's this one that was the first google result... Either way a jquery plugin is probably the easiest, most flexible way to go.
Use this in jquery document ready function. Considering there are two divs having ids "left" and "right."
var heightR = $("#right").height();
var heightL = $("#left").height();
if(heightL > heightR){
$("#right").css({ height: heightL});
} else {
$("#left").css({ height: heightR});
}
Although many disagree with using javascript for this type of thing, here is a method that I used to acheive this using javascript alone:
var rightHeight = document.getElementById('right').clientHeight;
var leftHeight = document.getElementById('left').clientHeight;
if (leftHeight > rightHeight) {
document.getElementById('right').style.height=leftHeight+'px';
} else {
document.getElementById('left').style.height=rightHeight+'px';
}
With "left" and "right" being the id's of the two div tags.
This is what I use in plain javascript:
Seems long, but is very uncomplicated!
function equalizeHeights(elements){
//elements as array of elements (obtain like this: [document.getElementById("domElementId"),document.getElementById("anotherDomElementId")]
var heights = [];
for (var i=0;i<elements.length;i++){
heights.push(getElementHeight(elements[i],true));
}
var maxHeight = heights[biggestElementIndex(heights)];
for (var i=0;i<elements.length;i++){
setElementHeight(elements[i],maxHeight,true);
}
}
function getElementHeight(element, isTotalHeight){
// isTotalHeight triggers offsetHeight
//The offsetHeight property is similar to the clientHeight property, but it returns the height including the padding, scrollBar and the border.
//http://stackoverflow.com/questions/15615552/get-div-height-with-plain-javascript
{
isTotalHeight = typeof isTotalHeight !== 'undefined' ? isTotalHeight : true;
}
if (isTotalHeight){
return element.offsetHeight;
}else{
return element.clientHeight;
}
}
function setElementHeight(element,pixelHeight, setAsMinimumHeight){
//setAsMinimumHeight: is set, we define the minimum height, so it can still become higher if things change...
{
setAsMinimumHeight = typeof setAsMinimumHeight !== 'undefined' ? setAsMinimumHeight : false;
}
var heightStr = "" + pixelHeight + "px";
if (setAsMinimumHeight){
element.style.minHeight = heightStr; // pixels
}else{
element.style.height = heightStr; // pixels
}
}
function biggestElementIndex(arr){
//http://stackoverflow.com/questions/11301438/return-index-of-greatest-value-in-an-array
var max = arr[0];
var maxIndex = 0;
for (var i = 1; i < arr.length; i++) {
if (arr[i] > max) {
maxIndex = i;
max = arr[i];
}
}
return maxIndex;
}
I agree with initial answer but the JS solution with equal_heights() method does not work in some situations, imagine you have products next to each other. If you were to apply it only to the parent container yes they will be same height but the product name sections might differ if one does not fit to two line, this is where i would suggest using below
https://jsfiddle.net/0hdtLfy5/3/
function make_children_same_height(element_parent, child_elements) {
for (i = 0; i < child_elements.length; i++) {
var tallest = 0;
var an_element = child_elements[i];
$(element_parent).children(an_element).each(function() {
// using outer height since that includes the border and padding
if(tallest < $(this).outerHeight() ){
tallest = $(this).outerHeight();
}
});
tallest = tallest+1; // some weird shit going on with half a pixel or something in FF and IE9, no time to figure out now, sowwy, hence adding 1 px
$(element_parent).children(an_element).each(function() {
$(this).css('min-height',tallest+'px');
});
}
}

Categories

Resources