How to link text to mouse pointer? - javascript

I'm trying to make text that follows my mouse pointer, but getting some troubles.
I'm using fullscreen div to take available space on page to make mouse event working for entire page.
Also using position: absolute to place one div on another. date-and-time is used to create text that follows the mouse.
I've tried almost anything I can but it didn't work and now I'm here.
html
<body>
<div id="fullscreen"></div>
<div id="date-and-time"></div>
<script src="./script.js"></script>
</body>
javascript
const dateAndTime = document.getElementById('date-and-time');
dateAndTime.innerText = new Date();
document.addEventListener("mousemove", function(e) {
dateAndTime.style.left = e.clientX;
dateAndTime.style.top = e.clientY;
});
css
div {
position: absolute;
}
#fullscreen {
width: 100%;
height: 100%;
left: 0;
top: 0;
background-color: yellow;
}
Problem is that text just ignores my mouse, but if I move pointer to left corner text gets moved to X=0 (maybe it's not actually but it worked that way before)

You are missing px for the postion values.
You are assigning the left and right position values to the node without px.
What happens when you move to left most position? Simple at that time the value will be 0. That will work without any unit.
div {
position: absolute;
}
#fullscreen {
width: 100%;
height: 100%;
left: 0;
top: 0;
background-color: yellow;
}
<body>
<div id="fullscreen"></div>
<div id="date-and-time"></div>
</body>
<script>
const dateAndTime = document.getElementById("date-and-time");
dateAndTime.innerText = new Date();
document.addEventListener("mousemove", function(e) {
dateAndTime.style.left = e.clientX + 'px';
dateAndTime.style.top = e.clientY + 'px';
});
</script>

Related

How do I make one div scroll slower or faster than other items on the page, using pure CSS or CSS/JS (without JQuery)?

