I'm trying to create a popup DIV that appear when mouse hover an IMG just to enlarge it and show to the user.
Images are part of a table, so it's difficult for me to obtain it only with HTML and CSS.
Besides, using JS, I'm finding problem to apply the img src (put in a variable) to the backGroundImage url.
This is the code i'm using:
let tableImgs = document.querySelectorAll('.immTable td img');
if (tableImgs) {
popup = document.getElementById('imgBox');
for (let i = 0; i < tableImgs.length; i++) {
tableImgs[i].addEventListener('mouseover', (event) => {
popup.style = `backGroundImage = url('${tableImgs[i].src}')`;
popup.style.top = (getPos(tableImgs[i]).top - getPos(tableImgs[i]).width) + 'px';
popup.style.left = (getPos(tableImgs[i]).left + 40) + 'px';
popup.style.opacity = 1;
// alert('Target: ' + getPos(tableImgs[i]).top + ', ' + getPos(tableImgs[i]).left);
});
tableImgs[i].addEventListener('mouseleave', (event) => {
popup.style = '';
});
}
}
The HTML part is a normal table (here only the more significant part), with at the end the DIV for the popup box ('imgBox' id):
<table class="immTable">
<tr>
<td data-th="id: ">25</td>
<td data-th="titolo: ">Schizzo n. 27, Antigone e suo fratello</td>
<td data-th="anno: ">1985</td>
<td data-th="descrizione: ">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Provident at eligendi, fugit eveniet aliquam.</td>
<td data-th="immagine: " class="immTd">
<img src="https://41.media.tumblr.com/c5d1ac7b9669b3bbb20ebb8444cb702a/tumblr_nxrgstujWX1sfie3io1_1280.jpg">
</td>
</tr>
</table>
<div id="imgBox"></div>
Regarding the CSS part, I think only the popup box style is significant:
#imgBox{
position: absolute;
width: 250px;
height: 250px;
border: 2px solid black;
top: 0;
left: -2000px;
opacity: 0;
transition: opacity 0.5s ease-in-out;
}
So, my problem is that the JS instruction popup.style = `backGroundImage = url('${tableImgs[i].src}')` doesn't set the background, where the other styles (top, left and opacity) apply.
I also tried with different quote marks settings without results.
Where is my mistake?
Related
Hello everyone I need to create 3 different types of dialog boxes for school but the way it's worded I cannot find information online of how to do it. I need to create a sticky popup that is unintrusive! to the screen and untimed. Closed by clicking the x in the popup. I have a growl notification already that is timed. Now I don't even know what to look for as the internet has me going in circles the image I attached best explanation of nitication I need
is the closest description of what I need to create. If anyone can point me in the right direction I would be very grateful.
I tried searching on the internet. I have created a flash notification and can figure out an alert but "sticky" popup dialog box I cannot find. To be able to scroll and have an unintrusive, untimed, notification or dialog box as my school calls them this is the assignmentschool assignment.
One way of doing it with good animations, is to create an element with a position: fixed in CSS.
then push the element outside of the screen by a 100% of it's width with transform: translateX().
then add a class to it that returns the element to its original position with the same CSS function.
you can add or remove the class using JavaScript through an onclick attribute on the HTML element or adding a click listener on the element
const closeElement = document.getElementById('notification');
const toggleNotification = () => {
closeElement.classList[closeElement.classList.contains('open') ? 'remove' : 'add']('open');
}
const closeNotification = () => {
closeElement.classList.remove('open')
}
const openNotification = () => {
closeElement.classList.add('open')
}
* {
box-sizing: border-box;
}
.growl {
position: fixed;
right: 1rem;
bottom: 1rem;
background-color: aquamarine;
min-width: 300px;
min-height: 50px;
padding: 8px;
border-radius: 8px;
transform: translateX(calc(100% + 1rem));
transition: all 0.2s ease;
}
.open {
transform: translateX(0px);
}
.growl .close-btn {
position: absolute;
top: 5px;
right: 8px;
cursor: pointer;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button onclick="openNotification()">Open</button>
<button onclick="toggleNotification()">toggle</button>
<div id="notification" class="growl">
<p>This is a small notification</p>
<span id="close-btn" onclick="closeNotification()" class="close-btn">X</span>
</div>
</body>
</html>
This notification will be at the bottom even if you will scroll.
function addNotification(){
//create notification
const NotiElement = document.createElement("div");
NotiElement.id = "stickyNotification";
NotiElement.style.display = "block";
NotiElement.style.position = "absolute";
NotiElement.style.width = "290px";
NotiElement.style.height = "90px";
NotiElement.style.padding = "10px";
NotiElement.style.borderRadius = "5px";
NotiElement.style.border = "1px solid black";
NotiElement.style.backgroundColor = "red";
NotiElement.style.right = "10px";
NotiElement.style.bottom = "10px";
NotiElement.innerHTML = " <span>Lorem ipsum dolor sit amet consectetur adipisicing elit.Lorem ipsum dolor sit amet consectetur adipisicing elit.</span><div id='closeBtn'>X</div>";
document.body.appendChild(NotiElement);
//keep it always at the bottom corner of the window
document.addEventListener("scroll", (event) => {
let btmPos = -window.scrollY + 10;
NotiElement.style.bottom = btmPos + "px";
});
//add close event to remove child
document.getElementById("closeBtn").addEventListener("click", (event) => {
document.body.removeChild(NotiElement);
});
}
//call function
addNotification();
#stickyNotification #closeBtn{
position: absolute;
top: 0;
right: 0;
padding: 5px;
}
#stickyNotification #closeBtn:hover{
color: white;
cursor: pointer;
}
body{
height: 200vh;
}
You can use window.alert("Hello World") to open a pop up you are trying to define.
<!DOCTYPE html>
<html>
<body>
<p>
Here is your HTML Content
</p>
<div id="pop_up">
<div id="close_pop_up">X</div>
Here is your text
</div>
<style>
#pop_up{
background: gray;
position: absolute;
width: 100px;
height: 100px;
right: 20px;
bottom: 20px;
}
</style>
<script>
const closePopUp = document.getElementById("close_pop_up");
closePopUp.addEventListener("click", () =>{
document.getElementById("pop_up").style.display = "none";
});
</script>
</body>
</html>
In your HTML code you can add a element that have an absolute position and will be your pop-up.
<div id="pop_up">
Here is your text
</div>
#pop_up{
position: absolute;
width: 100px;
height: 100px;
right: 20px;
bottom: 20px;
}
This is the first step if you want a sticky notification on your website.You can change the values of the css above depending on your needs.
Now if you want to close it you need to 1. add you x to you element:
<div id="pop_up">
<div id="close_pop_up">X</div>
Here is your text
</div>
Add a listener with javascript to hide the notification when you cilck on the X.
const closePopUp = document.getElementById("close_pop_up");
closePopUp.addEventListener("click", () =>{
document.getElementById("pop_up").style.display = "none";
});
You can add this script in a <script></script> just before the end on the enclosure tag body of your html.
I am showing a popup on text highlight using JavaScript. But I’m not able to position it at the center of the highlight,
Same as medium.com text highlight popup. I want the .toolbar at the center of the highlighted text like these images below.
const
getRoot = document.querySelector('.root'),
getTool = document.querySelector('.toolbar');
document.addEventListener('mouseup', e => {
window.getSelection().toString().length ?
(
getTool.style.left = e.clientX + 'px',
getTool.style.top = e.clientY + 'px',
getTool.classList.add('active')
) : null;
});
document.addEventListener('mousedown', () => {
window.getSelection().toString().length < 1 ?
getTool.classList.remove('active') : null;
});
*,
*::before,
*::after {
box-sizing: border-box;
}
body {
margin: 0;
}
.root {
max-width: 500px;
margin: 1rem auto;
font-size: 21px;
line-height: 1.8;
font-family: Times new roman;
}
.toolbar {
display: none;
position: absolute;
height: 45px;
width: 220px;
background-color: #212121;
border-radius: .25rem;
transition: .2s;
}
.toolbar.active {
display: block;
}
<div class="toolbar"></div>
<div class="root">
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Quos dignissimos porro explicabo soluta totam illum. Lorem
ipsum dolor sit amet consectetur adipisicing elit. Architecto, sunt.</p>
</div>
Medium.com
Like in this post you should use selection range and range boundingClientRect
document.addEventListener('mouseup', e => {
s = window.getSelection()
oRange = s.getRangeAt(0); //get the text range
oRect = oRange.getBoundingClientRect();
s.toString().length ?
(
getTool.style.left = ((oRect.left + oRect.width / 2) -110) + 'px', // 110 is toolbox.width/2
getTool.style.top = (oRect.top - 45 - 10) + 'px', //45 is toolbow.height
getTool.classList.add('active')
) : null;
});
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 2 years ago.
Improve this question
I've been using jQuery Cycle 2 now for some years, wondering if there is a way to accomplish most of what this does without the need for jQuery? http://jquery.malsup.com/cycle2/faq/
Here is a basic css fade in / fade out cycle transition.
var actual = 0;
var total = 3;
function addClass(elem, name) {
elem.className = elem.className + " " + name;
}
function deleteClass(elem, name) {
var c = elem.className;
elem.className = c.replace(name, "").replace(/ /g, " ").replace(/^ | $/g, "");
}
function nextImg() {
var e;
e = document.getElementById("img" + actual);
deleteClass(e, "visible");
actual++;
if (actual > total - 1) actual = 0;
e = document.getElementById("img" + actual);
addClass(e, "visible");
}
var slider = setInterval(nextImg, 3000);
.slide {
border: none;
opacity: 0;
position: absolute;
top: 0;
left: 0;
-webkit-transition: opacity .300s linear;
-moz-transition: opacity .300s linear;
-o-transition: opacity .300s linear;
transition: opacity .300s linear;
}
.visible {
opacity: 1;
}
<div class="header">
<span id="img0" class="slide visible"><img src="1.jpg">Orlandos studio</span>
<span id="img1" class="slide"><img src="2.jpg">Fida in Van</span>
<span id="img2" class="slide"><img src="3.jpg">Eternalife Productions</span>
</div>
I'm sure there is a shorter way to do this, however, this is my take on it. Does the same operation, just a little bit shorter.
var parent = document.getElementsByClassName("header")[0];
let i = 1;
let l = parent.children.length;
function imgCycle() {
let pre = parent.children[((i - 1) < 0) ? l - 1 : i - 1]; // get previous holder of visible
pre.className = pre.className.replace("visible", "");
let e = parent.children[i];
e.className += "visible";
i = (i + 1) % l; // Make it loop around
}
var slider = setInterval(imgCycle, 3000);
.slide {
border: none;
opacity: 0;
position: absolute;
top: 0;
left: 0;
-webkit-transition: opacity .300s linear;
-moz-transition: opacity .300s linear;
-o-transition: opacity .300s linear;
transition: opacity .300s linear;
}
.visible {
opacity: 1;
}
<div class="header">
<span id="img0" class="slide visible"><img src="1.jpg">Orlandos studio</span>
<span id="img1" class="slide"><img src="2.jpg">Fida in Van</span>
<span id="img2" class="slide"><img src="3.jpg">Eternalife Productions</span>
</div>
Checkout the below libraries:
I have not tried but there are many features, might be useful for you!
https://github.com/ganlanyuan/tiny-slider
https://github.com/gsantiago/vanilla-slider
https://github.com/turivishal/Slide-Projection-Vanilla-JS/tree/0.0.1
I have been working on this Slide-Projection-Vanilla-JS library for the last 2 days and have done some basic things as JQuery Cycle 2 has.
There are no any documentation or readme for now, I will add it soon, but I have added all kind of examples for ready to use.
Below features that relates with Cycle 2 library, for more details you can checkout GitHub Repository,
Next / Prev Controls
Pause on Hover Controls
Caption Controls
Manual Fx Controls
Overlay Options
Speed Option
Auto Play Option
Demo:
.center {
text-align: center;
}
#pauser {
width: 45%;
padding: 30px;
margin: auto;
text-align: center;
font-size: 16px
}
.info {
padding: 5px 2px;
color: #9B4D39;
background: #FCE9E3;
border: solid 1px #FBE1D5;
-webkit-border-radius: 4px;
-moz-border-radius: 4px;
border-radius: 4px
}
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/turivishal/Slide-Projection-Vanilla-JS#0.0.1/build/slide-projection.styles.min.css">
<h3 class="center">Slide Projection (SP)</h3>
<div class="sp-wrapper">
<div
class="sp-slideshow"
data-sp-speed="4000"
data-sp-auto-play="true"
data-sp-fx="slide"
data-sp-fx-next="next-slide"
data-sp-fx-prev="prev-slide"
data-sp-fx-active="active-slide"
data-sp-fx-initial="initial-slide"
data-sp-caption-template="Slide {{slideNum}} of {{slideCount}}">
<!-- empty element for caption -->
<div class="sp-caption"></div>
<div class="sp-overlay"></div>
<div class="sp-slide" data-sp-desc="Lorem ipsum dolor sit amet, consectetur adipiscing elit. In placerat risus bibendum, luctus nunc et, ultricies mauris. Pellentesque sagittis euismod urna">
<img src="https://cdn.jsdelivr.net/gh/turivishal/Slide-Projection-Vanilla-JS#0.0.1/demos/images/sp1.jpg" alt="SP1" />
</div>
<div class="sp-slide" data-sp-desc="Lorem ipsum dolor sit amet, consectetur adipiscing elit.">
<img src="https://cdn.jsdelivr.net/gh/turivishal/Slide-Projection-Vanilla-JS#0.0.1/demos/images/sp2.jpg" alt="SP2" />
</div>
<div class="sp-slide" data-sp-desc="Lorem ipsum dolor sit amet, consectetur adipiscing elit.">
<img src="https://cdn.jsdelivr.net/gh/turivishal/Slide-Projection-Vanilla-JS#0.0.1/demos/images/sp3.jpg" alt="SP3" />
</div>
<div class="sp-slide" data-sp-desc="Lorem ipsum dolor sit amet, consectetur adipiscing elit.">
<img src="https://cdn.jsdelivr.net/gh/turivishal/Slide-Projection-Vanilla-JS#0.0.1/demos/images/sp4.jpg" alt="SP4" />
</div>
<div class="sp-slide" data-sp-desc="Lorem ipsum dolor sit amet, consectetur adipiscing elit.">
<img src="https://cdn.jsdelivr.net/gh/turivishal/Slide-Projection-Vanilla-JS#0.0.1/demos/images/sp5.jpg" alt="SP5" />
</div>
<div class="sp-button-next"></div>
<div class="sp-button-prev"></div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/gh/turivishal/Slide-Projection-Vanilla-JS#0.0.1/build/slide-projection.vanilla.min.js"></script>
Have you seen slendr, it's relatively small and extendable.
Features
Written and tested entirely using Typescript.
Lightweight (just 2KB gzipped UMD)
Responsive (desktop and mobile) by default.
Modern browsers only. No more legacy browsers like IE10 or IE11 (but you can find it on v1.3 release).
High performance by Lighthouse audit.
CSS3
Hardware Acceleration 60fps animation.
Progressive images loading.
Highly customizable.
SASS support.
And it uses minimal markup...
<div class="slendr-slides">
<section class="slendr-slide" data-slide-src="image1.jpg"></section>
<section class="slendr-slide"></section>
<section class="slendr-slide" data-slide-src="image2.jpg"></section>
</div>
check out a demo on codepen
This is a very simple, vanilla js implementation (no library is required). Also, in ES 5 (supported in every browser).
I didn't add images as content as I don't have any, but the ugly demo content still can demonstrate the component.
It only supports crossfade, but you may change it to whatever else in the attached CSS. All you need is, to modify the .crossfade-item and the .crossfade-item.active class rulesets.
The script only adds/removes the active class, prevents the animation from running is the mouse is above the component, and drives the controls.
Usable for multiple sliders on the same page.
var CrossFade = function(selector, interval) {
this.interval = interval || 2000;
this.container = document.querySelector(selector);
this.items = this.container.querySelectorAll('.crossfade-item');
this.leftControl = this.container.querySelector('.control-left');
this.rightControl = this.container.querySelector('.control-right');
this.activeIndex = 0;
this.goNext = function() {
var oldIndex = this.activeIndex;
if (this.activeIndex + 1 > this.items.length - 1) {
this.activeIndex = 0;
} else {
++this.activeIndex;
}
this.items.item(oldIndex).classList.remove('active');
this.items.item(this.activeIndex).classList.add('active');
}.bind(this)
this.goBack = function() {
var oldIndex = this.activeIndex;
if (this.activeIndex - 1 < 0) {
this.activeIndex = this.items.length - 1;
} else {
--this.activeIndex;
}
this.items.item(oldIndex).classList.remove('active');
this.items.item(this.activeIndex).classList.add('active');
}.bind(this)
this.removeTimer = function() {
clearInterval(this.timer);
}.bind(this);
this.setTimer = function() {
this.timer = setInterval(this.goNext, this.interval);
}.bind(this);
this.leftControl.addEventListener('click',this.goBack);
this.rightControl.addEventListener('click', this.goNext);
this.container.addEventListener('mouseover', this.removeTimer);
this.container.addEventListener('mouseout', this.setTimer);
this.setTimer();
}
new CrossFade('#oneCrossFade');
new CrossFade('#twoCrossFade', 3000);
/*chrome, you may set dimensions, positions, etc. here*/
.crossfade {
position: relative;
width: 480px;
height: 120px;
}
.crossfade-item {
position: absolute;
left: 0;
top: 0;
width: 480px;
height: 120px;
z-index: 0;
opacity: 0;
transition: 2s all ease-out;
}
.crossfade-item.active {
z-index: 1;
opacity: 1;
transition: 1s all ease-in;
}
.crossfade-control {
position: absolute;
z-index: 2;
top: calc(50% - 10px);
}
.crossfade-control.control-left {
left: 0;
}
.crossfade-control.control-right {
right: 0;
}
/*content, you may put whatever you want after this point*/
.red {
background-color: red;
}
.green {
background-color: green;
}
.blue {
background-color: blue;
}
.yellow {
background-color: yellow;
color: #000;
}
.cyan {
background-color: cyan;
}
.magenta {
background-color: magenta;
}
.red, .green, .blue, .cyan, .magenta {
color: white;
}
<div class="crossfade" id="oneCrossFade">
<div class="crossfade-item red active">
<h2>A title here 1</h2>
<p>Some longer description comes here 1</p>
</div>
<div class="crossfade-item green">
<h2>A title here 2</h2>
<p>Some longer description comes here 2</p>
</div>
<div class="crossfade-item blue">
<h2>A title here 3</h2>
<p>Some longer description comes here 3</p>
</div>
<button class="crossfade-control control-left">
<
</button>
<button class="crossfade-control control-right">
>
</button>
</div>
<br /> <!-- this to demonstrate the support for multiple "sliders" on the same page -->
<div class="crossfade" id="twoCrossFade">
<div class="crossfade-item magenta active">
<h2>A title here 1</h2>
<p>Some longer description comes here 1</p>
</div>
<div class="crossfade-item yellow">
<h2>A title here 2</h2>
<p>Some longer description comes here 2</p>
</div>
<div class="crossfade-item cyan">
<h2>A title here 3</h2>
<p>Some longer description comes here 3</p>
</div>
<button class="crossfade-control control-left">
<
</button>
<button class="crossfade-control control-right">
>
</button>
</div>
So here is the best answer I could come up with:
First, you create a container with a span and an img.
<div class="container">
<img id="image">
<span id="text"></span>
</div>
Then, you position everything where you want, add some style to everything and create the fade transitions with #keyframes (in this example, I'll position the text and image in the center of the page).
body {
background-color: #000;
height: 100vh;
overflow: hidden;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.container {
width: auto;
height: auto;
padding: 1rem;
display: flex;
flex-direction: row;
align-items: center;
justify-content: center;
}
span {
color: #fff;
font-family: sans-serif;
font-size: 2rem;
margin: 0 1rem;
}
img {
height: 2rem;
width: 2rem;
margin: 0 1rem;
object-fit: cover;
border-radius: 2px;
border: none;
}
#keyframes fade {
0% {
opacity: 0;
}
50% {
opacity: 1;
}
80% {
opacity: 1;
}
100% {
opacity: 0;
}
}
Lastly, you need a function to change the text innerHTML and image src every x seconds.
const text = document.getElementById("text");
const image = document.getElementById("image");
var text_options = ["Orlandos Studio", "Fida in Van", "Eternalife Productions"];
var image_options = [
"http://via.placeholder.com/400x400",
"http://via.placeholder.com/400x400",
"http://via.placeholder.com/400x400"
];
var i = 0;
var j = text_options.length;
text.innerHTML = text_options[I];
image.src = image_options[i];
setInterval(function loop() {
text.innerHTML = text_options[i];
text.style.animation = "fade 3s ease-in-out infinite";
image.src = image_options[i];
image.style.animation = "fade 3s ease-in-out infinite";
i = (i + 1) % j;
}, 3000);
Take a look at my solution on Codepen: https://codepen.io/maxym11/pen/OJMERLJ
Hope it works!
EDIT 1: I realized you wanted to draw attention to
a vanilla javascript alternative to Mals Cycle 2 that has most of the same features, advance slide prev/next, pager, timed, preload,
so I recommend you to check out this tutorial: https://www.w3schools.com/howto/howto_js_slideshow.asp
EDIT 2: Also take a look at this, this, this, and this.
I have managed to do a scrolling effect as you can see in this link here.
On another link(see here) I have another animation that happens on mouse move.
On top of my scrolling effect, I want the first image to have the mouse move effect.
How can I combine that?
I am seeing it quite challenging because the styling for both are completely different. In one template I work actual images in the froont-end but in the other one I work with image background.
JS:
var zoom_value = 1;
var boxFullHeight = $('header').height();
var boxHalfHeight = $('header').height() / 2;
var domHeight = $('html').scrollTop();
//scrollController will check the value when scrolling up or down
var scrollController = 0;
//max number that the scroll happens before images change
var max_scrollController = 4;
//this will enable/disable the scrollbar after a certain period
var controller = 0;
$(window).on('wheel', function(e) {
var delta = e.originalEvent.deltaY;
function add_styling(zoom_value){
$("#firstbox img").css({
"font-size": zoom_value +"px",
"transform": "scale(" + zoom_value + ")",
"transition": "all .9s"
});
}
if (delta > 0 && controller < 10){
controller++;
zoom_value = zoom_value + 0.1;
scrollController++;
add_styling(zoom_value);
if(scrollController >= max_scrollController){
$('.img2').addClass('hide_image');
}
return false;
}
else if(delta < 0) {
if (zoom_value > 1) {
controller--;
zoom_value = zoom_value - 0.1;
scrollController--;
add_styling(zoom_value);
if(scrollController < max_scrollController){
$('.img2').removeClass('hide_image');
}
}
else{
zoom_value = 1;
add_styling(zoom_value);
}
}
});
CSS:
html,body,header, #header_box, .image_box, img {
height: 100%;
}
#firstbox{
background: red;
width: 100%;
}
#second_box{
background: blue;
}
#third_box{
background: black;
}
.general{
width: 100%;
height: 100%;
}
header {
position: relative;
overflow: hidden;
}
.image_box{
position: absolute;
width: 100%;
}
img{
width: 100%;
}
.hide_image {
visibility: hidden;
}
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<div id="firstbox" class="general">
<header>
<div id="header_box">
<div class="image_box">
<img class="img1" src="https://cdn.pixabay.com/photo/2017/03/07/13/38/landscape-2124022_960_720.jpg" alt="image here">
</div>
<div class="image_box box2">
<img class="img2" src="https://cdn.pixabay.com/photo/2017/06/05/20/10/blue-2375119_960_720.jpg" alt="image here">
</div>
</div>
</header>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Alias ut accusamus non error laboriosam in commodi ad, sint, neque voluptates deserunt magnam minima nulla officia nobis fugit enim optio assumenda.</p>
</div>
<div id="second_box" class="general">
</div>
<div id="third_box" class="general">
</div>
</body>
Just add this to your javascript:
$('.box2').on('mousemove', function(e){
var x = e.originalEvent.x,
y = e.originalEvent.y,
w = this.offsetWidth,
h = this.offsetHeight,
targetX = w / 2 - x,
targetY = h / 2 - y;
$(this).css({
'transform': 'scale(1.2) translate(' + targetX/10 +'px, ' + targetY/10 +'px)'
});
});
The width of the element changes as I type text between its tags. My question that I want some kind of relation of Width with Height. As the width gets longer, the height increases by the same but I don't want the height to exceed 35px nor start with below 5px.
The code I tried:
HTML:
<div class="btn bg-red">This buttons width expands as I write more and more text.</div>
CSS:
.btn {
padding-left: 10px;
padding-right: 10px;
display: inline-block !important;
border-radius: 6px;
color: #ffffff;
padding-top: 10px;
padding-bottom: 10px;
height: relative;
}
.bg-red{background-color:#F55C58;}
.bg-red:hover{background-color:#F44946}
I'm not sure if it is possible in CSS to do this.
Then I tried this:
HTML:
<div class="btn bg-red"><div class="auto">This buttons width expands as I write more and more text.</div></div>
CSS:
.btn {
padding-left: 10px;
padding-right: 10px;
display: inline-block !important;
border-radius: 6px;
color: #ffffff;
padding-top: 10px;
padding-bottom: 10px;
}
.auto {
height: 20%
}
.bg-red{background-color:#F55C58;}
.bg-red:hover{background-color:#F44946}
Javascript:
var cw = $('.auto').width();
$('.auto').css({'height':cw+'px'});
The second code doesn't seem to follow display:inline. It works when you change the code manually.
Find demo for First code here.
Find demo for Second code here.
Edit:
Understood Meaning: When the button/element has less text, the width is small and the same way, the height should act same but 20% less pixels. When the text is increased, the width increases and the height should also increase. The max length of Height can reach up to 35px but the Width is Infinite by default.
I don't know how do you add text on your div. Anyway, on the following snippets the eventlistener trigger is set to input since it's a contenteditable div (the text is added by the user throught keyboard).
Snippet #1:
document.getElementsByTagName("body")[0].onload=function(){equalize()};
var target = document.getElementById("target");
target.addEventListener("input", equalize);
function equalize() {
var x = target.offsetWidth;
target.style.height = x + "px";
}
#target {
display: inline-block;
background: skyblue;
}
<div id=target contenteditable="true">write here</div>
This second snippet is the same as the previous one, but now the height is 20% smaller than the width (it was equal on the previous example) plus have a max-height limit of 100px.
Snippet #2:
var target = document.getElementById("target");
document.getElementsByTagName("body")[0].onload=function(){equalize()};
target.addEventListener("input", equalize);
function equalize() {
var x = target.offsetWidth;
var reducedpart = x / 100 * 20;
var result = x - reducedpart;
if (result > 100) {
var result = 100;
}
target.style.height = result + "px";
}
#target {
display: inline-block;
background: skyblue;
}
<div id=target contenteditable="true">write here</div>
Same as before but using padding instead of height to let the text on center:
Snippet #3:
var target = document.getElementById("target");
document.getElementsByTagName("body")[0].onload=function(){equalize()};
target.addEventListener("input", equalize);
function equalize() {
var x = target.offsetWidth;
var reducedpart = x / 100 * 20;
var result = x - reducedpart;
if (result > 100) {
var result = 100;
}
var secresult = result / 2;
target.style.paddingTop = secresult + "px";
target.style.paddingBottom = secresult + "px";
}
#target {
display: inline-block;
background: skyblue;
padding-left: 15px;
padding-right: 15px;
}
<div id=target contenteditable="true">write here</div>
CSS-only workaround using padding instead of height:
Snippet #4:
.container {
vertical-align: bottom;
display: inline-block;
}
#a {
width: 100%;
padding-bottom: calc(80% - 1em);
background: gold;
}
#b {
width: 100%;
padding-top: calc(40% - 0.5em);
padding-bottom: calc(40% - 0.5em);
background: tomato;
}
<div class=container><div id=a contenteditable="true">write here</div></div>
<div class=container><div id=b contenteditable="true">write here</div></div>
In jquery there's a function .height() that get the current computed height for the html element in the given ID or Class. Getting the height value of your div.auto you can monitor the height increase. Given that, you can make a condition if ($('.auto').height() <= 35px) that limit it up to 35px .
Put this <script type="text/javascript" src="jquery-1.12.2.js"></script> in your <head> and that you have the latest JQuery library.
Here's the full implementation of code. Try it in your localhost, because sometimes it doesn't work on jsfiddle or likewise.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style media="screen">
.btn {
padding-left: 10px;
padding-right: 10px;
display: inline-block !important;
border-radius: 6px;
color: #ffffff;
padding-top: 10px;
padding-bottom: 10px;
}
.auto {
height: 20%
}
.bg-red{background-color:#F55C58;}
.bg-red:hover{background-color:#F44946}
</style>
<script type="text/javascript" src="jquery-1.12.2.js"></script>
</head>
<body>
<div class="btn bg-red"><div class="auto">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</div></div>
<script type="text/javascript">
var cw = $('.auto').width();
if ($('.auto').height() <= 35px) {
$('.auto').css({'height':cw+'px'});
}
</script>
</body>
</html>
Hope this will help