How to use GETELEMENT with an specific position - javascript

I have seen this code ( http://jsfiddle.net/eMNfd/21/ ), but I want to know how to make the new div can be created to the right of the blue, that is, in horizontal mode.
document.getElementById("text").onclick = function () {
var ok = true;
if (ok === true) {
var div = document.createElement('div');
div.className = 'new-rect';
//div.style.backgroundColor = "black";
document.getElementsByTagName('body')[0].appendChild(div);
}
};
.new-rect {
background: black;
width: 20%;
height: 30px;
}
<div id="text" style="width:20%;height:30px;background-color:blue;"></div>
Thanks to all.

You can use float for this (has to be set on all divs to work), you can also use inline-block:
document.getElementById("text").onclick = function () {
var ok = true;
if (ok === true) {
var div = document.createElement('div');
div.className = 'new-rect';
//div.style.backgroundColor = "black";
document.getElementsByTagName('body')[0].appendChild(div);
}
};
body {
font-size: 0; /* to get rid of the space between the divs */
white-space: nowrap; /* to prevent wrapping on multiple lines */
}
div {
display: inline-block; /* to add divs horizontally */
}
.new-rect {
background: black;
width: 20%;
height: 30px;
}
<div id="text" style="width:20%;height:30px;background-color:blue;"></div>

Related

'backgroundColor' not working with javascript

I'm creating a tab menu like this:
function clear_selected() //sets all columns color black
{
var parent = document.querySelector("#container")
var items = document.querySelectorAll(".item")
var n = items.length;
for (var i = 0; i < n; i++)
items[i].style.backgroundColor = "";
}
function plus(itself) //adds another column
{
var parent = itself.parentElement;
var n = parent.childElementCount;
clear_selected();
var n = parent.querySelectorAll(".item").length;
var page = document.createElement("button");
page.className = "item";
page.style.backgroundColor = "blue";
page.textContent = "column"
page.onclick = function() {
clear_selected();
this.style.backgroundColor = "blue";
};
var temp = document.createElement("span");
temp.className = "del"
temp.innerHTML = "×"
temp.onclick = function() { //it's suppose to remove a column and color default as blue
document.querySelector("#main_item").style.backgroundColor = "blue" //THIS LINE ISN'T WORKING
this.parentElement.remove();
};
page.appendChild(temp);
parent.insertBefore(page, parent.childNodes[n]);
}
function see(el) {
clear_selected();
el.style.backgroundColor = "blue";
}
#container {
display: flex;
width: 100%;
height: 50px;
text-align: center;
background-color: yellow;
}
.item {
background-color: black;
color: white;
border: none;
outline: none;
cursor: pointer;
margin: 0.1rem;
padding: 0.1rem;
max-width: 100%;
}
.del {
background-color: red;
display: inline-block;
cursor: pointer;
border-radius: 50%;
width: 0.7rem;
margin-left: 2rem;
}
<div id="container">
<button class="item" id="main_item" style="background-color:blue;" onclick="see(this)">default column </button>
<button class="item" onclick="plus(this)">+</button>
</div>
but when I press the 'x' to remove a column, I want the default column to color blue, but the line of code which is suppose to achieve that isn't working
document.querySelector("#main_item").style.backgroundColor = "blue"
Before pressing 'x':
After pressing 'x' on the last column:
What it SHOULD look like:
I've losing sleep over this, can someone PLEASE tell me why isn't it working?
When you click on the "X", both of your onclick handlers are getting called, including the one that runs clear_selected, which sets the background color to "".
You can fix this by using stopPropagation on the event passed into the onclick function for the "x". That will stop the click event from going up the chain to the parent element of the "x".
temp.onclick = function(e) {
document.querySelector("#main_item").style.backgroundColor = "blue"
this.parentElement.remove();
e.stopPropagation();
};

Vertical dragBar for resizing two divs