All I want is to do is to make one element on the page (a div is easiest) scroll slower or faster than the other items on the page. For example, when scrolling, this particular div will move at 50% or 200% of the speed of the other items, etc.
It seems like such a simple, straightforward thing, but I can't find any examples of this. Also, I don't want to use JQuery, someone else's sketchy / overly complicated 3rd party plugin, etc. Just simple, clean, CSS and JS.
Ok, so thanks #ajaypane for the answer, but I actually figured out an even simpler way of doing this. I can't believe that nobody has done this - it's far less complicated than everything else I've seen.
JS
function parallax() {
var s = document.getElementById("floater");
var yPos = 0 - window.pageYOffset/5;
s.style.top = 50 + yPos + "%"; }
window.addEventListener("scroll", function(){
parallax();
});
CSS
.section { position: relative; width: 100vw; height: 15vw; }
.object-in-3d {
margin-left: 45vw;
width: 10vw;
height: 10vw;
background-color: #41ebf4; }
.float-center {
position: absolute;
top: 50%; }
#red { background-color: #f44141; }
#yellow { background-color: #f48342; }
#green { background-color: #f4dc41; }
#floater {}
HTML
<div class="section" id="red"> </div>
<div class="section" id="yellow">
<div class="object-in-3d float-center" id="floater"> </div>
</div>
<div class="section" id="green"> </div>
It's in codepen, here:
https://codepen.io/escapetomars/pen/EeLmpp
So I have managed to come up with this which is not too complex, however, it does scroll relative to the users scroll speed, but does work with scroll wheel, scrollbars, and keyboard.
It also scrolls up and down.
You can change the speed to suit your needs, but 10 worked for keeping it pretty much in view all the way down for my scroll speed, but left it behind when faster or using Page Down.
document.addEventListener("DOMContentLoaded", function DomContentLoaded(){
//Get the element you want to slow down;
var slowDiv = document.getElementById('slowDiv');
//Set its style.top to be the offsetTop so if style.top is not set, it will still work.
slowDiv.style.top = slowDiv.offsetTop + 'px';
//set the last scrollTop to use for direction
var lastScrollTop = 0;
//Get the element you are scrolling against
var relativeSpeedDiv = document.getElementById('main');
var moveLittle = function MoveLittle(speed, scrollY) {
//Get the current top of the slow element
var topVal = parseInt(slowDiv.style.top);
//Check scroll direction
if (isScrollingDown(scrollY)) {
topVal = topVal + speed;
} else {
topVal = topVal - speed;
}
//Set new top of slow element
slowDiv.style.top = topVal + 'px';
};
var isScrollingDown = function IsScrollingDown(scrollY) {
var retVal = false;
if (scrollY > lastScrollTop) {
retVal = true;
}
lastScrollTop = scrollY;
return retVal;
};
window.onscroll = function WindowScroll() {
//Send speed and current scroll Y
moveLittle(10, this.scrollY);
}
});
.biggestBig {
margin: auto;
align-self: center;
width: 90%;
min-height: 9999em;
}
.faded {
background: linear-gradient(gray, black);
}
.slow {
width: 2em;
height: 2em;
background-color: #ee9b0b;
position: absolute;
}
<div id="mainDiv" class="biggestBig faded">
<div id="slowDiv" class="slow"></div>
</div>

Fix an element when it reaches the top of the screen using javascript and css

I have an element, that I wish to stick on top after it reaches the top of the screen.
<div id="HeaderWrapper">
...
<div id="Navigation">
Navigation
</div>
...
</div>
I am adding an event listener on scroll, which would call a function to check the posting of the element by using getBoundingClientRect() method. If the top or the y of the element is less then 0 relative to the viewport, then I would like to fix/stick the header. Again if its more than 0 then I would like to remove the fix position. In both the cases, I am adding and removing a class name of fixed_navbar which has the property of fix position.
document.addEventListener("scroll", function() {
const el = document.getElementById("Navigation");
let rect = el.getBoundingClientRect();
if (rect.top <= 0) {
el.classList.add("fixed_navbar");
} else {
el.classList.remove("fixed_navbar");
}
});
You can also the check the codepen demo.
When the position top of the element is more than zero it works fine. Also when scrolling down to the position where the element's top position is less than 0 it sticks to the page and has the fixed propery. But again when scrolling back to the position when the element's top is more than 0, the element still has the fixed propery and stick's to the top of the screen. How can I make the element stick to the top when it reaches the top of the screen and again when the element is below the top of the screen remove the fixed postion?
You can achieve this with CSS alone, by using:
position: sticky
When declaring position: sticky; you will also need to declare a top style (eg. top: 0;) to indicate at which point you want the element to become "stuck".
Working Example:
header {
height: 600px;
}
.navigation {
position: sticky;
top: 0;
margin-top: 150px;
}
<header>
<div class="navigation">Navigation</div>
</header>
Further Information:
position: sticky works in the following browsers:
https://caniuse.com/#feat=css-sticky
Try This
if (rect.top <= 0) {
In if condition you write rect.top < 0 that is wrong for your requirement
#Rounin provide an awesome solution. Although I fix your issue in JavaScript. you can check this
document.addEventListener("scroll", function() {
const el = document.getElementById("Navigation");
let rect = el.getBoundingClientRect();
if (rect.top <= 0) {
el.classList.add("fixed_navbar");
} else {
window.onscroll = function() {myFunction()};
function myFunction() {
if ( document.body.scrollTop < 100 ) {
el.classList.remove("fixed_navbar");
}
}
}
});
* {
margin: 0;
padding: 0;
}
#HeaderWrapper {
background: lightgrey;
height: 1500px;
}
.box {
background: skyblue;
width: 100%;
height: 100px;
}
#Navigation {
background: green;
}
.fixed_navbar {
position: fixed;
z-index: 1000;
width: 100%;
left: 0;
top: 0;
}
<div id="HeaderWrapper">
<div class="box"></div>
<div id="Navigation">
Navigation
</div>
</div>

How to move content along with window resize so that it appears in the same position?

