Why is my paragraph popup coming outside my div with the "mousedown" event? - html

I need to show my paragraph inside my <div> when click on the <div>. This is my code:
const area = document.getElementById("area");
const popup = document.getElementById("popup");
function showPopup(event) {
let x = event.clientX;
let y = event.clientY;
popup.style.left = `${x}px`;
popup.style.top = `${y}px`;
popup.style.visibility = "visible";
}
area.addEventListener("mousedown", showPopup);
.area {
border: 1px solid;
position: absolute;
height: 200px;
width: 200px;
}
.popup {
visibility: hidden;
position: absolute;
display: inline-block;
}
<div id="area" class="area">
<p class="popup" id="popup">popup</p>
</div>
Note that this is inside another main body <div> (also with position: absolute).

Try this
<div id="area">
<div class="area""
<p class="popup" id="popup">popup</p>
</div>
</div>

I tested your code and observed you are changing style.top property based on your ClientX value which is causing popup element to appear over random position. Use following updated code and it's should be good.
function showPopup(event) {
console.log(event.clientX, event.clientY)
let x = event.clientX;
let y = event.clientY;
popup.style.left = `${x - 8}px`;
popup.style.top = `${y - 8}px`;
popup.style.visibility = "visible";
}
and few CSS changes as -
.area {
border: 1px solid;
position: relative;
height: 200px;
width: 200px;
}
.popup {
visibility: hidden;
position: absolute;
display: inline-block;
margin: 0;
}
For more close positioning of popup element.

Related

Header position offset not following top margin of container