I wanted a vertical dragBar for resizing two divs. I have created an example for the same but I am facing an issue.
Actual : As and when I resize the the upper div and move the slider down, the area of parent div increases and hence a scroll bar is given.
Expected: When Resizing, if the slider is moved down, it should only show the data contained in the upper div and when slider is moved up, it should show the content of lower div and should not increase the over all length of the parent div.
var handler = document.querySelector('.handler');
var wrapper = handler.closest('.wrapper');
var boxA = wrapper.querySelector('.box1');
var boxB = wrapper.querySelector('.box2');
var isHandlerDragging = false;
document.addEventListener('mousedown', function(e) {
// If mousedown event is fired from .handler, toggle flag to true
if (e.target === handler) {
isHandlerDragging = true;
}
});
document.addEventListener('mousemove', function(e) {
// Don't do anything if dragging flag is false
if (!isHandlerDragging) {
return false;
}
// Get offset
var containerOffsetTop= wrapper.offsetTop;
var containerOffsetBottom= wrapper.offsetBottom;
// Get x-coordinate of pointer relative to container
var pointerRelativeXpos = e.clientY - containerOffsetTop;
var pointerRelativeXpos2 = e.clientY - e.offsetTop + e.offsetHeight;
var boxAminWidth = 30;
boxA.style.height = (Math.max(boxAminWidth, pointerRelativeXpos - 2)) + 'px';
boxA.style.flexGrow = 0;
boxB.style.height = (Math.max(boxAminWidth, pointerRelativeXpos2 - 8)) + 'px';
boxB.style.flexGrow = 0;
});
document.addEventListener('mouseup', function(e) {
// Turn off dragging flag when user mouse is up
isHandlerDragging = false;
});
body {
margin: 40px;
}
.wrapper {
background-color: #fff;
color: #444;
/* Use flexbox */
}
.box1, .box2 {
background-color: #444;
color: #fff;
border-radius: 5px;
padding: 20px;
font-size: 150%;
margin-top:2%;
/* Use box-sizing so that element's outerwidth will match width property */
box-sizing: border-box;
/* Allow box to grow and shrink, and ensure they are all equally sized */
}
.handler {
width: 20px;
height:7px;
padding: 0;
cursor: ns-resize;
}
.handler::before {
content: '';
display: block;
width: 100px;
height: 100%;
background: red;
margin: 0 auto;
}
<div class="wrapper">
<div class="box1">A</div>
<div class="handler"></div>
<div class="box2">B</div>
</div>
Hope I was clear in explaining the issue I am facing in my project. Any help is appreciated.
It looks like your on the right track. You just need to make the wrapper a flexbox with the flex direction column and assign it a height. Also box 2 needs to have a flex of 1 so it can grow and shrink as needed. Finally I needed to remove the code that set the flex grow to 0 in the JavaScript. Here is the result.
var handler = document.querySelector('.handler');
var wrapper = handler.closest('.wrapper');
var boxA = wrapper.querySelector('.box1');
var boxB = wrapper.querySelector('.box2');
var isHandlerDragging = false;
document.addEventListener('mousedown', function(e) {
// If mousedown event is fired from .handler, toggle flag to true
if (e.target === handler) {
isHandlerDragging = true;
}
});
document.addEventListener('mousemove', function(e) {
// Don't do anything if dragging flag is false
if (!isHandlerDragging) {
return false;
}
e.preventDefault();
// Get offset
var containerOffsetTop= wrapper.offsetTop;
var containerOffsetBottom= wrapper.offsetBottom;
// Get x-coordinate of pointer relative to container
var pointerRelativeXpos = e.clientY - containerOffsetTop;
var pointerRelativeXpos2 = e.clientY - e.offsetTop + e.offsetHeight;
var boxAminWidth = 30;
boxA.style.height = (Math.max(boxAminWidth, pointerRelativeXpos - 2)) + 'px';
boxB.style.height = (Math.max(boxAminWidth, pointerRelativeXpos2 - 8)) + 'px';
});
document.addEventListener('mouseup', function(e) {
// Turn off dragging flag when user mouse is up
isHandlerDragging = false;
});
body {
margin: 40px;
}
.wrapper {
background-color: #fff;
color: #444;
/* Use flexbox */
display: flex;
flex-direction: column;
height: 200px;
}
.box1, .box2 {
background-color: #444;
color: #fff;
border-radius: 5px;
padding: 20px;
font-size: 150%;
margin-top:2%;
/* Use box-sizing so that element's outerwidth will match width property */
box-sizing: border-box;
/* Allow box to grow and shrink, and ensure they are all equally sized */
}
.box2 {
flex: 1;
}
.handler {
width: 20px;
height:7px;
padding: 0;
cursor: ns-resize;
}
.handler::before {
content: '';
display: block;
width: 100px;
height: 100%;
background: red;
margin: 0 auto;
}
<div class="wrapper">
<div class="box1">A</div>
<div class="handler"></div>
<div class="box2">B</div>
</div>

