I have this HTML that renders a simple arrow sign pointing towards the right:
<!DOCTYPE html>
<html>
<head>
<style>
div { width: 0px; height: 0px; border-left: 20px solid black; border-top: 20px solid transparent; border-bottom: 20px solid transparent; border-right: 20px solid transparent; position: absolute; left: 35px; top: 53px; cursor: pointer; }
</style>
<body>
<div></div>
</body>
</html>
If you hover of it, the cursor turns to pointer. But because it is actually a square div, the cursor turns pointer even if you are just outside the arrow within the perimeter of the div.
So I wrote this Javascript addition such that the cursor turns pointer only when the mouse is hovering over that arrow. For this purpose, I figured the coordinates of the three vertices of the triangle from Firebug ((35,53),(55,73),(35,93) clockwise from top). Then I check whether the point in question lies inside the triangle formed by these 3 vertices. This I do by checking whether the point and the opposite vertex for each edge lies on the same side of that edge or not (if they do, the product of the values obtained by substituting the coordinates of that point for x and y in that equation will be positive).
<!DOCTYPE html>
<html>
<head>
<style>
div { width: 0px; height: 0px; border-left: 20px solid black; border-top: 20px solid transparent; border-bottom: 20px solid transparent; border-right: 20px solid transparent; position: absolute; left: 35px; top: 53px; }
.hoverclass { cursor: pointer; }
</style>
<script src="jquery.js">
</script>
<script>
$(document).ready(function(){
$("div").click(function(e) { alert(e.pageX + " " + e.pageY); });
function l1(x,y) { return y - x - 18; }
function l2(x,y) { return x+y-128; }
function l3(x,y) { return x-35; }
$("div").hover(function(e) {
var x = e.pageX;
var y = e.pageY;
if (l1(x,y)*l1(35,93) >= 0 && l1(x,y)*l1(35,93) >= 0 && l1(x,y)*l1(35,93) >= 0 ) {
$(this).addClass('hoverclass');
}
else { $(this).removeClass('hoverclass'); }
},
function() {
$(this).removeClass('hoverclass');
});
});
</script>
<body>
<div></div>
</body>
</html>
However, the results are not predictable. Sometimes the cursor turns pointer within the triangle only, sometimes outside as well (just as before), and sometimes not at all. I suspect that this is probably due to the hover function working overtime, that may be temporarily hanging the script. Is there any other way to achieve this?
This could be done using HTML5 canvas. Basic idea is to check for pixel color on mousemove on canvas element. This way, your element can be of any form as you wish. Of course, you should make some optimization of following code:
SEE WORKING DEMO
function findPos(obj) {
var curleft = 0, curtop = 0;
if (obj.offsetParent) {
do {
curleft += obj.offsetLeft;
curtop += obj.offsetTop;
} while (obj = obj.offsetParent);
return { x: curleft, y: curtop };
}
return undefined;
}
// set up triangle
var example = document.getElementById('example');
var context = example.getContext('2d');
context.fillStyle = '#000';
context.strokeStyle = '#f00';
context.lineWidth = 1;
context.beginPath();
// Start from the top-left point.
context.moveTo(10, 10); // give the (x,y) coordinates
context.lineTo(60, 60);
context.lineTo(10, 120);
context.lineTo(10, 10);
// Done! Now fill the shape, and draw the stroke.
// Note: your shape will not be visible until you call any of the two methods.
context.fill();
context.stroke();
context.closePath();
$('#example').mousemove(function(e) {
var pos = findPos(this);
var x = e.pageX - pos.x;
var y = e.pageY - pos.y;
var coord = "x=" + x + ", y=" + y;
var c = this.getContext('2d');
var p = c.getImageData(x, y, 1, 1).data;
if(p[3]!='0') $(this).css({cursor:'pointer'});
else $(this).css({cursor:'default'});
});
You'd better use CSS instead. With :before and :after pseudo classes you can do magic. Check out this Pure CSS GUI icons by Nicolas Gallagher.
If you use any CSS pre-processor, these icons can be wrapped up as a mixin, this way required properties can be assigned like this:
#icon > .close(16px, #fff, #E83921);
You can make any shape have cursor pointer with CSS only. The idea is to rotate wrapper container which has overflow: hidden (you can have several of them depending on the shape you need). In case of OP problem this code does a trick:
<div class="arrow"><i></i></div>
.arrow {
margin: 100px;
border_: 1px red solid;
width: 40px;
height: 40px;
overflow: hidden;
-webkit-transform: rotate(45deg);
transform: rotate(45deg);
}
.arrow i {
height: 65px;
width: 65px;
background-color: green;
content: '';
display: block;
cursor: pointer;
margin: -35px 0 0 11px;
-webkit-transform: rotate(45deg);
transform: rotate(45deg);
}
See this demo: http://cssdesk.com/PaB5n
True that this requires CSS transform support so it's not cross browser.
Related
hello everyone hope you guys are having a great day!
so, i am building a simple game where I use a custom-made cursor as the aim for shooting div elements moving around the screen as the enemies and when i apply the "pointerdown" event i want the enemy to change its color. however, every time i hover over the enemy the cursor falls behind witch i don't understand why, and when i use the z-index property it will prevent the "pointerdown" event from firing. if some cool OG programmer can help me, it would mean a lot to me.
style
* {
margin: 0;
padding: 0;
cursor: none;
}
.aim {
position: absolute;
background: black;
width: 10px;
height: 10px;
border-radius: 50%;
transform: translate(-50%, -50%);
}
.enemy {
position: absolute;
border: 3px solid black;
background-color: blue;
width: 50px;
height: 50px;
}
javascript
const body = document.body;
const aim = document.createElement("div");
const enemy = document.createElement("div");
body.appendChild(aim);
body.appendChild(enemy);
aim.classList.add("aim");
enemy.classList.add("enemy");
let enemy_X_position = 0;
let enemy_Y_position = 0;
let enemy_X_distance = 1;
let enemy_Y_distance = 1;
function Flight()
{
enemy.style.left = enemy_X_position + "px";
enemy.style.top = enemy_Y_position + "px";
}
setInterval(function()
{
enemy_X_position += enemy_X_distance;
enemy_Y_position += enemy_Y_distance;
if ((enemy_X_position + enemy.offsetWidth) >= window.innerWidth || enemy_X_position <= 0)
enemy_X_distance = -enemy_X_distance;
if ((enemy_Y_position + enemy.offsetHeight) >= window.innerHeight || enemy_Y_position <= 0)
enemy_Y_distance = -enemy_Y_distance;
Flight();
},1000/60)
window.onmousemove = function()
{
aim.style.left = event.pageX + "px";
aim.style.top = event.pageY + "px";
}
enemy.onpointerdown = function()
{
event.target.style.background = "red";
}
enemy.onpointerup = function()
{
event.target.style.background = null;
}
Update
The event is not triggering because pointerdown was received by aim when it sits on top of enemy.
To solve this, add pointer-events: none on aim class to prevent it from being the target of a pointer event.
More about pointer-events
Hope this will help!
.aim {
position: absolute;
background: black;
width: 10px;
height: 10px;
border-radius: 50%;
transform: translate(-50%, -50%);
pointer-events: none;
}
Original
Perhaps an over simplified solution, but it seems that if you reverse the order of appendChild, the aim should be stacked over enemy without additional styling.
Example:
body.appendChild(enemy);
body.appendChild(aim);
Because both elements are child of body, Unless there is other styling that override this stacking, the later one should be on top.
I am attempting to emulate Medium style comments in an html document.
This answer has gotten me nearly there: How to implement Medium-style commenting interface in VueJS
With that method, I can highlight text and make comments, but I want to display the coments on the same line as the range the commenter selected. The code as I have treats every paragraph it seems as a separate document, such that I don't know how to return to the correct paragraph to find the original range being commented on.
Here is the commenting component:
<template>
<div class="popup" :style="{top: offsetTop, left: offsetLeft}" ref="popup">
<span #click="AlertSelectedText">Comment</span>
</div>
</template>
<script>
export default {
data() {
return {
popupInitialTopOffset: 0,
popupInitialLeftOffset: 0,
offsetTop: 0,
offsetLeft: "-999em",
selectedText: undefined
};
},
methods: {
ListenToDocumentSelection() {
let sel = window.getSelection();
console.log('sel is: ', sel)
setTimeout(_ => {
if (sel && !sel.isCollapsed) {
this.selectedText = sel.toString();
if (sel.rangeCount) {
let range = sel.getRangeAt(0).cloneRange();
console.log('range is: ', range)
if (range.getBoundingClientRect) {
var rect = range.getBoundingClientRect();
console.log('boundingrect is: ', rect)
let left = rect.left + (rect.right - rect.left) / 2;
let top = rect.top;
this.offsetTop = top - this.popupInitialTopOffset - 30 + "px";
this.offsetLeft = left - this.popupInitialLeftOffset / 2 + "px";
}
}
} else {
this.offsetLeft = "-999em";
}
}, 0);
},
AlertSelectedText() {
alert(`"${this.selectedText}" posted as comment`);
}
},
mounted() {
this.popupInitialTopOffset = this.$refs.popup.offsetHeight;
this.popupInitialLeftOffset = this.$refs.popup.offsetWidth;
console.log('this is the positions of the popup', this.popupInitialTopOffset, this.popupInitialLeftOffset);
window.addEventListener("mouseup", this.ListenToDocumentSelection);
},
destroyed() {
window.removeEventListener("mouseup", this.ListenToDocumentSelection);
}
};
</script>
<style scoped>
.popup {
position: absolute;
color: #FFF;
background-color: #000;
padding: 10px;
border-radius: 5px;
transform-origin: center, center;
cursor: pointer;
}
.popup:after {
content: "";
border-bottom: 5px solid #000;
border-right: 5px solid #000;
border-top: 5px solid transparent;
border-left: 5px solid transparent;
position: absolute;
top: calc(100% - 5px);
transform: rotate(45deg);
left: calc(50% - 3px);
}
</style>
if I could know how to add coordinates for returning to the commented range, I think I could manage the rest.
Wherever you want to enable commenting, try giving those elements a class and a unique ID.
A class would help you identify that it has commenting enabled whereas an ID would help you uniquely identify it.
In your logic, you can access the list of classes on that element as
sel.anchorNode.parentElement.classList
and ID as
sel.anchorNode.parentElement.id
With the help of this combination, you can surely associate a comment to your elements.
I have two elements, and one is moving towards the other. I am trying to get the new distance as it moves closer. Consider the code below:
<html>
<center>
<body onload = 'start()'>
<div class='field'>
<div id='bull'></div>
<div id='mount'></div>
</div>
<button id='one'>DO</button>
</body>
</center>
<style>
.field{
width: 440px;
height: 260px;
background: rgba(0, 0, 0, .2);
margin-top: 30px;
border: 1px solid #222;
border-radius: 10px;
}
#bull{
width: 15px;
height: 10px;
background: #000;
border-top-right-radius: 5px;
border-bottom-right-radius: 5px;
position: absolute;
}
#mount{
width: 60px;
height: 30px;
background: rgba(20, 10, 45);
color: #fff;
border-radius: 4px;
margin-top: 210px;
}
</style>
<script type='text/javascript'>
function start() {
var ball = document.getElementById('bull');
var button = document.getElementById('one');
var mount = document.getElementById('mount');
button.addEventListener('click', go);
var x_pos = 0;
var y_pos = 0;
var bounce_point = 200;
var ball_dim = ball.getBoundingClientRect();
var ball_h_half = ball_dim.width / 2;
var ball_w_half = ball_dim.height / 2;
var mount_dim = mount.getBoundingClientRect();
var mount_h_half = mount_dim.width / 2;
var mount_w_half = mount_dim.height / 2;
function go() {
for(x_pos = 0; bounce_point > x_pos; x_pos++) {
ball.style.margin = x_pos + "px";
ball.style.transition = x_pos/2 + "s";
var dist = ((ball_h_half - mount_h_half)*(ball_w_half - mount_w_half)) + ((mount_h_half - ball_h_half)*(mount_w_half - ball_w_half));
console.log(dist);
if(dist < 3) {
console.log('One');
}
}
}
}
</script>
When bull reaches comes within 3px of mount, nothing happens... I've pretty much explained the issue as best as I can.
**
When bull reaches comes within 3px of mount, nothing happens... I've pretty much explained the issue as best as I can.**
Well i tried a little bit more, and your logic doens't seem to fit to what you want to do. First of all, you probably noticed your value in the log doesn't change.
It could have been because the values are retreived outside the loop, but not only (they actually have to be in the loop to be updated). You have 2 other problems: first, you are measuring the elements width and height, which don't take account of margin or other positioning. Your elements don't change size, so the value also won't. The other problem is actually the transition itself on the movement. Because of the delay, all your loop iterations are most probably done, and the margin already set to its final value when your "bull" effectively starts to move. It means that in the loop, you can't detect the position change, the element having not started to move yet. Using the value that was just set (margin) instead of detecting the real position of the element should show a progression for the value, but it makes harder to detect the collision because your 2 elements don't have the same positioning rules and you can't just compare the margins.
Here is a quick example that gets updated values (because the transition has been disabled, if you enable back, the problem comes again). You'll notice your calculation for the collision is wrong too. You can't just compare a distance between 2 corners for that, for a rectangle it's rather "has gone beyond left vertical edge AND has gone beyond top horizontal edge" (this of course takes only in account the top left corner, to be complete, it should also be added that it must not have reached the right or bottom edge yet).
Well, I can't propose you an all ready solution, but this addresses your code main issues:
<html>
<center>
<body onload = 'start()'>
<div class='field'>
<div id='bull'></div>
<div id='mount'></div>
</div>
<button id='one'>DO</button>
</body>
</center>
<style>
.field{
width: 440px;
height: 260px;
background: rgba(0, 0, 0, .2);
margin-top: 30px;
border: 1px solid #222;
border-radius: 10px;
}
#bull{
width: 15px;
height: 10px;
background: #000;
border-top-right-radius: 5px;
border-bottom-right-radius: 5px;
position: absolute;
}
#mount{
width: 60px;
height: 30px;
background: rgba(20, 10, 45);
color: #fff;
border-radius: 4px;
margin-top: 210px;
}
</style>
<script type='text/javascript'>
function start() {
var ball = document.getElementById('bull');
var button = document.getElementById('one');
var mount = document.getElementById('mount');
button.addEventListener('click', go);
var x_pos = 0;
var y_pos = 0;
var bounce_point = 200;
var ball_dim, ball_x, ball_y, mount_dim, mount_x, mount_y, diff_x, diff_y;
var stayInLoop = true;
//ball.style.transition = "0.4s"; //i don't know why you updated the transition time based on position, changed to a fixed value outside the loop because it's quicker for the example
function go() {
for(x_pos = 0; bounce_point > x_pos && stayInLoop; x_pos++) {
ball_dim = ball.getBoundingClientRect();
ball_y = ball_dim.top + 10; // +10 because we're considering the bottom edge of bull
ball_x = ball_dim.left + 15; // +15 because we're considering the right edge of bull
mount_dim = mount.getBoundingClientRect();
mount_y = mount_dim.top;
mount_x = mount_dim.left;
diff_x = mount_x - ball_x;
diff_y = mount_y - ball_y;
console.log(diff_x, diff_y);
ball.style.margin = x_pos + "px";
if(diff_x < 3 && diff_y < 3) {
console.log('One');
stayInLoop = false;
}
}
}
}
</script>
EDIT/SUGGESTION: i suggest looking at window.requestAnimationFrame() MDN doc here for a better control on animations
Please run the snippet and drag you mouse over the bar to make it red.
If you drag the mouse very slowly, you will fill it red, but if you move it fast, there will be white holes in it.
How to fix it? (the white holes)
I want to make a bar divided into 500 parts and if you hover it, it becomes red and being able to drag fast and fill it without holes.
Any help appreciated :)
$(function() {
var line = $("#line");
for ( var i = 0; i < 500; i++) {
line.append('<div class="tile" id="t'+(i+1)+'"></div>');
}
var tile = $(".tile");
tile.hover (
function() { //hover-in
$(this).css("background-color","red");
},
function() { //hover-out
}
);
});
#line{
height: 50px;
background-color: #000;
width: 500px;
}
.tile {
height: 50px;
float: left;
background-color: #ddd;
width: 1px;
}
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<div id="line"></div>
With your design one way would be to iterate over the first to your current hovered element and fill it, which would lead no spaces. That said you may want to consider using the HTML5 Canvas and drawing a rectangle from 0 to your mouse position, which will perform significantly faster.
$(function() {
var line = $("#line");
for ( var i = 0; i < 500; i++) {
line.append('<div class="tile" id="t'+(i+1)+'"></div>');
}
var tile = $(".tile");
tile.hover (
function() { //hover-in
var self = this;
$("#line").children().each(function(){
$(this).css("background-color","red");
if(this == self) return false;
});
},
function() { //hover-out
}
);
});
#line{
height: 50px;
background-color: #000;
width: 500px;
}
.tile {
height: 50px;
float: left;
background-color: #ddd;
width: 1px;
}
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<div id="line"></div>
Edit
Below is an example doing the same task but using the HTML 5 Canvas:
$("#line").mousemove(function(e){
var canvas = $(this)[0];
var ctx = canvas.getContext("2d");
var rect = canvas.getBoundingClientRect()
var x = e.clientX - rect.left;
ctx.fillStyle="red";
ctx.fillRect(0, 0, x, canvas.height);
});
#line{ background-color: #ddd; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="line" width=500 height=50 ></canvas>
This is another approach with nextUntil to select siblings..
$(function() {
var line = $("#line");
for ( var i = 0; i < 500; i++) {
line.append('<div class="tile" id="t'+(i+1)+'"></div>');
}
var tile = $(".tile");
line.on( 'mouseover', function(ev){
$('.tile').first().nextUntil( $('.tile').eq(ev.pageX) ).css("background-color","red");
});
line.on( 'mouseleave', function(ev){
$('.tile').css("background-color","#ddd");
});
});
#line{
height: 50px;
background-color: #000;
width: 500px;
}
.tile {
height: 50px;
float: left;
background-color: #ddd;
width: 1px;
}
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<div id="line"></div>
Another solution makes use of jQuery's mousemove method. This allows the bar to go both forward and backwards, simply following the cursors position.
This detects movement inside of the div, then I calculate the position of the cursor within the div as a percentage and apply it as the width of the red bar.
$( ".bar" ).mousemove(function( event ) {
var xCord = event.pageX;
xPercent = (xCord + $('.pct').width()) / $( document ).width() * 100;
$('.pct').width(xPercent+'%');
});
.bar{
background:'#999999';
width:50%;
height:50px;
}
.pct{
height:100%;
background:red;
width:0%;
}
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js">
</script>
<div class="bar" style="background:#999999">
<div class="pct"></div>
</div>
I need help for an effect I'm trying to create: I made a CSS triangle and I want it to be fixed on the Y-axis but follow the mouse on his X-axis (didn't you read the title ?!). If it's not clear, I want it to move only to the left/right but not up/down. I managed to apply a js script I found on the internet to my triangle but I can't figure out how to change it to stop it from moving on the Y-axis. When I try to change anything, the whole thing doesn't move anymore. Can some one help me ?
// Here get the Div that you want to follow the mouse
var div_moving = document.getElementById('div_moving');
// Here add the ID of the parent element
var parent_div = 'parent_div';
// object to make a HTML element to follow mouse cursor ( http://coursesweb.net/ )
var movingDiv = {
mouseXY: {}, // will contain the X, Y mouse coords inside its parent
// Get X and Y position of the elm (from: vishalsays.wordpress.com/ )
getXYpos: function(elm) {
x = elm.offsetLeft; // set x to elm’s offsetLeft
y = elm.offsetTop; // set y to elm’s offsetTop
elm = elm.offsetParent; // set elm to its offsetParent
//use while loop to check if elm is null
// if not then add current elm’s offsetLeft to x, offsetTop to y and set elm to its offsetParent
while(elm != null) {
x = parseInt(x) + parseInt(elm.offsetLeft);
y = parseInt(y) + parseInt(elm.offsetTop);
elm = elm.offsetParent;
}
// returns an object with "xp" (Left), "=yp" (Top) position
return {'xp':x, 'yp':y};
},
// Returns object with X, Y coords inside its parent
getCoords: function(e) {
var xy_pos = this.getXYpos(e.target);
// if IE
if(navigator.appVersion.indexOf("MSIE") != -1) {
var standardBody = (document.compatMode == 'CSS1Compat') ? document.documentElement : document.body;
x = event.clientX + standardBody.scrollLeft;
y = event.clientY + standardBody.scrollTop;
}
else {
x = e.pageX;
y = e.pageY;
}
x = x - xy_pos['xp'];
y = y - xy_pos['yp'];
return {'xp':x, 'yp':y};
}
};
// registers 'mousemove' event to parent_div
document.getElementById(parent_div).addEventListener('mousemove', function(e){
mouseXY = movingDiv.getCoords(e);
div_moving.style.left = mouseXY.xp + 8 +'px';
div_moving.style.top = mouseXY.yp - 8 +'px';
});
#parent_div {
position: relative;
width: 100%;
height: 800px;
margin: 1em auto;
border; 1px solid #333;
background: #fefebe;
}
#div_moving {
position: absolute;
width: 41em;
height: 31em;
margin: 0;
border: 1px solid #33f;
background: #88ee99;
overflow:hidden;
}
.container {
width: 37.5em;
height: 37.5em;
position: relative;
border-top: 20px solid #e74c3c;
left:3%;
}
.triangle {
position: relative;
margin: auto;
top: -20em;
left: 0;
right: 0;
width:31em;
height:31em;
transform: rotate(45deg);
-webkit-transform: rotate(45deg);
-moz-transform: rotate(45deg);
-o-transform: rotate(45deg);
-ms-transform: rotate(45deg);
border-right: 20px solid #e74c3c;
border-bottom: 20px solid #e74c3c;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="parent_div">
<div id="div_moving">
<div class="container">
<div class="triangle"></div>
</div>
</div>
Content in parent ...
</div>
I just reformatted a little, then commented one line and it's working in Chrome on my machine. Is this what you're looking for?
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script language="javascript">
// object to make a HTML element to follow mouse cursor ( http://coursesweb.net/ )
var movingDiv = {
mouseXY: {}, // will contain the X, Y mouse coords inside its parent
// Get X and Y position of the elm (from: vishalsays.wordpress.com/ )
getXYpos: function(elm) {
x = elm.offsetLeft; // set x to elm’s offsetLeft
y = elm.offsetTop; // set y to elm’s offsetTop
elm = elm.offsetParent; // set elm to its offsetParent
//use while loop to check if elm is null
// if not then add current elm’s offsetLeft to x, offsetTop to y and set elm to its offsetParent
while(elm != null) {
x = parseInt(x) + parseInt(elm.offsetLeft);
y = parseInt(y) + parseInt(elm.offsetTop);
elm = elm.offsetParent;
}
// returns an object with "xp" (Left), "=yp" (Top) position
return {'xp':x, 'yp':y};
},
// Returns object with X, Y coords inside its parent
getCoords: function(e) {
var xy_pos = this.getXYpos(e.target);
// if IE
if(navigator.appVersion.indexOf("MSIE") != -1) {
var standardBody = (document.compatMode == 'CSS1Compat') ? document.documentElement : document.body;
x = event.clientX + standardBody.scrollLeft;
y = event.clientY + standardBody.scrollTop;
}
else {
x = e.pageX;
y = e.pageY;
}
x = x - xy_pos['xp'];
y = y - xy_pos['yp'];
return {'xp':x, 'yp':y};
}
};
$(document).ready(function() {
// Here get the Div that you want to follow the mouse
var div_moving = document.getElementById('div_moving');
// Here add the ID of the parent element
var parent_div = 'parent_div';
// registers 'mousemove' event to parent_div
document.getElementById(parent_div).addEventListener('mousemove', function(e){
mouseXY = movingDiv.getCoords(e);
div_moving.style.left = mouseXY.xp + 8 +'px';
//div_moving.style.top = mouseXY.yp - 8 +'px';
});
});
</script>
<style>
#parent_div {
position: relative;
width: 100%;
height: 800px;
margin: 1em auto;
border; 1px solid #333;
background: #fefebe;
}
#div_moving {
position: absolute;
width: 41em;
height: 31em;
margin: 0;
border: 1px solid #33f;
background: #88ee99;
overflow:hidden;
}
.container {
width: 37.5em;
height: 37.5em;
position: relative;
border-top: 20px solid #e74c3c;
left:3%;
}
.triangle {
position: relative;
margin: auto;
top: -20em;
left: 0;
right: 0;
width:31em;
height:31em;
transform: rotate(45deg);
-webkit-transform: rotate(45deg);
-moz-transform: rotate(45deg);
-o-transform: rotate(45deg);
-ms-transform: rotate(45deg);
border-right: 20px solid #e74c3c;
border-bottom: 20px solid #e74c3c;
}
</style>
</head>
<body>
<div id="parent_div">
<div id="div_moving">
<div class="container">
<div class="triangle"></div>
</div>
</div>
Content in parent ...
</div>
</body>
</html>
Differences:
Load the JQuery script first
Process the listener in a ready function so all the content has been loaded
Comment out the Y positioning
EDIT: I found a solution to my problem.
So here the problems and what I did:
I wanted the object to move only on X-axis and not Y: IgnusFast found out the line to delete was "div_moving.style.top = mouseXY.yp - 8 +'px';"
I wanted it to stop staggering when the mouse passed over it: deleted "parseInt(x) +" in "while(elm != null) {x = parseInt(x) + parseInt(elm.offsetLeft); elm = elm.offsetParent;}" (makes the div stay where it is when not sure.
I wanted it to center with the mouse instead of being on its right: original was " div_moving.style.left = mouseXY.xp + 8 +'px';" wich made it go 8 pixels to the right of the current mouse's coordinates so I just used a negative number and place like this :" div_moving.style.left = mouseXY.xp + -350 +'px';"