I have to center a div vertically, with only a margin above and below.
So I made it generate the margin with JavaScript, like this.
var xLength = ((document.getElementById("outerdiv").offsetHeight)+"px");
xLength = (xLength - 222); //222 is the Length of the to be centered div
xMargin = (xLength / 2); //because of the 2 margins
xMargin = (xMargin());
document.getElementById(innerdiv).style.marginTop = xMargin;
document.getElementById(innerdiv).style.marginBottom = xMargin;
Please help, can't get it to work, any ideas?
Here is the CSS of outer and inner div:
#outerdiv {
min-height:302px;
width:58px;
margin-left:640px;
z-index:2;
float:right;
margin-right:228px;
border: 1px solid black;
position:absolute;
}
#innerdiv {
height:222px;
width:58px;
position:absolute;
border: 1px solid green;
}
HTML:
<div id='outerdiv'>
<div id='innerdiv'>
</div>
</div>
This is because your element's parent doesn't have a defined height itself.
With respect to your JavaScript, one problem is this line, which makes no sense at all and should be removed:
xMargin = (xMargin());
You should also add 'px' to the values you are setting, and put quotes around the ID, like this:
document.getElementById('innerdiv').style.marginTop = xMargin + 'px';
document.getElementById('innerdiv').style.marginBottom = xMargin + 'px';
window.onload = checkAvailableHeight;
window.onresize = checkAvailableHeight;
function checkAvailableHeight(){
var yourDiv = document.getElementById("yourDiv");
yourDiv.style.marginTop = ((window.innerHeight - yourDivHeight) / 2) + "px";
}
Related
The following code always shows the coordinates of the cursor below the cursor:
function showCoords(e) {
var x = event.clientX;
var y = event.clientY;
var coor = "(" + x + ", " + y + ")";
document.getElementById("box").innerHTML = coor;
var bx = document.getElementById("box");
bx.style.left = e.pageX - 50;
bx.style.top = e.pageY + 20;
}
function clearCoords() {
document.getElementById("box").innerHTML = "";
}
div.relative {
position: relative;
width: 400px;
height: 300px;
border: 1px solid black;
}
div.abs {
position: absolute;
top: 100px;
right: 50px;
width: 200px;
height: 100px;
background-color: yellow;
}
<body onmousemove="showCoords(event)">
<div class="relative">
<div class="abs" onmousemove="showCoords(event)" onmouseout="clearCoords()"></div>
</div>
<div id="box" style="width:100px; height:30px; position:absolute"></div>
</body>
I only want the coordinates to be visible when the mouse pointer is hovering over the yellow rectangle.
If I change <body onmousemove="showCoords(event)"> to <body>, the coordinates are never visible.
How do I get the coordinates be visible only when hovering over the yellow rectangle?
Move the onmousemove listener from the body to the element you want to listen on - div.abs in this case.
I'd recommend not using the onmousemove attribute, in favour of using an entirely javascript solution - just to keep javascript-y things together. Something like (untested)
var listenOn = document.querySelector(".abs");
listenOn.addEventListener("mousemove", ShowCoords);
I am having a little bit of trouble with my CSS, as when I change the default zoom (Command + on Mac) of the browser it causes the below image.
When it is at 100% viewport on chrome, it is supposed to look like the below where it fits perfectly in the black box.
My html code is below. For the sake of simplicity, I have only included the container and the tag to show where I wrote it.
<body>
<div class="container">
<div class="container-bars"></div>
</div>
</body>
My CSS code is below:
body {
background-color: rgb(89, 87, 87);
margin-right: auto;
margin-left: auto;
.container {
background-color: rgb(37, 35, 35);
height: 80%;
position: absolute;
width: 60%;
left: 500px;
top: 150px;
}
.bars {
float: left;
border: 1px solid rgb(232, 10, 10);
background-color: rgb(218, 215, 215);
}
The .container is the black box in the background and the body is the grey background. Finally, .bars just represents the CSS for each bar. I am creating a visualizer so the when adding the bars, I am using javascript. The code for adding the bars is below.
const container = document.querySelector('.container');
function add_bars(input) {
const Div = document.createElement('div');
const containerWidth = container.clientWidth;
const containerHeight = container.clientHeight;
const barWidth = containerWidth / inputval - 2;
Div.className = 'bars';
//prettier-ignore
Div.style.height = `${((containerHeight / 100) * input) - 2}px`;
Div.style.width = `${barWidth}px`;
containerBars.append(Div);
}
The input in this case is how large the size of the array is which I am dividing in order to split the width of each bar equally. Any help would be appreciated as to why it exceeds the container when I change how "zoomed" in the browser is. Thanks!
function for_loop(array) {
resetArray();
for (let i = 0; i < array.length; i++) {
add_bars(array[i]);
}
}
When you use % or vh vw in css and change zoom the elements will change their sizes. Try a console.log(document.querySelector(".container")) after and before changing zoom and you will see a different value. In order to avoid that behavior you have to use fixed sizes in your elements. For example:
.container {
background-color: rgb(37, 35, 35);
position: absolute;
height: 600px; // pixels, not % or vh
width: 800px;// the same
left: 150px;
top: 150px;
}
Also, when you make zoom out the problem persist. In order to avoid that just add the next:
* {
box-sizing: border-box;
}
And there is no need to substract 2 px in add_bars function:
...
const barWidth = containerWidth / inputval;
...
Div.style.height = `${((containerHeight / 100) * input)}px`;
...
I have a table full of data that tends to be larger than the screen.
I put the table in a DIV and set the "overflow" to "auto" in CSS
div.scrolling-comps {
width : 970px;
height : 800px;
overflow : auto;
}
So the DIV can be scrolled up/down, left right using the browser's built-in scroll bars.
Problem is, the table can be WAAY bigger than the screen. And while the mousewheel will scroll it up/down, scrolling left/right is a pain in the hooch.
So, looking for a javascript/jquery or CSS way to scroll the div NATURALLY.
In other words, when someone viewing the huuuge table moves their mouse to the right, the DIV goes to the left (thus scrolling without using the scroll bars).
Something similar to this, but instead of following the mouse, the div would move opposite the mouse...
window.onload = function() {
var bsDiv = document.getElementById("box-shadow-div");
var x, y;
// On mousemove use event.clientX and event.clientY to set the location of the div to the location of the cursor:
window.addEventListener('mousemove', function(event) {
x = event.clientX;
y = event.clientY;
if (typeof x !== 'undefined') {
bsDiv.style.left = x + "px";
bsDiv.style.top = y + "px";
}
}, false);
}
#box-shadow-div {
position: fixed;
width: 1000px;
height: 800px;
border-radius: 0%;
background-color: black;
box-shadow: 0 0 10px 10px black;
top: 49%;
left: 48.85%;
}
<div id="box-shadow-div"></div>
The example you have about using the mouse position is interesting... But it is not what you need to achieve what you described.
In fact... What you need to know is the "ratio" between the div wrapping the table and its scrollWidth
Then, using the X position of the mouse, you can apply a scroll to the div in order to make it "move".
I used jQuery to do it using very few lines.
// Just to fake a big table
var fakeCell = $("<td>Some data</td>");
for(i=0;i<100;i++){
var fakeRow = $("<tr>");
for(k=0;k<50;k++){
fakeRow.append(fakeCell.clone().append(" "+k));
}
$("#test").append(fakeRow.clone());
}
// ---------------------------------------------------
// Calculate the "ratio" of the box-div width versus its scrollable width
var ratio = $("#box-div")[0].scrollWidth / $("#box-div").width();
console.log("Ratio: "+ratio);
// Scroll left/rigth based on mouse movement
$(window).on("mousemove", function(e){
var X = ratio * e.pageX;
// Scroll the div using the mouse position multiplyed by the ratio
$("#box-div").scrollLeft(X);
});
td{
white-space: nowrap;
border: 1px solid black;
}
#box-div{
overflow:auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div id="box-div">
<table id="test">
</table>
</div>
</body>
So while the user moves the mouse over the div's width, you apply a scroll multiplied by the ratio... The effect is the user can scroll it all from the most left to most right ends easilly.
How about this?
wrap a table in div (i.e. parent-div) which is relatively positioned
Give position absolute to the target div.
And change left & top position of target div on mousemove event.
window.onload = function() {
var bsDiv = document.getElementById("box-shadow-div");
var x, y;
// On mousemove use event.clientX and event.clientY to set the location of the div to the location of the cursor:
window.addEventListener('mousemove', function(event) {
x = event.clientX;
y = event.clientY;
if (typeof x !== 'undefined') {
bsDiv.style.left = -x + "px";
bsDiv.style.top = -y + "px";
}
}, false);
}
.parent-div {
position: relative;
}
#box-shadow-div {
position: absolute;
width: 1000px;
height: 800px;
border-radius: 0%;
background-color: black;
box-shadow: 0 0 10px 10px black;
top: 0;
left: 0;
}
<div class="parent-div">
<div id="box-shadow-div"></div>
</div>
Have you tried changing x to -x? this will technically "invert" the effect.
window.onload = function() {
var bsDiv = document.getElementById("box-shadow-div");
var x, y;
// On mousemove use event.clientX and event.clientY to set the location of the div to the location of the cursor:
window.addEventListener('mousemove', function(event) {
x = event.clientX;
y = event.clientY;
if (typeof x !== 'undefined') {
bsDiv.style.left = -x + "px";
bsDiv.style.top = -y + "px";
}
}, false);
}
#box-shadow-div {
position: fixed;
width: 1000px;
height: 800px;
border-radius: 0%;
background-color: black;
box-shadow: 0 0 10px 10px black;
top: 49%;
left: 48.85%;
}
<div id="box-shadow-div"></div>
I need to use JS no JQuery plugins to make a simple tooltip like on the image below.
Click on ? image should open this tooltip and click again on the same image to close it.
I think that it's simple for someone with good JS knowledge but I can't do it anyway :(
This is something that I have tried I know it's not too much but I am simply stuck.
How to display it like on the image, how to hide it when it's open and how to add that little triangle in the corner?
myfiddle
<img id="info" src="http://www.craiglotter.co.za/wp-content/uploads/2009/12/craig_question_mark_icon1.png"/>
<div id="ttip">bla bla</div>
document.getElementById('info').addEventListener('click', function(){
// how to check if it's visible so I can close tooltip
document.getElementById('ttip').style.display="block";
});
#info{margin-left:100px;margin-top:50px;}
#ttip
{
width: 280px;
z-index: 15001;
top: 0px;
left: 0px;
display: none;
border-color: #666;
background-color: #fff;
color: #666;
position: relative;
border: 1px solid #666;
padding: 15px 9px 5px 9px;
text-align: left;
word-wrap: break-word;
overflow: hidden;
}
Clean up the css and this will basically do it:
<script>
function doTip(e){
var elem = e.toElement;
if(elem.getAttribute('data-tip-on') === 'false') {
elem.setAttribute('data-tip-on', 'true');
var rect = elem.getBoundingClientRect();
var tipId = Math.random().toString(36).substring(7);
elem.setAttribute('data-tip-id', tipId);
var tip = document.createElement("div");
tip.setAttribute('id', tipId);
tip.innerHTML = elem.getAttribute('data-tip');
tip.style.top = rect.bottom+ 10 + 'px';
tip.style.left = (rect.left-200) + 'px';
tip.setAttribute('class','tip-box');
document.body.appendChild(tip);
} else {
elem.setAttribute('data-tip-on', 'false');
var tip = document.getElementById(elem.getAttribute('data-tip-id'));
tip.parentNode.removeChild(tip);
}
}
function enableTips(){
var elems = document.getElementsByClassName('quick-tip');
for(var i = 0; i < elems.length; i++) {
elems[0].addEventListener("click", doTip, false);
}
}
window.onload = function(){
enableTips();
}
</script>
<style>
.quick-tip {
background: black;
color: #fff;
padding: 5px;
cursor: pointer;
height: 15px;
width: 15px;
text-align: center;
font-weight: 900;
margin-left: 350px;
}
.tip-box {
/* change dimensions to be whatever the background image is */
height: 50px;
width: 200px;
background: grey;
border: 1px solid black;
position: absolute;
}
</style>
<div class="quick-tip" data-tip="THIS IS THE TIP! change elements 'data-tip' to change." data-tip-on="false">?</div>
<script>enableTips(); //might be required for jsfiddle, especially with reloads.</script>
Edit: fixed formatting and a bug. jsfiddle: http://jsfiddle.net/u93a3/
Proof of concept:
The following markup in HTML: Create a div with class tooltip, add image and a div with class info with all text (can be multiple paragraphs if needed, scollbars is shown if necessary):
<div class='tooltip'>
<img src='craig_question_mark_icon1.png' alt='Help'/>
<div class='info'>
Some text to fill the box with.
</div>
</div>
The div.info is set to display:none in CSS.
When the page is loaded a pure javascript is running that draws an image of a triangle on a canvas-element, and then creates a div-element where the triangle is set as a background. Then, for every div.tooltip:
add a click-eventhandler to the image
replace the div.info with a div.info_container
add a clone of the triangle-div to div.info_container
add the original div.info to div.info_container
You can test it with this fiddle. It is tested successfully on FF25, Chrome31, IE10, Opera 12&18.
<!doctype html>
<html>
<head>
<script>
"use strict";
function click(event) {
var elem = this.parentNode.querySelector('div.info_container');
if (elem) elem.style.display = elem.style.display === 'block' ? 'none' : 'block';
}
function toolify() {
var idx,
len,
elem,
info,
text,
elements = document.querySelectorAll('div.tooltip'),
canvas,
imgurl,
pointer,
tipHeight = 20,
tipWidth = 20,
width = 200,
height = 100,
ctx;
// Create a canvas element where the triangle will be drawn
canvas = document.createElement('canvas');
canvas.width = tipHeight;
canvas.height = tipWidth;
ctx = canvas.getContext('2d');
ctx.strokeStyle = '#000'; // Border color
ctx.fillStyle = '#fff'; // background color
ctx.lineWidth = 1;
ctx.translate(-0.5,-0.5); // Move half pixel to make sharp lines
ctx.beginPath();
ctx.moveTo(1,canvas.height); // lower left corner
ctx.lineTo(canvas.width, 1); // upper right corner
ctx.lineTo(canvas.width,canvas.height); // lower right corner
ctx.fill(); // fill the background
ctx.stroke(); // stroke it with border
//fix bottom row
ctx.fillRect(0,canvas.height-0.5,canvas.width-1,canvas.height+2);
// Create a div element where the triangel will be set as background
pointer = document.createElement('div');
pointer.style.width = canvas.width + 'px';
pointer.style.height = canvas.height + 'px';
pointer.innerHTML = ' ' // non breaking space
pointer.style.backgroundImage = 'url(' + canvas.toDataURL() + ')';
pointer.style.position = 'absolute';
pointer.style.top = '2px';
pointer.style.right = '1px';
pointer.style.zIndex = '1'; // place it over the other elements
for (idx=0, len=elements.length; idx < len; ++idx) {
elem = elements[idx];
elem.querySelector('img').addEventListener('click',click);
text = elem.querySelector('div.info');
// Create a new div element, and place the text and pointer in it
info = document.createElement('div');
text.parentNode.replaceChild(info,text);
info.className = 'info_container';
info.appendChild(pointer.cloneNode());
info.appendChild(text);
//info.addEventListener('click',click);
}
}
window.addEventListener('load',toolify);
</script>
<style>
div.tooltip
{
position:relative;
display:inline-block;
width:300px;
text-align:right;
}
div.tooltip > div.info
{
display:none;
}
div.tooltip div.info_container
{
position:absolute;
right:20px;
width:200px;
height:100px;
display:none;
}
div.tooltip div.info
{
text-align:left;
position:absolute;
left:1px;
right:1px;
top:20px;
bottom:1px;
color:#000;
padding:5px;
overflow:auto;
border:1px solid #000;
}
</style>
</head>
<body>
<div class='tooltip'>
<img src='craig_question_mark_icon1.png' alt='Help'/>
<div class='info'>
Some text to fill the box with.
</div>
</div>
<div class='tooltip'>
<img src='craig_question_mark_icon1.png' alt='Help'/>
<div class='info'>
Some text to fill the box with.
Some text to fill the box with.
Some text to fill the box with.
Some text to fill the box with.
</div>
</div>
</body>
</html>
I am trying to create a function that is supposed to take the mouse coordinates and draw a small radius using their values and inserting them into CSS left and top positions. I am stuck at the part where I am supposed to add the div that I have created to the html. Please forgive me if I am not being clear enough.
<script type="text/javascript">
function getcoord(event) {
var x=event.clientX ;
var y=event.clientY ;
follow(x,y);
function follow(xcor,ycor) {
folowHTML =
'<div style="'background-color:red;width:30px;height:30px;'
+'border-radius:30px;position:absolute;left:''+xcor;'top:'+ycor';">'
+'</div>';
};}
</script>
<body onmouseover="getcoord(event);">
</body>
Maybe try add this line:
document.body.innerHtml = folowHTML + document.body.innerHtml;
Also You should probably change position absolute to fixed I think.
Edit: This was bad way
Here You have answer:
Instert element before </body> tag with vanilla JavaScript
You could try something like this...
<style>
#follow {
background-color: #fff;
border:1px solid red;
border-radius: 50%;
height: 20px;
margin:-10px 0 0 -10px;
position: absolute;
width: 20px;
z-index: 10;
}
</style>
<script>
function initFollow(){
var follow = document.createElement('div');
follow.setAttribute('id','follow');
document.getElementsByTagName("body")[0].appendChild(follow);
window.addEventListener('mousemove', function(e) {
var left = e.pageX + 'px',
top = e.pageY + 'px';
follow.style.left = left;
follow.style.top = top;
}, false);
}
window.addEventListener('load',initFollow,false);
</script>