DIVs split into half and added as a child in a loop

I was asked this question during an interview recently.
Problem statement - Given a div of a certain width and height, keep appending divs to it, but size it down to half before the append. Do it until height/width is less than 10. Attached is my solution
let toggle = true;
let border = 0;
container = $('.mainBox');
while (container.height() > 10 || container.width() > 10) {
if(toggle) {
container = splitVertically(container);
toggle = false;
} else {
container = splitHorizontally(container);
toggle = true;
}
}
function splitVertically(container) {
let $newElem = $('<div>')
.width(container.width()/2)
.height(container.height())
.css('border-right', 'solid 1px');
container.append($newElem);
return $newElem;
}
function splitHorizontally(container) {
let $newElem = $('<div>')
.height(container.height()/2)
.width(container.width())
.css('border-bottom', 'solid 1px');
container.append($newElem);
return $newElem;
}
.mainBox {
width: 500px;
height: 200px;
/* background: blue; */
border: 1px solid;
}
.addBorder {
border: 1px solid;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="mainBox"></div>
If I wanted to add the divs to right of parent how would I do that?
Thanks!
You can try by putting border-left and float:right
let toggle = true;
let border = 0;
container = $('.mainBox');
while (container.height() > 10 || container.width() > 10) {
if (toggle) {
container = splitVertically(container);
toggle = false;
} else {
container = splitHorizontally(container);
toggle = true;
}
}
function splitVertically(container) {
let $newElem = $('<div class="pull-right">')
.width(container.width() / 2)
.height(container.height())
.css('border-left', 'solid 1px');
container.append($newElem);
return $newElem;
}
function splitHorizontally(container) {
let $newElem = $('<div class="">')
.height(container.height() / 2)
.width(container.width())
.css('border-bottom', 'solid 1px');
container.append($newElem);
return $newElem;
}
.mainBox {
width: 500px;
height: 200px;
/* background: blue; */
border: 1px solid;
}
.addBorder {
border: 1px solid;
}
.pull-right {
float: right;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="mainBox"></div>
Use after in place of append and also add a class name to the div you are adding and then in its style make display: inline-block; Check the below snippet in full page mode to see it in work.
let toggle = true;
let border = 0;
container = $('.mainBox');
while (container.height() > 10 || container.width() > 10) {
if(toggle) {
container = splitVertically(container);
toggle = false;
} else {
container = splitHorizontally(container);
toggle = true;
}
}
function splitVertically(container) {
let $newElem = $('<div class="mainBox">')
.width(container.width()/2)
.height(container.height())
.css('border-right', 'solid 1px');
container.after($newElem);
return $newElem;
}
function splitHorizontally(container) {
let $newElem = $('<div class="mainBox">')
.height(container.height()/2)
.width(container.width())
.css('border-bottom', 'solid 1px');
container.after($newElem);
return $newElem;
}
.mainBox {
width: 500px;
height: 200px;
/* background: blue; */
border: 1px solid;
display: inline-block;
}
.addBorder {
border: 1px solid;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="mainBox"></div>
Hope this helps
Adding float: left to the CSS for your child divs will allow that. This version also shows an example that doesn't require jQuery
let box = document.querySelector('.mainBox'), w = box.clientWidth, h = box.clientHeight
function px(val){ return [val, 'px'].join('') }
while(Math.max(w, h) > 10){
let child = document.createElement('div')
if(w > h) w /= 2
else h /= 2
child.style.width = px(w)
child.style.height = px(h)
box.appendChild(child)
}
div {
border: 1px solid black;
vertical-align: top;
box-sizing: border-box;
}
.mainBox {
width: 500px;
height: 200px;
/* background: blue; */
}
.mainBox > div {
float: left;
}
<div class="mainBox"></div>

Javascript: removeChild at certain screen size

I'm trying for hours now to add a wrapper around two divs (aside and .related) at a certain screensize (>60em and <90em). I'm doing this with matchMedia and an eventListener. The wrapper seems to be added at the right spot, but the problem is that it's still there even when the condition of the size is not met.
Here is a jsfiddle: http://jsfiddle.net/Vanilla__/4q26ngmg/1/
Simplified HTML:
<body>
<header>Header</header>
<main>Main</main>
<aside>Aside</aside>
<div class="related">Related</div>
<footer>Footer</footer>
</body>
Javascript:
if(window.matchMedia("screen and (min-width: 60em) and (max-width: 90em)").matches) {
window.addEventListener("resize", function addWrapper(q) {
//Create div with id wrapper
var div = document.createElement('div');
div.id = "wrapper";
// Select aside
var selectDiv = document.querySelector("aside");
//clone
div.appendChild(selectDiv.cloneNode(true));
//Place the new wrapper at the right place in the HTML
selectDiv.parentNode.replaceChild(div, selectDiv);
//Add related to the wrapper so they're both in the wrapper
document.querySelector('#wrapper').appendChild(
document.querySelector('.related') );
});
}
I wanted to add an 'else' to remove the child (with removeChild) or delete the eventListener (with removeEventListener) when there's another screen size, but all I get is errors about that the function is not definied or other errors whatever I try.
else {
window.removeEventListener("resize", addWrapper(q));
}
Does anyone know how the wrapper can be removed when the screensize is not >60em and <90em? I'm a Javascript rookie (as might be clear ;) ). Any help is appreciated.
You could do something like this:
var addWrapper = function () {
//Don't add wrapper if already added
var wrapper = document.getElementById("wrapper");
if (wrapper !== null) return;
//Create div with id wrapper
var div = document.createElement('div');
div.id = "wrapper";
// Select aside
var selectDiv = document.querySelector("aside");
//clone
div.appendChild(selectDiv.cloneNode(true));
//Place the new wrapper at the right place in the HTML
selectDiv.parentNode.replaceChild(div, selectDiv);
//Add related to the wrapper so they're both in the wrapper
document.querySelector('#wrapper').appendChild(
document.querySelector('.related'));
};
var removeWrapper = function () {
//Don't remove if there is no wrapper
var wrapper = document.getElementById("wrapper");
if (wrapper === null) return;
//Replace wrapper with its content
wrapper.outerHTML = wrapper.innerHTML;
}
var wrapperFixer = function () {
if (window.matchMedia("screen and (min-width: 60em) and (max-width: 90em)").matches) {
addWrapper();
} else {
removeWrapper();
}
}
window.onload = function () {
window.addEventListener("resize", wrapperFixer);
//Check and add if wrapper should be added on load
wrapperFixer();
}
body {
display: flex;
height: 40em;
flex-wrap: wrap;
font-family: Helvetica, Arial, sans-serif;
color: white;
text-align: center;
}
header {
background-color: purple;
width: 30%
}
main {
background-color: pink;
width: 40%
}
aside {
background-color: deepPink;
width: 15%
}
.related {
background-color: red;
width: 15%
}
footer {
background-color: slateBlue;
width: 100%;
height: 5em;
}
#wrapper {
border: 4px solid white;
}
<body>
<header>Header</header>
<main>Main</main>
<aside>Aside</aside>
<div class="related">Related</div>
<footer>Footer</footer>
</body>

Div containing input disapears on mouseout

I would like to keep a div visible while the mouse is in the bounds of the div, the code works until it hovers over the input. I would like a sign up form appear onmouseover and when the sign in is complete and the mouse moves off the div is no longer visible. jsFiddle Demo
HTML
<div class="members">
Members
<div id="sign-up-form" class="sign-up-form">
<input type="text" name="firstName">
</div>
</div>
JS
var signUp = document.getElementById('signUp');
var signUpForm = document.getElementById('sign-up-form');
signUp.onmouseover = function(){
signUpForm.style.display = 'block';
}
signUpForm.onmouseout = function(){
signUpForm.style.display = 'none';
}
CSS
#signUp{
position: relative;
background-color: red;
color: white;
padding: 6px;
}
#sign-up-form{
display: none;
position:absolute;
top: 32px;
left: 8px;
background-color: rgba(0,83,159,0.6);
padding: 15px;
}
I would do it this only with CSS:
#sign-up-form {
display: none;
}
.members:hover #sign-up-form {
display: block;
}
This example uses mouseover and mouseout event listeners and a function that will listen to all children elements before changing the display of the signUpForm element.
function outVis(event) {
var e = event.toElement || event.relatedTarget;
if (e.parentNode == this || e == this) {
return;
}
signUpForm.style.display = 'none';
}
http://jsfiddle.net/9xhb532v/1/

Categories

Resources