I'm trying to show HTML code inside a tooltip (div, table,...), but it doesn't show up and it doesn't show any errors.
If I use the <span> tag with some text inside it, it works correctly. But I need to insert more HTML code inside it. How can I fix it?
Only works with <span> tag, and I don't know how to solve this problem, any help? Why is this happening?
$(document).ready(function() {
//Tooltips
$(".tip_trigger").hover(function(){
tip = $(this).find('.tip');
tip.show(); //Show tooltip
}, function() {
tip.hide(); //Hide tooltip
}).mousemove(function(e) {
var mousex = e.pageX + 20; //Get X coodrinates
var mousey = e.pageY + 20; //Get Y coordinates
var tipWidth = tip.width(); //Find width of tooltip
var tipHeight = tip.height(); //Find height of tooltip
//Distance of element from the right edge of viewport
var tipVisX = $(window).width() - (mousex + tipWidth);
//Distance of element from the bottom of viewport
var tipVisY = $(window).height() - (mousey + tipHeight);
if ( tipVisX < 20 ) { //If tooltip exceeds the X coordinate of viewport
mousex = e.pageX - tipWidth - 20;
} if ( tipVisY < 20 ) { //If tooltip exceeds the Y coordinate of viewport
mousey = e.pageY - tipHeight - 20;
}
tip.css({ top: mousey, left: mousex });
});
});
body {
margin: 0; padding: 0;
font: normal 12px Verdana, Geneva, sans-serif;
line-height: 1.8em;
color: #333;
}
* {
outline: none;
}
img {border: none;}
a {color: #d60000; text-decoration: none;}
/*--Tooltip Styles--*/
.tip {
display: inline-block;
color: #fff;
background:#1d1d1d;
display:none; /*--Hides by default--*/
padding:10px;
position:absolute; z-index:1000;
-webkit-border-radius: 3px;
-moz-border-radius: 3px;
border-radius: 3px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<p style="text-align:left;">My First
<a href="#" class="tip_trigger">Link
<span class="tip">
Some text. Works correctly!
</span>
</a>
</p>
<p style="text-align:left;">My Second
<a href="#" class="tip_trigger">Link
<div class="tip">
<table><tr><td>More text. Doesn't work!</td></tr></table>
</div>
</a>
</p>
Your issue is with the type of elements you put inside of other elements.
For example:
You can not put a <div> inside of an <a> or a <p>
See here: Putting <div> inside <p> is adding an extra <p>
I updated your example code with a working one.
$(document).ready(function() {
//Tooltips
$(".tip_trigger").hover(function(){
tip = $(this).siblings('.tip');
tip.show(); //Show tooltip
}, function() {
tip.hide(); //Hide tooltip
}).mousemove(function(e) {
var mousex = e.pageX + 20; //Get X coodrinates
var mousey = e.pageY + 20; //Get Y coordinates
var tipWidth = tip.width(); //Find width of tooltip
var tipHeight = tip.height(); //Find height of tooltip
//Distance of element from the right edge of viewport
var tipVisX = $(window).width() - (mousex + tipWidth);
//Distance of element from the bottom of viewport
var tipVisY = $(window).height() - (mousey + tipHeight);
if ( tipVisX < 20 ) { //If tooltip exceeds the X coordinate of viewport
mousex = e.pageX - tipWidth - 20;
} if ( tipVisY < 20 ) { //If tooltip exceeds the Y coordinate of viewport
mousey = e.pageY - tipHeight - 20;
}
tip.css({ top: mousey, left: mousex });
});
});
body {
margin: 0; padding: 0;
font: normal 12px Verdana, Geneva, sans-serif;
line-height: 1.8em;
color: #333;
}
* {
outline: none;
}
img {border: none;}
a {color: #d60000; text-decoration: none;}
/*--Tooltip Styles--*/
.tip {
display: none;
color: #fff;
background:#1d1d1d;
display:none; /*--Hides by default--*/
padding:10px;
position:absolute; z-index:1000;
-webkit-border-radius: 3px;
-moz-border-radius: 3px;
border-radius: 3px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<p style="text-align:left;">My First
<a href="#" class="tip_trigger">Link
</a>
<span class="tip">
Some text. Works correctly!
</span>
</p>
<div style="text-align:left;">My Second
Link
<div class="tip">
<table><tr><td>More text. Doesn't work!</td></tr></table>
</div>
</div>
Related
I wanted to recreate the text colour overlay clip-path effect from this site http://fleurmoreau.fr/
I made a version here https://codepen.io/Kerrys7777/pen/eYOrwbV. It seems to work OK, but hovering some areas seems to cause a bubbling effect? What can I change to make it smooth and functional?
I was following the tutorial https://www.youtube.com/watch?v=l_ahowxmqzg but using pure JavaScript.
I think the 'mouseout' function/method is causing this (bubbling) issue?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<link rel="stylesheet" href="css/normalize.css" type="text/css" media="all">
<style>
#import url('https://fonts.googleapis.com/css?family=Cormorant+Garamond:300,700|Titillium+Web:200,400,400i,700&display=swap');
:root {
--maskX: 0;
--maskY: 50;
}
*,*:before,*:after {
box-sizing: border-box;
}
body {
font-family: 'Titillium Web', sans-serif;
font-size: 18px;
line-height: 1.4;
color: #161B1E;
}
h1,
h2,
h3,
h4
{
font-family: 'Cormorant Garamond', serif;
margin: 0;
}
h1 {
font-size: 15vw;
}
#titleContainer {
position: relative;
margin: 100px 0 0 50px;
display: inline-block;
}
p {
margin-left: 80px;
font-size: 1em;
}
.titleWrapper {
cursor: pointer;
color: #D4BBAB;
padding: 30px;
/*--maskX: 0;
--maskY: 50;*/
}
.cloneWrapper {
position: absolute;
top: 0;
left: 0;
color:#f2dcca;
/*clip-path: polygon(0 0, calc(var(--maskX) * 1%) 0, calc(var(--maskY) * 1%) 100%, 0% 100%);*/
transition: all 0.8s cubic-bezier(0.165,0.84,0.44,1);
clip-path: polygon(0 0,calc(var(--maskX) * 1% + (var(--maskY) - 50) * .4%) 0,calc(var(--maskX) * 1% + (var(--maskY) - 50) * -.4%) 100%,0 100%)
}
</style>
</head>
<body>
<section id="titleContainer">
<div class="titleWrapper">
<h1>Text Effect</h1>
</div>
<div class="titleWrapper cloneWrapper">
<h1>Text Effect</h1>
</div>
</section>
<p>Mouse over the rectangle above, and get the coordinates of your mouse pointer.</p>
<p id="demo"></p>
<script>
//GET MOUSE POSITION RELATIVE TO THIS ELEMENT
var titleContainerBox = document.getElementById("titleContainer");
//ADD EVENT (MOUSEMOVE) LISTENER
titleContainerBox.addEventListener("mousemove", function(event) {
mousePosMove(event);
});
//ADD EVENT (RESIZE) LISTENER
titleContainerBox.addEventListener("resize", function(event) {
mousePosMove(event);
});
/*['mousemove','resize'].forEach( evt =>
titleContainerBox.addEventListener(evt, mousePosMove(event), false)
);*/
function mousePosMove(e) {
//GET CONTAINER DIMENSIONS
var rect = titleContainerBox.getBoundingClientRect();
var width = titleContainerBox.clientWidth;
var height = titleContainerBox.clientHeight;
//MOUSE POSITION PX INSIDE titleContainer
var x = e.clientX - rect.left;
var y = e.clientY - rect.top;
//MOUSE POSITION PERCENTAGE INSIDE titleContainer
var oX = Math.floor((x/width) * 100);
var oY = Math.floor((y/height) * 100);
//UPDATE CSS VARIABLES
titleContainerBox.style.setProperty('--maskX', oX);
titleContainerBox.style.setProperty('--maskY', oY);
//SHOW INFO IN PAGE
var mouseCoordinates = "Coordinates: (" + x + ", " + y + ")" + "<br>" + " Dimensions: (" + width + ", " + height + ")" + "<br>" + " Percentage relative position: (" + oX + ", " + oY + ")";
document.getElementById("demo").innerHTML = mouseCoordinates;
}
//ADD EVENT (MOUSEOUT) LISTENER TO REMOVE EFFECT
titleContainerBox.addEventListener("mouseout", function(event) {
mousePosOut(event);
});
function mousePosOut(e) {
//SET CSS VARIABLES TO ZERO (REMOVE EFFECT)
setTimeout(function() {
titleContainerBox.style.setProperty('--maskX', 0); //-16 VALUE TO CORRECT CORNER ISSUE
titleContainerBox.style.setProperty('--maskY', 0);
}, 1000);
}
</script>
</body>
</html>
BTW where has the live example code setup window gone here at SO?
The mouseout event was causing the issue. Changed to mouseleave and some other minor tweaks. Seems to work fine now.
//GET MOUSE POSITION RELATIVE TO THIS ELEMENT TO FEED CLIP-PATH CSS VARIABLE VALUES
var titleContainerBox = document.getElementById("titleContainer");
//ADD EVENT (MOUSEMOVE) LISTENER
titleContainerBox.addEventListener("mousemove", function(event) {
mousePosMove(event);
});
//ADD EVENT (RESIZE) LISTENER
titleContainerBox.addEventListener("resize", function(event) {
mousePosMove(event);
});
/*['mousemove','resize'].forEach( evt =>
titleContainerBox.addEventListener(evt, mousePosMove(event), false)
);*/
function mousePosMove(e) {
//GET CONTAINER DIMENSIONS
var rect = titleContainerBox.getBoundingClientRect();
var width = titleContainerBox.clientWidth;
var height = titleContainerBox.clientHeight;
//MOUSE POSITION PX INSIDE titleContainer
var x = e.clientX - rect.left;
var y = e.clientY - rect.top;
//MOUSE POSITION PERCENTAGE INSIDE titleContainer
var oX = Math.floor((x/width) * 100);
var oY = Math.floor((y/height) * 100);
//UPDATE CSS VARIABLES
titleContainerBox.style.setProperty('--maskX', oX);
titleContainerBox.style.setProperty('--maskY', oY);
//SHOW INFO IN PAGE
var mouseCoordinates = "Coordinates: (" + x + ", " + y + ")" + "<br>" + " Dimensions: (" + width + ", " + height + ")" + "<br>" + " Percentage relative position: (" + oX + ", " + oY + ")";
document.getElementById("demo").innerHTML = mouseCoordinates;
}
//ADD EVENT (MOUSEOUT) LISTENER TO REMOVE EFFECT
titleContainerBox.addEventListener("mouseleave", function( event ) {
//SET CSS VARIABLES TO ZERO AFTER A SHORT DELAY
setTimeout(function() {
titleContainerBox.style.setProperty('--maskX', -16);
titleContainerBox.style.setProperty('--maskY', 0);
}, 700);
}, false);
#import url('https://fonts.googleapis.com/css?family=Cormorant+Garamond:300,700|Titillium+Web:200,400,400i,700&display=swap');
:root {
--maskX: 0;
--maskY: 50;
}
*,*:before,*:after {
box-sizing: border-box;
}
body {
font-family: 'Titillium Web', sans-serif;
font-size: 18px;
line-height: 1.4;
color: #161B1E;
}
h1,
h2,
h3,
h4
{
font-family: 'Cormorant Garamond', serif;
margin: 0;
}
h1 {
font-size: 15vw;
}
#titleContainer {
position: relative;
z-index: 3;
margin: 100px 0 0 50px;
}
p {
margin-left: 80px;
font-size: 1em;
}
.titleWrapper {
cursor: pointer;
color: #D4BBAB;
padding: 30px;
/*--maskX: 0;
--maskY: 50;*/
}
.cloneWrapper {
position: absolute;
top: 0;
left: 0;
color:#f2dcca;
/*clip-path: polygon(0 0, calc(var(--maskX) * 1%) 0, calc(var(--maskY) * 1%) 100%, 0% 100%);*/
transition: all 0.8s cubic-bezier(0.165,0.84,0.44,1);
clip-path: polygon(0 0,calc(var(--maskX) * 1% + (var(--maskY) - 50) * .4%) 0,calc(var(--maskX) * 1% + (var(--maskY) - 50) * -.4%) 100%,0 100%)
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Clip Path Text Colour Effect</title>
</head>
<body>
<section id="titleContainer">
<div class="titleWrapper">
<h1>Text Effect</h1>
</div>
<div class="titleWrapper cloneWrapper">
<h1>Text Effect</h1>
</div>
</section>
<p>Mouse over the rectangle above, and get the coordinates of your mouse pointer.</p>
<p id="demo"></p>
</body>
</html>
I have a table full of data that tends to be larger than the screen.
I put the table in a DIV and set the "overflow" to "auto" in CSS
div.scrolling-comps {
width : 970px;
height : 800px;
overflow : auto;
}
So the DIV can be scrolled up/down, left right using the browser's built-in scroll bars.
Problem is, the table can be WAAY bigger than the screen. And while the mousewheel will scroll it up/down, scrolling left/right is a pain in the hooch.
So, looking for a javascript/jquery or CSS way to scroll the div NATURALLY.
In other words, when someone viewing the huuuge table moves their mouse to the right, the DIV goes to the left (thus scrolling without using the scroll bars).
Something similar to this, but instead of following the mouse, the div would move opposite the mouse...
window.onload = function() {
var bsDiv = document.getElementById("box-shadow-div");
var x, y;
// On mousemove use event.clientX and event.clientY to set the location of the div to the location of the cursor:
window.addEventListener('mousemove', function(event) {
x = event.clientX;
y = event.clientY;
if (typeof x !== 'undefined') {
bsDiv.style.left = x + "px";
bsDiv.style.top = y + "px";
}
}, false);
}
#box-shadow-div {
position: fixed;
width: 1000px;
height: 800px;
border-radius: 0%;
background-color: black;
box-shadow: 0 0 10px 10px black;
top: 49%;
left: 48.85%;
}
<div id="box-shadow-div"></div>
The example you have about using the mouse position is interesting... But it is not what you need to achieve what you described.
In fact... What you need to know is the "ratio" between the div wrapping the table and its scrollWidth
Then, using the X position of the mouse, you can apply a scroll to the div in order to make it "move".
I used jQuery to do it using very few lines.
// Just to fake a big table
var fakeCell = $("<td>Some data</td>");
for(i=0;i<100;i++){
var fakeRow = $("<tr>");
for(k=0;k<50;k++){
fakeRow.append(fakeCell.clone().append(" "+k));
}
$("#test").append(fakeRow.clone());
}
// ---------------------------------------------------
// Calculate the "ratio" of the box-div width versus its scrollable width
var ratio = $("#box-div")[0].scrollWidth / $("#box-div").width();
console.log("Ratio: "+ratio);
// Scroll left/rigth based on mouse movement
$(window).on("mousemove", function(e){
var X = ratio * e.pageX;
// Scroll the div using the mouse position multiplyed by the ratio
$("#box-div").scrollLeft(X);
});
td{
white-space: nowrap;
border: 1px solid black;
}
#box-div{
overflow:auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div id="box-div">
<table id="test">
</table>
</div>
</body>
So while the user moves the mouse over the div's width, you apply a scroll multiplied by the ratio... The effect is the user can scroll it all from the most left to most right ends easilly.
How about this?
wrap a table in div (i.e. parent-div) which is relatively positioned
Give position absolute to the target div.
And change left & top position of target div on mousemove event.
window.onload = function() {
var bsDiv = document.getElementById("box-shadow-div");
var x, y;
// On mousemove use event.clientX and event.clientY to set the location of the div to the location of the cursor:
window.addEventListener('mousemove', function(event) {
x = event.clientX;
y = event.clientY;
if (typeof x !== 'undefined') {
bsDiv.style.left = -x + "px";
bsDiv.style.top = -y + "px";
}
}, false);
}
.parent-div {
position: relative;
}
#box-shadow-div {
position: absolute;
width: 1000px;
height: 800px;
border-radius: 0%;
background-color: black;
box-shadow: 0 0 10px 10px black;
top: 0;
left: 0;
}
<div class="parent-div">
<div id="box-shadow-div"></div>
</div>
Have you tried changing x to -x? this will technically "invert" the effect.
window.onload = function() {
var bsDiv = document.getElementById("box-shadow-div");
var x, y;
// On mousemove use event.clientX and event.clientY to set the location of the div to the location of the cursor:
window.addEventListener('mousemove', function(event) {
x = event.clientX;
y = event.clientY;
if (typeof x !== 'undefined') {
bsDiv.style.left = -x + "px";
bsDiv.style.top = -y + "px";
}
}, false);
}
#box-shadow-div {
position: fixed;
width: 1000px;
height: 800px;
border-radius: 0%;
background-color: black;
box-shadow: 0 0 10px 10px black;
top: 49%;
left: 48.85%;
}
<div id="box-shadow-div"></div>
I have three buttons for instance. On hover each I calculate the x and y axis of the mouse using jQuery and show a border to the hovered element. For individual elements, the hovering works fine. But for child elements, only the parent element shows border. The code used for the sample.
$(document).ready(function(){
$(document).mousemove(function(event){
$(".button").removeClass('active')
$('.button').each(function(){
var position = $(this).position();
var width = $(this).width()
var height = $(this).height()
var x1 = position.left
var y1 = position.top
var x2 = x1+width
var y2 = y1+height
if (event.pageX > x1 && event.pageX < x2 && event.pageY > y1 && event.pageY < y2){
$("span").text(event.pageX + ", " + event.pageY);
$(this).addClass('active')
}
});
});
});
.button{
width:150px;
height:35px;
display:block;
position:absolute;
pointer-events: none;
border:1px solid transparent;
}
.button.x{ top:10%; left;35%;}
.button.y{top:40%; left;35%;}
.button.z{top:20%; left;35%;}
.button.active{
border-color:blue;
pointer-events: auto;
border:1px solid;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="button x">
Hello
<div class="button y">
Hello
</div>
</div>
<div class="button z">
Hello
</div>
<span></span>
It's a common mistake, due in part to the naming of the jQuery methods involved (IMHO). You're using position ("Get the current coordinates...relative to the offset parent.") where you want to use offset ("Get the current coordinates...relative to the document."):
var position = $(this).offset();
Updated Example (easiest to see if you hit the Full Page link) (I've also added backgrounds to the nested elements and tweaked the border that gets added, to make it clearer when the mouse is over them):
$(document).ready(function(){
$(document).mousemove(function(event){
$(".button").removeClass('active')
$('.button').each(function(){
var position = $(this).offset();
var width = $(this).width()
var height = $(this).height()
var x1 = position.left
var y1 = position.top
var x2 = x1+width
var y2 = y1+height
if (event.pageX > x1 && event.pageX < x2 && event.pageY > y1 && event.pageY < y2){
$("span").text(event.pageX + ", " + event.pageY);
$(this).addClass('active')
}
});
});
});
.button{
width:150px;
height:35px;
display:block;
position:absolute;
pointer-events: none;
border:1px solid transparent;
}
.button.x{ top:10%; left;35%;}
.button.y{top:40%; left;35%;}
.button.z{top:20%; left;35%;}
.button.active{
pointer-events: auto;
border:2px solid red;
}
.button.x {
background-color: #00d;
}
.button.y {
background-color: #0d0;
}
<div class="button x">
Hello
<div class="button y">
Hello
</div>
</div>
<div class="button z">
Hello
</div>
<span></span>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script>
Or do it with CSS:
.button:hover {
border-color:blue;
pointer-events: auto;
border:1px solid;
}
(And remove pointer-events: none; from .button.)
Live Example (with the same visibility tweaks):
.button{
width:150px;
height:35px;
display:block;
position:absolute;
/*pointer-events: none;*/
border:1px solid transparent;
}
.button.x{ top:10%; left;35%;}
.button.y{top:40%; left;35%;}
.button.z{top:20%; left;35%;}
.button:hover {
pointer-events: auto;
border:2px solid red;
}
.button.x {
background-color: #00d;
}
.button.y {
background-color: #0d0;
}
<div class="button x">
Hello
<div class="button y">
Hello
</div>
</div>
<div class="button z">
Hello
</div>
<span></span>
I want to build a page to show a blown-up version of an image.
I have the smaller image and the bigger image built out. I am not sure how to build the in between portion that looks like rays coming out of the smaller image.
HTML
<div class="flex">
<div class="exp" tabindex="0">
<img class="image" src="http://via.placeholder.com/50x50">
</div>
<div class="big-image">
<img class="image" src="http://via.placeholder.com/350x550">
</div>
</div>
CSS
.exp {
margin: 5px;
width: 100px;
height: 100px;
background-color: #ded3c0;
border-radius: 100%;
line-height: 80px;
align-items: center;
display: flex;
justify-content: center;
}
.exp .image {
width: 50px;
height: 50px;
}
.big-image {
border: 1px solid #000;
padding: 20px;
border-radius: 19px;
}
.flex {
display: flex;
align-items: center;
justify-content: space-around;
}
Any pointers on how to do this is helpful.
Here is jsfiddle https://jsfiddle.net/npkeq7ut/
If you need only lines you can achieve this with JS and skew transform:
let topLine = document.getElementById('top-line');
let bottomLine = document.getElementById('bottom-line');
function updateLines()
{
let b = document.getElementById('b').getBoundingClientRect();
let a = document.getElementById('a').getBoundingClientRect();
let left = a.right;
let width = b.left - a.right;
let tHeight = a.top - b.top;
let tTop = tHeight / 2 + b.top;
let tAngle = Math.atan(tHeight / width) * 180 / Math.PI;
let bHeight = b.bottom - a.bottom;
let bTop = bHeight / 2 + a.bottom - bottomLine.offsetHeight;
let bAngle = Math.atan(bHeight / width) * 180 / Math.PI;
topLine.style.top = tTop + "px";
topLine.style.left = left + "px";
topLine.style.width = width + "px";
topLine.style.transform = "skewY("+(-tAngle)+"deg)";
bottomLine.style.top = bTop + "px";
bottomLine.style.left = left + "px";
bottomLine.style.width = width + "px";
bottomLine.style.transform = "skewY("+(bAngle)+"deg)";
}
updateLines();
Fiddle: https://jsfiddle.net/JacobDesight/f40yeuqe/2/
#EDIT
If you want trapeze with background then here is example using canvas: https://jsfiddle.net/JacobDesight/f40yeuqe/3/
This could be a starting point for you.
Code by thecodeplayer.
http://thecodeplayer.com/walkthrough/magnifying-glass-for-images-using-jquery-and-css3
$(document).ready(function() {
var native_width = 0;
var native_height = 0;
//Now the mousemove function
$(".magnify").mousemove(function(e) {
//When the user hovers on the image, the script will first calculate
//the native dimensions if they don't exist. Only after the native dimensions
//are available, the script will show the zoomed version.
if (!native_width && !native_height) {
//This will create a new image object with the same image as that in .small
//We cannot directly get the dimensions from .small because of the
//width specified to 200px in the html. To get the actual dimensions we have
//created this image object.
var image_object = new Image();
image_object.src = $(".small").attr("src");
//This code is wrapped in the .load function which is important.
//width and height of the object would return 0 if accessed before
//the image gets loaded.
native_width = image_object.width;
native_height = image_object.height;
} else {
//x/y coordinates of the mouse
//This is the position of .magnify with respect to the document.
var magnify_offset = $(this).offset();
//We will deduct the positions of .magnify from the mouse positions with
//respect to the document to get the mouse positions with respect to the
//container(.magnify)
var mx = e.pageX - magnify_offset.left;
var my = e.pageY - magnify_offset.top;
//Finally the code to fade out the glass if the mouse is outside the container
if (mx < $(this).width() && my < $(this).height() && mx > 0 && my > 0) {
$(".large").fadeIn(100);
} else {
$(".large").fadeOut(100);
}
if ($(".large").is(":visible")) {
//The background position of .large will be changed according to the position
//of the mouse over the .small image. So we will get the ratio of the pixel
//under the mouse pointer with respect to the image and use that to position the
//large image inside the magnifying glass
var rx = Math.round(mx / $(".small").width() * native_width - $(".large").width() / 2) * -1;
var ry = Math.round(my / $(".small").height() * native_height - $(".large").height() / 2) * -1;
var bgp = rx + "px " + ry + "px";
//Time to move the magnifying glass with the mouse
var px = mx - $(".large").width() / 2;
var py = my - $(".large").height() / 2;
//Now the glass moves with the mouse
//The logic is to deduct half of the glass's width and height from the
//mouse coordinates to place it with its center at the mouse coordinates
//If you hover on the image now, you should see the magnifying glass in action
$(".large").css({
left: px,
top: py,
backgroundPosition: bgp
});
}
}
})
})
/*Some CSS*/
* {
margin: 0;
padding: 0;
}
.magnify {
width: 200px;
margin: 50px auto;
position: relative;
}
/*Lets create the magnifying glass*/
.large {
width: 175px;
height: 175px;
position: absolute;
border-radius: 100%;
/*Multiple box shadows to achieve the glass effect*/
box-shadow: 0 0 0 7px rgba(255, 255, 255, 0.85), 0 0 7px 7px rgba(0, 0, 0, 0.25), inset 0 0 40px 2px rgba(0, 0, 0, 0.25);
/*Lets load up the large image first*/
background: url('http://thecodeplayer.com/uploads/media/iphone.jpg') no-repeat;
/*hide the glass by default*/
display: none;
}
/*To solve overlap bug at the edges during magnification*/
.small {
display: block;
}
<!-- Lets make a simple image magnifier -->
<div class="magnify">
<!-- This is the magnifying glass which will contain the original/large version -->
<div class="large"></div>
<!-- This is the small image -->
<img class="small" src="http://thecodeplayer.com/uploads/media/iphone.jpg" width="200"/>
</div>
<!-- Lets load up prefixfree to handle CSS3 vendor prefixes -->
<script src="http://thecodeplayer.com/uploads/js/prefixfree.js" type="text/javascript"></script>
<!-- You can download it from http://leaverou.github.com/prefixfree/ -->
<!-- Time for jquery action -->
<script src="http://thecodeplayer.com/uploads/js/jquery-1.7.1.min.js" type="text/javascript"></script>
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';"