I have a page with a grid containing three div elements. Each one of this div has the size of the viewport so at any time just one of the divs if visible and the other two are outside. So the grid is three times big the viewport.
Resizing the window will cause the divs, hence the grid, to resize as well.
The html is pretty simple:
<div class="container">
<div class="square square1">1</div>
<div class="square square2">2</div>
<div class="square square3">3</div>
</div>
Styled like this:
body {
margin: 0;
padding: 0;
}
.container {
position: relative;
height: 100vh;
width: 300vw;
}
.square {
height: 100vh;
position: absolute;
width: 100vw;
}
.square1 {
background: red;
left: 0;
}
.square2 {
background: green;
left: 100vw;
}
.square3 {
background: yellow;
left: 200vw;
}
The initial position, set via javascript, is on the middle div.
What happens is that resizing the window makes the whole document to move proportionally with the resizing. So, if at some point I'm seeing just the second div, resizing the window will make the third to appear more and more.
I'm quite sure that with some javascript I could move the grid so that it appears fixed while resizing, but I can't figure out a formula.
I tried something like this:
var windowW = $(window).width();
$(window).resize(function() {
var newWidth = $(window).width();
var diff = windowW - newWidth;
var windowLeftPos = $(window).scrollLeft();
$(window).scrollLeft(windowLeftPos - diff / 2);
});
But it's just a blind guess. I tried other formulas with multiplication and division and scale factors, but nothing worked.
Any idea?
Here's a working example showing what I mean.
Initially you see just the green div. Resizing the window, on of the two other divs will appear, instead I would like to see only the green one.
Edit: the question similar to mine is very interesting but it seems to me also very different. The main huge difference is that I'm resizing and moving DOM elements that stay outside the viewport. Besides, the answers are pretty focused on the image/background aspect ratio, which is part of the question, but it's not the case for me. I don't have a problem resizing elements, just compensating the movement due to the resizing
Update: I edited the pen and I think I'm getting closer to the desired result: http://codepen.io/anon/pen/vGeRgJ
It seems to kind of work, but it doesn't especially when I'm closer to one of the extremes, like all on the left or on the right.
Here is an updated version for you, from where you can easily make your own adjustments.
Since jQuery doesn't throttle the resize event by default, I made this one in plain javascript.
To get rid of the vertical scroll, and I also added a getScrollbarSize function as a bonus :)
function getWidth() { return window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth; }
function getLeft() { return document.body.scrollLeft; }
function setLeft(v) { document.body.scrollLeft = v; }
function getScrollbarSize() {
var div, width;
div = document.createElement('div');
div.innerHTML = '<div style="width:50px;height:50px;position:absolute;left:-50px;top:-50px;overflow:auto;"><div style="width:1px;height:100px;"></div></div>';
div = div.firstChild;
document.body.appendChild(div);
width = div.offsetWidth - div.clientWidth;
document.body.removeChild(div);
return width;
};
(function(t,w,l,l2) {
document.querySelector('.container').style.height = 'calc(100vh - ' + getScrollbarSize() + 'px)';
w = getWidth(), l = w, l2 = l / w, setLeft(w);
window.addEventListener("resize", function(e) {
if ( !t ) {
t = setTimeout(function() {
t = null;
resizeHandler(e);
}, 66); /* throttle timeout */
}
}, false);
function resizeHandler(e) {
w = getWidth();
l = getLeft();
setLeft(w * l2);
}
window.addEventListener("scroll", function(e) {
if ( !t ) {
l2 = getLeft() / w;
}
}, false);
}());
body {
margin: 0;
padding: 0;
}
.container {
position: relative;
height: 100vh;
width: 100vw;
}
.square {
height: 100%;
position: absolute;
width: 100vw;
}
.square1 {
background: red;
left: 0;
}
.square2 {
background: green;
left: 100%;
}
.square3 {
background: yellow;
left: 200%;
}
<div class="container">
<div class="square square1">1</div>
<div class="square square2">2</div>
<div class="square square3">3</div>
</div>

Why positioning element next to mouse cursor is so "laggy"?