Here I have a header with position: fixed. As it does not go with the normal flow of the window, a margin for the body is set to the height of the header (here 100px). Now, the body starts right after the bottom of the header.
The main div in the body has a margin-top of 50px. But, the header grasps that margin, and it's not shown. If I set a border on the body, then the margin is shown. I don't know what is the relation of that top margin with the border of the body.
This can be solved if I add 50px more to the margin-top of the main div. But I want to know what's happening here.
body {
background-color: white;
margin-top: 100px;
/* border: 1px solid black; */
}
header {
background-color: black;
height: 100px;
position: fixed;
z-index: 1;
top: 0;
left: 0;
right: 0;
}
main {
background-color: gray;
margin-top: 50px;
width: 100%;
height: 100vh;
}
<header></header>
<main></main>
Adding a border adjusts the display of the layout because the <body> and the <main> margins overlap without the border (since it's just whitespace), but with the border rendered, the two margins must be separate. Thus, without the border, the total margin is 100px, and with the border, the total margin is 150px.
See demo below. (I've also added a button to hide the <header> since it's position is fixed, so it isn't relevant to the situation.
const body = document.querySelector("body");
const header = document.querySelector("header");
const a = document.createElement("div");
const b1 = document.createElement("button");
b1.textContent = "Toggle body border";
b1.addEventListener("click", () => {
if (body.style.border !== "1px solid red") {
body.style.border = "1px solid red";
} else {
body.style.border = "none";
}
});
const b2 = document.createElement("button");
b2.textContent = "Toggle body margin";
b2.addEventListener("click", () => {
if (body.style.marginTop !== "0px") {
body.style.marginTop = "0px";
} else {
body.style.marginTop = "100px";
}
});
const b3 = document.createElement("button");
b3.textContent = "Toggle header visibility";
b3.addEventListener("click", () => {
if (header.style.display !== "none") {
header.style.display = "none";
} else {
header.style.display = "block";
}
});
a.appendChild(b1);
a.appendChild(b2);
a.appendChild(b3);
a.style.position = "fixed";
a.style.top = "0";
a.style.zIndex = "2";
document.body.appendChild(a);
body {
background-color: white;
margin-top: 100px;
}
header {
background-color: black;
height: 100px;
position: fixed;
z-index: 1;
top: 0;
left: 0;
right: 0;
}
main {
background-color: gray;
margin-top: 50px;
width: 100%;
height: 100vh;
}
<header></header>
<main></main>

Display a Search bar on header on scroll HTML/CSS

I have a search bar which would like to display onto the header on scroll, a great example is like the one on this site: https://www.indiamart.com/
Approach 1 - A simple way to do this would be to detect a scroll & add and remove a class that contains display: none;
You can have an event listener -
window.addEventListener('scroll', function() {
if( window.scrollY !== 0) {
document.getElementById('searchBar').classList.add('scrolled');
} else {
document.getElementById('searchBar').classList.remove('scrolled');
}
});
With the CSS -
.noScroll
{
background: yellow;
position:fixed;
height: 50px; /*Whatever you want*/
width: 100%; /*Whatever you want*/
top:0;
left:0;
display:none;
}
/*Use this class when you want your content to be shown after some scroll*/
.scrolled
{
display: block !important;
}
.parent {
/* something to ensure that the parent container is scrollable */
height: 200vh;
}
And the html would be -
<div class="parent">
<div class ='noScroll' id='searchBar'>Content you want to show on scroll</div>
</div>
Here's a JSFiddle of the same - https://jsfiddle.net/kecnrh3g/
Approach 2 -
Another simple approach would be
<script>
let prevScrollpos = window.pageYOffset;
window.onscroll = function() {
let currentScrollPos = window.pageYOffset;
if (prevScrollpos > currentScrollPos) {
document.getElementById('searchBar').style.top = '-50px';
} else {
document.getElementById('searchBar').style.top = '0';
}
prevScrollpos = currentScrollPos;
}
</script>
with the html -
<div class="parent">
<div id ='searchBar'>Content you want to show on scroll</div>
</div>
and css
#searchBar {
background: yellow;
position: fixed;
top: 0;
left: 0;
height: 50px;
width: 100%;
display: block;
transition: top 0.3s;
}
.parent {
height: 200vh;
}
Here's a JSFiddle of the same - https://jsfiddle.net/0tkedcns/1/
From the same example, the idea is only to show/hide once user scroll the page using inline css display property, you can do the same or at least provide a code sample so we can help you!
HTML
<div class="search-bar">
<div class="sticky-search">
Sticky Search: <input type="text" value="search" />
</div>
</div>
CSS
.sticky-search {
display:none;
position:fixed;
top:0px;
left:0px;
right:0px;
background:blue;
padding:10px;
}
JS
var searchHeight = $(".search-bar").outerHeight();
var offset = $(".search-bar").offset().top;
var totalHeight = searchHeight + offset;
console.log(totalHeight);
$(window).scroll(function(){
if($(document).scrollTop() >= totalHeight) {
$('.sticky-search').show();
} else {
$('.sticky-search').hide();
}
});

Contain fixed element within container

Having a flex layout with top, left, middle and right.
Middle is divided into main and foot.
Within the main I want to have fixed elements, kind of like an MDI, as well as static elements.
If one scroll the fixed element should stay in same position of view. But, it should be contained within the main element if it is moved above or to the left of main. As in: not overlap the top, left, right etc.
THIS:
Colors and margins added to make a visual representation of the layout
NOT THIS:
Below is a simplified sample with a container within a container.
If one select the fixed positioning for the sub "window" it stay in place on scrolling, but it overlaps the parent if moved outside.
I can use absolute and reposition it on scroll by using JavaScript, but wondered if there was a pure CSS / layout way to get the same result.
function set_style_pos (e) {
moveable.style.position = e.target.value;
}
function halt (e) {
e.preventDefault();
e.stopPropagation();
}
const drag = {
el: null,
ex: 0,
ey: 0,
xs: 0,
ys: 0,
move: function (e) {
halt(e);
drag.el.style.marginLeft = (e.clientX - drag.sx + drag.ex) + 'px';
drag.el.style.marginTop = (e.clientY - drag.sy + drag.ey) + 'px';
},
end: function (e) {
halt(e);
window.removeEventListener('mouseup', drag.end);
window.removeEventListener('mousemove', drag.move);
},
start: function (e) {
let cs;
halt(e);
window.addEventListener('mouseup', drag.end);
window.addEventListener('mousemove', drag.move);
drag.el = e.target;
cs = getComputedStyle(drag.el);
drag.ex = parseInt(cs.getPropertyValue('margin-left')) || 0;
drag.ey = parseInt(cs.getPropertyValue('margin-top')) || 0;
drag.sx = e.clientX;
drag.sy = e.clientY;
},
check: function (e) {
let t = e.target;
if (t.dataset.moveable == "1")
drag.start(e);
}
};
document.addEventListener('mousedown', drag.check);
document.addEventListener('change', set_style_pos);
lines.textContent = "scroll me\n".repeat(100);
* {
box-sizing: border-box;
}
body {
margin: 0;
height: 100vh;
display: flex;
flex-direction: column;
color: #444;
font: 14px sans-serif;
}
label {
cursor: pointer;
}
.outer {
display: flex;
padding: 20px;
background: goldenrod;
flex-grow: 1;
overflow: hidden;
}
.inner {
position: relative;
overflow: scroll;
background: gray;
flex-grow: 1;
}
.box {
position: absolute;
width: 140px;
height: 150px;
background: silver;
box-shadow: 0 0 3px red;
cursor: move;
margin-left: 90px;
margin-top: -5px;
padding: 20px;
}
.box div {
font-weight: 700;
pointer-events: none;
text-align: center;
}
<div class="outer">
<div class="inner">
<div class="box" id="moveable" data-moveable="1">
<div>Move Me</div><br />
<label><input type="radio" name="p" value="absolute" checked />absolute</label><br />
<label><input type="radio" name="p" value="fixed" />fixed</label>
</div>
<pre id="lines"></pre>
</div>
</div>
Just use z-index.
Example:
function set_style_pos (e) {
moveable.style.position = e.target.value;
}
function halt (e) {
e.preventDefault();
e.stopPropagation();
}
const drag = {
el: null,
ex: 0,
ey: 0,
xs: 0,
ys: 0,
move: function (e) {
halt(e);
drag.el.style.marginLeft = (e.clientX - drag.sx + drag.ex) + 'px';
drag.el.style.marginTop = (e.clientY - drag.sy + drag.ey) + 'px';
},
end: function (e) {
halt(e);
window.removeEventListener('mouseup', drag.end);
window.removeEventListener('mousemove', drag.move);
},
start: function (e) {
let cs;
halt(e);
window.addEventListener('mouseup', drag.end);
window.addEventListener('mousemove', drag.move);
drag.el = e.target;
cs = getComputedStyle(drag.el);
drag.ex = parseInt(cs.getPropertyValue('margin-left')) || 0;
drag.ey = parseInt(cs.getPropertyValue('margin-top')) || 0;
drag.sx = e.clientX;
drag.sy = e.clientY;
},
check: function (e) {
let t = e.target;
if (t.dataset.moveable == "1")
drag.start(e);
}
};
document.addEventListener('mousedown', drag.check);
document.addEventListener('change', set_style_pos);
lines.textContent = "scroll me\n".repeat(100);
* {
box-sizing: border-box;
}
body {
margin: 0;
height: 100vh;
display: flex;
flex-direction: column;
color: #444;
font: 14px sans-serif;
}
label {
cursor: pointer;
}
.outer {
display: flex;
padding: 20px;
background: goldenrod;
/*flex-grow:1; Disable to control the height for presentaion*/
height:200px !important;
overflow:hidden; /*to hide scrollme lines*/
}
.inner {
position: relative;
overflow: scroll;
background: gray;
flex-grow: 1;
}
.box {
position: absolute;
width: 140px;
height: 150px;
background: silver;
box-shadow: 0 0 3px red;
cursor: move;
margin-left: 90px;
margin-top: -5px;
padding: 20px;
}
.box div {
font-weight: 700;
pointer-events: none;
text-align: center;
}
.prevent{
width:200px;
height:200px;
display:flex;
background-color:blue;
color:white;
justify-content:center;
align-items:center;
font-weight:bold;
/*--The solution--*/
z-index:1;
}
<div class="outer">
<div class="inner">
<div class="box" id="moveable" data-moveable="1">
<div>Move Me</div><br />
<label><input type="radio" name="p" value="absolute" checked />absolute</label><br />
<label><input type="radio" name="p" value="fixed" />fixed</label>
</div>
<pre id="lines"></pre>
</div>
</div>
<div class="prevent">
Prevent overlap
</div>
I hope this helps.
Use a sticky container and let children be absolute.
Had tested with z-index, all over, before posting but had not found any satisfactory solution that way.
I also tried various with position: sticky, and there is where I found the solution at last :)
One can wrap the sub windows in a sticky container which is positioned top left of the main container.
Pros:
Simple
Fairly clean HTML structure
The window stay below scroll-bars of container
Positioning relative to content wrapper
Cons:
If one want to make it non-fixed / non-sticy one have to move the element to parent and vice versa.
Absolute positioned children will not expand the container – thus not rearranging the DOM flow. (Which was the issue on earlier attempts using sticky).
Tested in FireFox, Chrome, Vivaldi, Opera Mini and Opera.
The core of it:
<div class="outer">
<div class="main">
<div class="wrap-sticky">
<div class="sub-window">
Fixed Window
</div>
</div>
Other "normal" content
</div>
</div>
And:
.outer {
overflow: hidden;
}
.main {
position: relative;
overflow: scroll;
}
.wrap-sticky {
position: sticky;
top: 0;
left: 0;
}
.sub-window {
position: absolute;
}
function get_pos (el) {
let cs = getComputedStyle(el);
return [
parseInt(cs.getPropertyValue('left')) || 0,
parseInt(cs.getPropertyValue('top')) || 0
];
}
function set_style_pos (e) {
let [x, y] = get_pos (moveable);
if (e.target.value == "sticky") {
wrap_sticky.appendChild(moveable);
moveable.style.left = (x - inner.scrollLeft) + 'px';
moveable.style.top = (y - inner.scrollTop) + 'px';
} else {
inner.appendChild(moveable);
moveable.style.left = (x + inner.scrollLeft) + 'px';
moveable.style.top = (y + inner.scrollTop) + 'px';
}
}
function halt (e) {
e.preventDefault();
e.stopPropagation();
}
const drag = {
el: null,
ex: 0,
ey: 0,
xs: 0,
ys: 0,
move: function (e) {
halt(e);
drag.el.style.left = (e.clientX - drag.sx + drag.ex) + 'px';
drag.el.style.top = (e.clientY - drag.sy + drag.ey) + 'px';
},
end: function (e) {
halt(e);
window.removeEventListener('mouseup', drag.end);
window.removeEventListener('mousemove', drag.move);
},
start: function (e) {
halt(e);
window.addEventListener('mouseup', drag.end);
window.addEventListener('mousemove', drag.move);
drag.el = e.target;
[drag.ex, drag.ey] = get_pos(drag.el);
drag.sx = e.clientX;
drag.sy = e.clientY;
},
check: function (e) {
let t = e.target;
if (t.dataset.moveable == "1")
drag.start(e);
}
};
document.addEventListener('mousedown', drag.check);
document.addEventListener('change', set_style_pos);
lines.textContent = "scroll me\n".repeat(100) + "horiz".repeat(100) + 'END';
* {
box-sizing: border-box;
}
body {
margin: 0;
height: 100vh;
display: flex;
flex-direction: column;
color: #444;
font: 14px sans-serif;
}
label {
cursor: pointer;
}
.outer {
display: flex;
padding: 20px;
background: goldenrod;
flex-grow: 1;
overflow: hidden;
}
.inner {
position: relative;
overflow: scroll;
background: gray;
flex-grow: 1;
}
.box {
position: absolute;
width: 160px;
height: 100px;
background: silver;
box-shadow: 0 0 3px red;
cursor: move;
padding: 20px;
top: 20px;
left: 20px;
}
.box div {
font-weight: 700;
pointer-events: none;
text-align: center;
}
.wrap-sticky {
position: sticky;
top: 0;
left: 0;
}
<div class="outer">
<div class="inner" id="inner">
<div class="wrap-sticky" id="wrap_sticky">
<div class="box" id="moveable" data-moveable="1">
<div>Drag & Move Me</div>
<label><input type="radio" name="p" value="sticky" checked />In sticky</label><br />
<label><input type="radio" name="p" value="absolute" />In main</label>
</div>
</div>
<pre id="lines"></pre>
</div>
</div>

