I have a set of buttons shown on the screen. I am trying to implement a function which executes upon hovering on a button (having a class 'button').
This function needs to display the mouse pointer at the center of the button, meaning that whilst the actual mouse pointer is on the button, the mouse pointer is displayed in the center of the button. I tried using the RequestPointerLock API but this hides the mouse pointer whereas I want it to be displayed and I believe it only works with the event handler onclick.
This is what I've done so far:
var buttons = document.getElementsByClassName('button');
buttons.requestPointerLock = buttons.requestPointerLock || buttons.mozRequestPointerLock;
document.exitPointerLock = document.exitPointerLock || document.mozExitPointerLock;
document.addEventListener('pointerlockchange', lockChangeAlert, false);
document.addEventListener('mozpointerlockchange', lockChangeAlert, false);
function lockChangeAlert()
{
if (document.pointerLockElement === buttons || document.mozPointerLockElement === buttons)
{
console.log('The pointer lock status is now locked');
document.addEventListener("mousemove", updatePosition, false);
} else
{
console.log('The pointer lock status is now unlocked');
document.removeEventListener("mousemove", updatePosition, false);
}
}
function updatePosition(e)
{
}
buttons.onclick = function()
{
buttons.requestPointerLock();
}
Any ideas on how I can implement this please?
There is no way for you to set the position of the cursor using JavaScript. This goes against a number of security considerations. The best you can do is hide the cursor (with cursor: none on :hover, and draw a static image of one on the center of the button.
Please note that the inconsistency of the cursor icons on different systems will prove to be a problem if you choose to go down this path.
As it is with a few other JavaScript APIs, requestPointerLock doesn't work with events such as mouseover (not unlike requestFullscreen). They need direct user interaction to work. An event such as mouseover would be exploited too easily.
The Pointer Lock API example uses a canvas to draw a circle to a canvas.
This might be helpful.
button {
background: #333;
position: relative;
color: #fff;
padding: 40px 80px;
border: none;
font-size: 32px;
}
button:hover {
cursor: none;
}
button:hover:after {
content: '';
background-image: url("http://www.freeiconspng.com/uploads/original-file---svg-file-nominally-550--400-pixels-file-size-3--23.png");
width: 48px;
height: 48px;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background-size: contain;
background-repeat: no-repeat;
}
<button>Here</button>
Here is also the codepen: http://codepen.io/hunzaboy/pen/pNwOqZ
Related
I have button in html that is on the middle left of the screen, that button is styled such as:
.openbtn {
font-size: 20px;
border-radius: 0 5px 5px 0;
cursor: pointer;
position: fixed;
Top: 50%;
left: 0px;
background-color: #181A1B;
color: white;
padding: 10px 15px;
border: none;
z-index: 1;
transition: 0.5s;
}
now when i click this button i want it to transfer to the upper right and when i click again it should go back to its original position. In Javascript the button is handled as so:
var lastState = false;
function sideButtonClicked() {
if(!lastState){
//open
lastState=true
document.getElementById("Button").style.left = "";
document.getElementById("Button").style.right = "0";
document.getElementById("Button").style.top = "0";
}
else{
//close
lastState=false
document.getElementById("Button").style.left = "0px";
document.getElementById("Button").style.right = "";
document.getElementById("Button").style.top = "50%";
}
I find this tricking because if i want to play that button on the upper right corner is when i declare it on css i dont place the left property but since its initial position is in the left i have to declare it. I tried setting it to "" but it does not work. What i know works is the button moves up/down upon clicking the button,
}
This is a simple example of how to toggle classes in vanilla JS. Then, you just do your styling via CSS.
// Cache the DOM element for continued use
var btn = document.getElementById("btn");
// Attach event listener to button for 'click' event
btn.addEventListener("click", () =>
{
// Where we see if it has the class or not
// Is it inactive?
if (!btn.classList.contains("active"))
{
console.log("Added");
btn.classList.add("active");
} else // If it *is* currently active
{
console.log("Removed");
btn.classList.remove("active");
}
});
.btn {
padding: 1rem;
width: 200px;
transition: all 300ms ease-in-out;
}
.btn.active {
padding: 2rem;
width: 400px;
}
<button class="btn" id="btn">Click Me</button>
Essentially, you're using a CSS class as a target for the different styling and just using JS to turn the class on/off. That way, you can just edit the 'toggle' class in CSS to whatever you want and the code will always work. This is usually what we use for sticky navbars, etc. You just add/remove another class, and that overrides the default styling.
I am trying to change my cursor into different images depending on the object that it is hovering over inside my banner. Currently I only know to change the cursor style in CSS. But the cursor stays the same throughout. How do I replace the cursor image on mouseover in my javascript? I am only using jQuery and TweenMax as this is for an assignment.
Using CSS cursor property
Without using any pseudo-selectors in CSS, you can have a pretty good result by playing around with the cursor property. For example, you can select one cursor style from a range of available ones. Or even add your own by linking the URL of the icon.
For example, the code below will show a heart when you hover over the grey area:
.heart {
cursor: url("https://s3-us-west-2.amazonaws.com/s.cdpn.io/9632/heart.png"), auto;
width: 200px;
height: 200px;
background: grey;
}
<div class="heart"></div>
You can change the origin of the image's position relative to the actual mouse position by setting the x and y position along with the URL in the cursor property:
cursor: url(<URL>) [x y|auto];
Using JavaScript
Of course, you can handle this feature with JavaScript code. Here are several things we will need to achieve this:
creating an HTML element with the image of the cursor you want as background
using the onmouseenter, onmousemove and onmouseleave events
getting the position of the mouse on the page: properties pageX, pageY
setting the position of our cursor element to be at the position of the mouse (the actual mouse pointer will be hidden): with the transform CSS property.
There are several other tricks I have used to get it right: for example setting the boxes' overflow to be hidden so that the cursor elements can't be seen outside the box. Also, listening to the onmouseleave event allows us to hide the cursor element when the mouse is outside the box area.
I have made a little demo here, click Show code snippet > Run code snippet:
const showCursor = function(event) {
let cursor = event.target.querySelector('.cursor');
event.target.onmousemove = function(e) {
cursor.style.display = 'block'
let [x, y] = [e.pageX - e.target.offsetLeft - 20, e.pageY - e.target.offsetTop - 20]
cursor.style.transform = `translate(${x}px, ${y}px)`
}
event.target.onmouseleave = function(e) {
cursor.style.display = 'none'
}
}
.box {
cursor: none;
overflow: hidden;
width: 200px;
height: 200px;
background: pink;
display: inline-block;
margin: 10px;
}
.box:nth-child(1) {
background: aquamarine;
}
.box:nth-child(2) {
background: pink;
}
.box:nth-child(3) {
background: cornflowerblue;
}
.box:nth-child(4) {
background: lightcoral;
}
.cursor {
display: none;
width: 100px;
height: 100px;
}
#heart {
background: no-repeat url("https://png.icons8.com/color/50/000000/hearts.png");
}
#diamond {
background: no-repeat url("https://png.icons8.com/color/50/000000/diamonds.png")
}
#spade {
background: no-repeat url("https://png.icons8.com/metro/50/000000/spades.png")
}
#clubs {
background: no-repeat url("https://png.icons8.com/ios/50/000000/clubs-filled.png")
}
<div onmousemove="showCursor(event)" class="box">
<div id="diamond" class="cursor"></div>
</div>
<div onmouseenter="showCursor(event)" class="box">
<div id="heart" class="cursor"></div>
</div>
<div onmousemove="showCursor(event)" class="box">
<div id="spade" class="cursor"></div>
</div>
<div onmousemove="showCursor(event)" class="box">
<div id="clubs" class="cursor"></div>
</div>
The function showCursor() is called when the user's mouse enters one of the boxes with the attribute onmouseenter="showCursor(event)" (see HTML markup above).
Below I have provided the JavaScript code with comments explaining how it works:
const showCursor = function(event) {
// get the element object of the cursor of this box
let cursor = event.target.querySelector('.cursor');
// function that will be execute whenever the user moves inside the box
event.target.onmousemove = function(e) {
// the user is moving inside the box
// show the cursor element
cursor.style.display = 'block'
// calcultate the translate values of the cursor element
let [x, y] = [e.pageX - e.target.offsetLeft - 20, e.pageY - e.target.offsetTop - 20]
// apply these values to the style of the cursor element
cursor.style.transform = `translate(${x}px, ${y}px)`
}
// function that will be executed when the user leaves the box
event.target.onmouseleave = function(e) {
// the user's mouse left the box area
// hide the cursor element
cursor.style.display = 'none'
}
}
With a <svg> element
A while ago I answered a post on how to add an <svg> element as the cursor of the mouse. It's a little bit more advanced though. It's still a JavaScript solution but it involves using a <svg> element as the cursor instead of it being a simple <div> (as seen in the second point).
I'm not that good with jQuery animations, but i'm trying to animate an background image when mouse enters on its element. The animation is simple, mouse enters, the image moves a little to the left. Mouse leaves, image returns to its position.
I could have that working on Chrome, but with a different behaviour in IE. FF doesn't event move anything. My is the following:
$(".arrow").on("mouseenter", function()
{
$(this).stop(true).animate({ "background-position-x": "75%" });
}).on("mouseleave", function()
{
$(this).stop(true).animate({ "background-position-x": "50%" });
});
Where .arrow is a div with these properties:
.arrow {
width: 50px;
padding: 10px 0;
background: url(http://upload.wikimedia.org/wikipedia/commons/4/45/Right-facing-Arrow-icon.jpg) no-repeat center;
background-size: 16px
}
And here is a demo.
What is most strange for me is the case of IE. It seems that the animation start always from left to right, not middle right. It occours when mouses leaves too. Any ideas ?
Because Firefox doesn't support backgroundPositionX, but it does support background position
Try this code in firefox and InternetExplorer:
$(".arrow").on("mouseenter", function()
{
$(this).stop(true).animate({ "background-position": "75%" });
}).on("mouseleave", function()
{
$(this).stop(true).animate({ "background-position": "50%" });
});
More Info: backgroundPositionX not working on Firefox
Here is Updated Demo working well with FF and IE
I know Manwal has solved it , but it can also be done very easily in CSS3 like so:
.arrow {
float:left;
width: 50px;
padding: 10px 0;
background: url(http://upload.wikimedia.org/wikipedia/commons/4/45/Right-facing-Arrow-icon.jpg) no-repeat center;
background-size: 16px;
transition: all 2s ease-in-out;
}
.arrow:hover {
transform :translateX(50px);
}
where translate 50px will be the value you wish to move it along the X axis
When a user clicks a link which has an image as a background, I need an onClick event that changes the background position of it. This is the link:
Favorite
It's already set in css and there are two states, regular and hover, with hover being shifted by 12px.
a.favorite {
width: 15px;
height: 12px;
background: url(img/icon-fav.png) no-repeat;
overflow: hidden;
position: absolute;
top: 0;
right: 0;
text-indent: -300px;
}
a.favorite:hover {
background-position: 0 -12px
}
When I click the image once, I need the background position to be set the same as the hover state.
I'm doing that like this, and it works:
document.getElementById("favorite_1").style.backgroundPosition = "0 -12px";
But when the link is clicked again, I need it to switch back to the normal background position and I can't get that to work. This is the function I'm trying but it only works for moving the background to "0 -12px", not for moving it back to its original position.
function favoriteBusiness(id){
if(document.getElementById("favorite_1").style.backgroundPosition == "0 -12px")
document.getElementById("favorite_1").style.backgroundPosition = "";
else
document.getElementById("favorite_1").style.backgroundPosition = "0 -12px";
}
Can someone point me in the right direction here?
Unless you're making calculations, you're better off adding and removing classes that contain the new position. This is usually what's done for manipulating CSS sprites.
I have 2 sibling-nodes with 'position absolute' which both handle mousedown event. How can I trigger the handler of 'div 1' when I am clicking on the transparent area of the 'div 2' (on the pic.)
If the overlapping elements are dynamic, I don't believe it is possible to accomplish this using regular event bubbling since the two overlapping elements in question are "siblings".
I had the same problem and I was able to solve it with more of a hitTest scenerio where I test if the user's mouse position is within the same area.
function _isMouseOverMe(obj){
var t = obj.offset().top;
var o = obj.offset().left;
var w = obj.width();
var h = obj.height();
if (e.pageX >= o+1 && e.pageX <= o+w){
if (e.pageY >= t+1 && e.pageY <= t+h){
return true;
}
}
return false
}
You'll want to use 3 event handlers, one for div1, one for div2, and one for contentArea. The contentArea handler should stop propagation so that the div2 handler is not called. The div2 handler should call the div1 handler:
function div1Click (e)
{
// do something
}
function div2Click (e)
{
div1Click.call(div1, e);
}
function contentAreaClick (e)
{
e = e || window.event;
if (e.stopPropagation) e.stopPropagation();
e.cancelBubble = true;
// do something
}
div1.onclick = div1Click;
div2.onclick = div2Click;
contentArea.onclick = contentAreaClick;
What you were looking was CSS's pointer-events property. I didn't make a research to learn whether it was available at the times the question been asked, but that I faced the same thing I'm taking a liberty of covering it.
Here're your two DIVs:
<body>
<div class="inner div-1"></div>
<div class="inner div-2">
<div class="div-2__content-area"></div>
</div>
</body>
Styling:
.inner {
height: 10em;
position: absolute;
width: 15em;
}
.div-1 {
/* Intrinsic styling & initial positioning, can be arbitrary */
background: #ff0;
left: 50%;
top: 50%;
transform: translate(-75%, -75%);
}
.div-2 {
/* Intrinsic styling & initial positioning, can be arbitrary */
background: rgba(0, 255, 0, 0.25);
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
/* Centering content area */
align-items: center;
display: flex;
justify-content: center;
/* Key feature -- making visible part of transparent DIV insensitive to mouse (pointer) events), letting them fire on the underlying element */
pointer-events: none;
}
.div-2__content-area {
/* Styling content area */
background: #f00;
height: 75%;
width: 75%;
/* Reverting 'pointer-events' perception to regular */
pointer-events: auto;
}
Event listeners and displaying:
document.querySelector(".div-1").addEventListener("mousedown", (_) => {
alert("div 1");
});
document.querySelector(".div-2__content-area").addEventListener("mousedown", (_) => {
alert("Content area");
});
This all on codepen:
https://codepen.io/Caaat1/pen/RwZEJVP