https://jsfiddle.net/m0zwwav4/
html:
<div id="container"></div>
<div id="tooltip">Tooltip!</div>
css:
#container {
width: 500px;
height: 500px;
border: solid 1px red;
}
#tooltip {
position: absolute;
}
js:
var container = document.getElementById('container')
var tooltip = document.getElementById('tooltip')
container.onmousemove = function(event) {
tooltip.style.left = (event.pageX + 20) + 'px'
tooltip.style.top = event.pageY + 'px'
}
When I move cursor inside red box, tooltip seems to be little bit laggy (there is a little delay) - testing in chrome on max os. Is there any trick to make it faster to make it look like moving exactly fast as mouse cursor?
You can do this without JavaScript.
Change the container's cursor to a URL, which is an image containing the tooltip text:
You can do this using a Data URI:
#container {
cursor: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEoAAAAZCAIAAAAZqC9/AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAIPSURBVFhH5Zg7csIwEIZxzgKp0kCH6KCCg0BBAQV0KdOFwpTQ5QapcAUdLqFhUgB3cX5Ji2T5IRNjBsb5ZjLj1YqVPz1sT5wgCCrl5QV/jDHHcfb7vWwqE1wP7Ha7yWRSPkPSA+v1ejgclsxQ6wHf90u2hoYewBqWyTCqBx5l6A3wgHOcgUdxESToAYuhvIckWvMz9bkfNAVXD5WsB/6+hm+vVboqhoTVPB8PdHUlqXog0XCB7wDBqi/i/oriYNEVDfekOtqKobajK2fSpgfynMPzvCWmXRLdR/bsBb5yvaW4XPZCHc0VlbWQChU1K6bqdTod2X+z2TQaDWrNgo9TG/sUcfxxTe0vezYvqBEqiihUMKoHK7VW+JQRW4EjW7LwPuU4lx17chkPlx9iSu1Zgy7OgLH77duRuSfeiX4RKmjowQ1rRUEOvG+xn5g7pWNYHb2LEf2fU1b2Bpj7JeW7UzlhuqDWg9tsNsMcyMN2w9vP/ggt+gFrhfRwuuBWr9dleBuHo9psCU9ye7ZosFzNZjN8zEC73ZYt6iJO7MWgDpNupD4ytmfjBSmmcyUx+6iK5tnTJQKuFyennh7AQN3gVVldMNzdFIjqmYRuKVkPZBrG7oaIjBnJW7IJBbWgTY+5K13VHC+/3hOg9Gj946TqAYjhx8/qBrL1Ur9aAN4N6FHQ4/Qx/IP/lJWYUutVKr8O6jUK23d1QgAAAABJRU5ErkJggg==), auto;
}
Fiddle

How to user controlled overlap images in JS

I'm desperately searching for solution for my client. I have graphic - something like that:
And I want to be able to take the line with circle in the center and drag it to right or left. And it will be hiding and unhiding my two full images. It's basically two images on the same place, just with another z-index I think.
I think it's possible to do it with JavaScript, but I don't know of any functions or methods for this option.
Here is my solution:
The HTML is pretty simple, just two divs for the images and one for the drag:
<div class="img" id="img1"></div>
<div class="img" id="img2"></div>
<div id="drag"></div>
For the CSS, the important part is to absolute position all the divs and give a background image.
As for the Javascript, with a little help from jQuery, we listen for the mouse events, make some calculations and adjust the CSS of the second image:
$('#drag').on('mousedown', function(e){
var $self = $(this),
dragPos = $self.position().left + $self.width()/2,
imgWidth = $('#img1').width();
$(document).on('mouseup', function(e){
$(document).off('mouseup').off('mousemove');
});
$(document).on('mousemove', function(me){
var mx = me.pageX - e.pageX + dragPos
$self.css({ left: mx });
$('#img2').css({
width: imgWidth - mx,
left: mx,
backgroundPosition: -mx + 'px 0px',
});
});
});
From there, I believe it's pretty easy to customize it and give it a unique look.
Hope this helps!
JsFiddle Demo
Something like this alphamask plugin may do the trick, though I'm not sure how simple it would be for you to implement in the manner of your slider example.
Actually quite simple. The first step is to make it work manually. I'd set it up as follows:
<div class="wrap" id="wrap1">
<div class="img-wrap img1"></div>
<div class="img-wrap img2"></div>
<div>
With CSS as follows:
.wrap {
position: relative;
width: 300px;
height: 300px;
}
.img-wrap {
width: 100%;
height: 100%;
position: absolute;
top: 0px;
left: 0px;
}
.img1 {
z-index: 1;
background: url(bg1.png) no-repeat 0px 0px;
}
.img2 {
z-index: 2;
background: url(bg1.png) no-repeat 0px 0px;
}
Now some JavaScript (with jQuery) to set a position (you can call this when you move a slider over the top later):
function setPosition(percentage){
// get the width of the container
var w = $('#wrap1').width();
// work out the width of left panel
var w1 = Math.floor(w * percentage);
// and the right panel
var w2 = w - w1;
// set the width of the right panel
// move it right by the width of the left panel
// and move the background back by the width of the left panel
$('#wrap1 .img2').css({
width: w2,
left: w1,
backgroundPosition: -w1 + 'px 0px',
});
}
You now just have to decide how to do the dragging. You could even just do it on mouseOver. Easy!

Categories

Resources