How to use negative padding in css

I want to add negative padding in css, I have written a small code of battery charging cell. What I want is if I enter value in negative like -1px than the cell color should move to the left side and div should stay in center.
.cell {
width: 100px;
height: 30px;
border: 1px solid black;
}
.padding {
background-color: #3D9970;
width: 10px;
float: left;
height: 30px;
position: absolute;
left: 55px;
padding-right: 1px;
}
<div class="cell">
<div class="cell1"></div>
<div class="padding"></div><span style="display: inline;">
</div>
Please help me.
You can't.
See the specification:
Unlike margin properties, values for padding values cannot be negative.
I think you can achieve the same effect with pseudo elements:
.cell{
display:block;
width: 100px;
height: 30px;
position:relative;
}
.cell:before{
content:'';
background-color: #3D9970;
width: 10px;
top:0;
left:calc(50% - 5px);
height: 100%;
position: absolute;
}
.cell:after{
content:'';
border: 1px solid black;
width:100%;
height:100%;
display:block;
top:0;
left: 0px;
position: absolute;
}
<div class="cell">
</div>
"Left" property could be negative, so if you change it you can move the position of the green rectangle in the middle (.cell:before) of the block and border itself (.after)
The easiest way is to use an absolute positioning relatively to a parent node. Here the parent node would be the battery "housing".
So you can set the position CSS value of the rot div to relative, and then the charge one to absolute. Indeed, according to MDN Webdocs:
absolute: [...] It is positioned relative to its closest positioned ancestor, if any.
Then, you just have to play with the left and width CSS properties. For the "middle" case, I chose to display one border.
Below a working snippet. Just click the "Begin the charge variation" button to start the show.
var chargeElement = document.getElementById("charge");
// To set a charge to the battery, simply call: setCharge(percentage)
function setCharge(percentage) {
var left;
var width;
if (percentage > 100) percentage = 100;
if (percentage < 0) percentage = 0;
chargeElement.setAttribute("data-value", percentage);
// If the charge is 50%, simply draw a line
if (percentage == 50) {
chargeElement.className = "middle";
} else {
chargeElement.className = "";
}
// Otherwise, adjust left and width values
if (percentage >= 50) {
left = 50;
width = percentage - left;
} else {
left = percentage;
width = 50 - left;
}
// Then update the charge style.
chargeElement.style.left = left + "%";
chargeElement.style.width = width + "%";
}
// A simple function to add / remove some charge
function addCharge(percentage) {
var value = parseInt(chargeElement.getAttribute("data-value"));
value += percentage;
setCharge(value);
}
// Here just some stuff for illustration.
// You don't need those functions to set the charge.
function letsBeginTheShow(buttonElement) {
buttonElement.disabled = true;
setNextCharge(10);
}
function setNextCharge(increment) {
var percentage = parseInt(chargeElement.getAttribute("data-value"))
percentage += increment;
if (percentage > 100) {
percentage = 100;
increment = -5;
}
if (percentage < 0) {
percentage = 0;
increment = 5;
}
setCharge(percentage);
setTimeout(function() {
setNextCharge(increment);
}, 50);
}
setCharge(50);
.battery {
position: relative;
width: 100px;
height: 30px;
border: 1px solid black;
/* Below : only for aestethic reasons */
float: left;
margin-right: 30px;
/* End of aesthethic stuff */
}
#charge {
height: 100%;
position: absolute;
background-color: #3D9970;
border-color: #3D9970;
}
.middle {
border-left: 1px solid;
}
<div class="battery">
<div id="charge" data-value="50" class="middle"></div>
</div>
<button onclick="letsBeginTheShow(this)">Begin the charge variation</button>

HTML element wont stay positioned at bottom

So I have a chat UI that is a box where messages go, and at the bottom of the box of messages is a text input element. It works fine at the beginning, but once enough messages appear then the text input element scrolls up, along with the messages, and will not stay positioned at the bottom. How can I do this? Any useful thoughts would be appreciated.
<html>
<body>
<div id="chatui">
<div id="chatmsgs"></div>
<input type="text" id="chatbox">
</div>
</body>
</html>
Here is my CSS:
#chatui {
z-index:3;
position:absolute;
bottom:5px;
width: 380px;
height: 150px;
border: 3px solid #8AC007;
margin-left:5px;
overflow:auto;
}
#chatbox {bottom:3px;position:absolute;width:378px;}
#chatmsgs {position:absolute;}
Here is my Javascript:
This just says when you press "Enter" on your keyboard to display the text you typed into the "chatmsgs" div.
$(window).keydown(function(e){
if (e.keyCode == 13) {
if (document.activeElement.id == 'chatbox') {
var msg = document.getElementById('chatbox').value;
document.getElementById('chatbox').value = '';
var ms = '<p>'+msg+'</p>';
$('#chatmsgs').append(ms);
}
}
});
Check out this fiddle to see what I am talking about:
https://jsfiddle.net/ev3uymw6/
You have to add overflow:auto and appropriate height to the chatmsgs div, so that it doesn't grow beyond the size of chatui and make it scroll alltogether.
$(window).keydown(function(e) {
if (e.keyCode == 13) {
if (document.activeElement.id == 'chatbox') {
var msg = document.getElementById('chatbox').value;
document.getElementById('chatbox').value = '';
var ms = '<p>' + msg + '</p>';
$('#chatmsgs').append(ms);
}
}
});
#chatui {
z-index: 3;
position: absolute;
bottom: 5px;
width: 380px;
height: 150px;
border: 3px solid #8AC007;
margin-left: 5px;
}
#chatbox {
bottom: 3px;
position: absolute;
width: 378px;
}
#chatmsgs {
position: absolute;
height: 130px;
overflow: auto;
width: 378px
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div id="chatui">
<div id="chatmsgs">
</div>
<input type="text" id="chatbox">
</div>
</body>