Looking for some help with a custom cursor. It's all working fine except for when you scroll, the custom cursor stays where it is on the page until you move the mouse again and then it catches up. So I need to make the custom cursor stick to the position of the default cursor at all times.
Thanks in advance!
const queryCursor = document.querySelector(".cursor");
var cursor = {
delay: 8,
_x: 0,
_y: 0,
endX: window.innerWidth / 2,
endY: window.innerHeight / 2,
cursorVisible: true,
cursorEnlarged: false,
$cursor: queryCursor,
init: function () {
this.outlineSize = this.$cursor.offsetWidth;
this.setupEventListeners();
this.animateDotOutline();
},
setupEventListeners: function () {
var self = this;
// On Hover Active
document.querySelectorAll("a, img, .elementor-custom-embed-image-overlay, button").forEach(function (el) {
el.addEventListener("mouseover", function () {
self.cursorEnlarged = true;
queryCursor.classList.add("active");
});
el.addEventListener("mouseout", function () {
self.cursorEnlarged = false;
queryCursor.classList.remove("active");
});
});
// On Hover Disappears
document.querySelectorAll("input, textarea, iframe, video, .footer").forEach(function (el) {
el.addEventListener("mouseover", function () {
self.cursorEnlarged = true;
queryCursor.classList.add("hidden");
});
el.addEventListener("mouseout", function () {
self.cursorEnlarged = false;
queryCursor.classList.remove("hidden");
});
});
document.addEventListener("mousemove", function (e) {
self.cursorVisible = true;
self.toggleCursorVisibility();
self.endX = e.pageX;
self.endY = e.pageY;
});
document.addEventListener("mouseenter", function (e) {
self.cursorVisible = true;
self.toggleCursorVisibility();
self.$cursor.style.opacity = 1;
});
document.addEventListener("mouseleave", function (e) {
self.cursorVisible = true;
self.toggleCursorVisibility();
self.$cursor.style.opacity = 0;
});
},
animateDotOutline: function () {
var self = this;
self._x += (self.endX - self._x) / self.delay;
self._y += (self.endY - self._y) / self.delay;
self.$cursor.style.top = self._y + "px";
self.$cursor.style.left = self._x + "px";
requestAnimationFrame(this.animateDotOutline.bind(self));
},
toggleCursorVisibility: function () {
var self = this;
if (self.cursorVisible) {
self.$cursor.style.opacity = 1;
} else {
self.$cursor.style.opacity = 0;
}
}
};
cursor.init();
.cursor {
z-index: 1000;
pointer-events: none;
position: absolute;
top: 50%;
left: 50%;
border-radius: 50%;
opacity: 0;
transform: translate(-50%, -50%);
transition: opacity 0.3s ease-in-out, transform 0.3s ease-in-out, background-color 0.3s, width 0.3s, height 0.3s;
width: 20px;
height: 20px;
background-color: #EBF602;
display: flex;
align-items: center;
justify-content: center;
}
.cursor.active {
transform: translate(-50%, -50%) scale(2);
opacity:0.7 !important;
}
.cursor.hidden {
opacity: 0 !important;
}
section{
min-height:100vh;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="cursor"></div>
<section></section>
<section></section>
Related
Is it possible to a piece of javascript on mobile/tablet devices only? I'd like to do something a bit better than display: none and it makes sense to stop the script from running if it's not required?
Basically I have a custom cursor effect, that is only required when it follows the cursor on desktop with a mouse/trackpad.
This is the script I have:
var cursor = document.querySelector('.cursor-outer');
var cursorinner = document.querySelector('.cursor');
var a = document.querySelectorAll('a');
var moveCursor = true;
var radiusOfCursor = parseInt(getComputedStyle(cursor).getPropertyValue('width')) / 2; // radiusOfCursor = (width_of_cursor / 2).
document.addEventListener('mousemove', function (e) {
var x = e.clientX;
var y = e.clientY;
cursorinner.style.left = x + 'px';
cursorinner.style.top = y + 'px';
if (!moveCursor) return;
cursor.style.marginLeft = `calc(${e.clientX}px - ${radiusOfCursor}px)`;
cursor.style.marginTop = `calc(${e.clientY}px - ${radiusOfCursor}px)`;
moveCursor = false;
setTimeout(() => {
moveCursor = true;
}, 32) // The wait time. I chose 95 because it seems to work just fine for me.
});
/* Centre pointer after stopping */
function mouseMoveEnd() {
cursor.style.marginLeft = `calc(${cursorinner.style.left} - ${radiusOfCursor}px)`;
cursor.style.marginTop = `calc(${cursorinner.style.top} - ${radiusOfCursor}px)`;
}
var x;
document.addEventListener('mousemove', function() {
if (x) clearTimeout(x);
x = setTimeout(mouseMoveEnd, 10);
}, false);
/* End */
document.addEventListener('mousedown', function() {
cursor.classList.add('click');
cursorinner.classList.add('cursorinnerhover');
});
document.addEventListener('mouseup', function() {
cursor.classList.remove('click');
cursorinner.classList.remove('cursorinnerhover');
});
a.forEach(item => {
item.addEventListener('mouseover', () => {
cursor.classList.add('hover');
});
item.addEventListener('mouseleave', () => {
cursor.classList.remove('hover');
});
});
a.forEach((item) => {
const interaction = item.dataset.interaction;
item.addEventListener("mouseover", () => {
cursorinner.classList.add(interaction);
});
item.addEventListener("mouseleave", () => {
cursorinner.classList.remove(interaction);
});
});
* {
cursor: none;
}
.cursor-outer {
border: 2px solid black;
border-radius: 100%;
box-sizing: border-box;
height: 32px;
pointer-events: none;
position: fixed;
top: 16px;
left: 16px;
transform: translate(-50%, -50%);
transition: height .12s ease-out, margin .12s ease-out, opacity .12s ease-out, width .12s ease-out;
width: 32px;
z-index: 100;
}
.cursor {
background-color: black;
border-radius: 100%;
height: 4px;
opacity: 1;
position: fixed;
transform: translate(-50%, -50%);
pointer-events: none;
transition: height .12s, opacity .12s, width .12s;
width: 4px;
z-index: 100;
}
<div class="cursor-outer"></div>
<div class="cursor"></div>
Thanks in advance!
Option #1
You can use something similar to this to determine if a device is touch-enabled:
isTouchDevice = () => {
return ( 'ontouchstart' in window ) ||
( navigator.maxTouchPoints > 0 ) ||
( navigator.msMaxTouchPoints > 0 );
};
This is adapted from Patrick H. Lauke's Detecting touch article on Mozilla.
Then just: if (isTouchDevice()) { /* Do touch screen stuff */}
Option #2
But maybe a pure CSS approach could work better in your situation, like:
#media (hover: none) {
.cursor {
pointer-events: none;
}
}
Option #3
If you don't mind using a third-party library, then Modernizr is really great for detecting things like this in the user's environment. Specifically, Modernizr.pointerevents will confirm if touchscreen is being used.
I have a small page. Circles appear here, when you click on them they disappear.
I added here the possibility that in addition to clicking on the LMB, you can also click on a keyboard key, in my case it is "A".
But I noticed the problem that if you hold down the "A" button, then drive in circles, then the need for clicks disappears, and this is the main goal.
Can I somehow disable the ability to hold this button so that only clicking on it works?
I tried pasting this code, but all animations stopped working for me.
var down = false;
document.addEventListener('keydown', function () {
if(down) return;
down = true;
// your magic code here
}, false);
document.addEventListener('keyup', function () {
down = false;
}, false);
Get error:
"message": "Uncaught ReferenceError: mouseOverHandler is not defined"
//create circle
var clickEl = document.getElementById("clicks");
var spawnRadius = document.getElementById("spawnRadius");
var spawnArea = spawnRadius.getBoundingClientRect();
const circleSize = 95; // Including borders
function createDiv(id, color) {
let div = document.createElement('div');
div.setAttribute('class', id);
if (color === undefined) {
let colors = ['#ebc6df', '#ebc6c9', '#e1c6eb', '#c6c9eb', '#c6e8eb', '#e373fb', '#f787e6', '#cb87f7', '#87a9f7', '#87f7ee'];
randomColor = colors[Math.floor(Math.random() * colors.length)];
div.style.borderColor = randomColor;
}
else {
div.style.borderColor = color;
}
// Randomly position circle within spawn area
div.style.top = `${Math.floor(Math.random() * (spawnArea.height - circleSize))}px`;
div.style.left = `${Math.floor(Math.random() * (spawnArea.width - circleSize))}px`;
div.classList.add("circle", "animation");
// Add click handler
let clicked = false;
div.addEventListener('mouseover', mouseOverHandler );
div.addEventListener('mouseout', mouseOutHandler );
div.addEventListener('click', (event) => {
if (clicked) { return; } // Only allow one click per circle
clicked = true;
div.style.animation = 'Animation 200ms linear forwards';
setTimeout(() => { spawnRadius.removeChild(div); }, 220);
});
spawnRadius.appendChild(div);
}
let i = 0;
const rate = 1000;
setInterval(() => {
i += 1;
createDiv(`circle${i}`);
}, rate);
let focusedEl = null;
const keyDownHandler = (evt) => {
if(evt.keyCode === 65 && focusedEl) focusedEl.click();
}
const mouseOutHandler = (evt) => focusedEl = null;
const mouseOverHandler = (evt) => focusedEl = evt.currentTarget;
document.addEventListener('keydown', keyDownHandler );
window.focus();
html, body {
width: 100%;
height: 100%;
margin: 0;
background: #0f0f0f;
}
.circle {
width: 80px;
height: 80px;
border-radius: 80px;
background-color: #0f0f0f;
border: 3px solid #000;
position: absolute;
}
#spawnRadius {
top: 55%;
height: 250px;
width: 500px;
left: 50%;
white-space: nowrap;
position: absolute;
transform: translate(-50%, -50%);
background: #0f0f0f;
border: 2px solid #ebc6df;
}
#keyframes Animation {
0% {
transform: scale(1);
opacity: 1;
}
50% {
transform: scale(.8);
}
100% {
transform: scale(1);
opacity: 0;
}
}
<html>
<body>
<div id="spawnRadius"></div>
</body>
</html>
You can check the repeat property of the event, which
… is true if the given key is being held down such that it is automatically repeating.
(but notice the compatibility notes on auto-repeat handling)
const keyDownHandler = (evt) => {
if (!evt.repeat && evt.keyCode === 65) {
// ^^^^^^^^^^^
focusedEl?.click();
}
}
//create circle
var clickEl = document.getElementById("clicks");
var spawnRadius = document.getElementById("spawnRadius");
var spawnArea = spawnRadius.getBoundingClientRect();
const circleSize = 95; // Including borders
function createDiv(id, color) {
let div = document.createElement('div');
div.setAttribute('class', id);
if (color === undefined) {
let colors = ['#ebc6df', '#ebc6c9', '#e1c6eb', '#c6c9eb', '#c6e8eb', '#e373fb', '#f787e6', '#cb87f7', '#87a9f7', '#87f7ee'];
randomColor = colors[Math.floor(Math.random() * colors.length)];
div.style.borderColor = randomColor;
}
else {
div.style.borderColor = color;
}
// Randomly position circle within spawn area
div.style.top = `${Math.floor(Math.random() * (spawnArea.height - circleSize))}px`;
div.style.left = `${Math.floor(Math.random() * (spawnArea.width - circleSize))}px`;
div.classList.add("circle", "animation");
// Add click handler
let clicked = false;
div.addEventListener('mouseover', mouseOverHandler );
div.addEventListener('mouseout', mouseOutHandler );
div.addEventListener('click', (event) => {
if (clicked) { return; } // Only allow one click per circle
clicked = true;
div.style.animation = 'Animation 200ms linear forwards';
setTimeout(() => { spawnRadius.removeChild(div); }, 220);
});
spawnRadius.appendChild(div);
}
let i = 0;
const rate = 1000;
setInterval(() => {
i += 1;
createDiv(`circle${i}`);
}, rate);
let focusedEl = null;
const mouseOutHandler = (evt) => focusedEl = null;
const mouseOverHandler = (evt) => focusedEl = evt.currentTarget;
document.addEventListener('keydown', keyDownHandler );
window.focus();
html, body {
width: 100%;
height: 100%;
margin: 0;
background: #0f0f0f;
}
.circle {
width: 80px;
height: 80px;
border-radius: 80px;
background-color: #0f0f0f;
border: 3px solid #000;
position: absolute;
}
#spawnRadius {
top: 55%;
height: 250px;
width: 500px;
left: 50%;
white-space: nowrap;
position: absolute;
transform: translate(-50%, -50%);
background: #0f0f0f;
border: 2px solid #ebc6df;
}
#keyframes Animation {
0% {
transform: scale(1);
opacity: 1;
}
50% {
transform: scale(.8);
}
100% {
transform: scale(1);
opacity: 0;
}
}
<html>
<body>
<div id="spawnRadius"></div>
</body>
</html>
I want to hide scroll bar while preloader is loading the scroll bar will not show until unless preloader disappears which means the user can't able to scroll the page while preloader is loading here I'm using canvas as a preloader. I tried by using body overflow: hidden and some CSS also but unable to achieve the result here I used canvas effect as a preloader. Can anyone point me in the right direction what I'm doing wrong?
/* Preloader Effect */
var noise = function(){
//const noise = () => {
var canvas, ctx;
var wWidth, wHeight;
var noiseData = [];
var frame = 0;
var loopTimeout;
// Create Noise
const createNoise = function() {
const idata = ctx.createImageData(wWidth, wHeight);
const buffer32 = new Uint32Array(idata.data.buffer);
const len = buffer32.length;
for (var i = 0; i < len; i++) {
if (Math.random() < 0.5) {
buffer32[i] = 0xff000000;
}
}
noiseData.push(idata);
};
// Play Noise
const paintNoise = function() {
if (frame === 9) {
frame = 0;
} else {
frame++;
}
ctx.putImageData(noiseData[frame], 0, 0);
};
// Loop
const loop = function() {
paintNoise(frame);
loopTimeout = window.setTimeout(function() {
window.requestAnimationFrame(loop);
}, (1000 / 25));
};
// Setup
const setup = function() {
wWidth = window.innerWidth;
wHeight = window.innerHeight;
canvas.width = wWidth;
canvas.height = wHeight;
for (var i = 0; i < 10; i++) {
createNoise();
}
loop();
};
// Reset
var resizeThrottle;
const reset = function() {
window.addEventListener('resize', function() {
window.clearTimeout(resizeThrottle);
resizeThrottle = window.setTimeout(function() {
window.clearTimeout(loopTimeout);
setup();
}, 200);
}, false);
};
// Init
const init = (function() {
canvas = document.getElementById('noise');
ctx = canvas.getContext('2d');
setup();
})();
};
noise();
$(document).ready(function(){
$('body').css({
overflow: 'hidden'
});
setTimeout(function(){
$('#preloader').fadeOut('slow', function(){
$('body').css({
overflow: 'auto'
});
});
}, 5000);
});
#preloader {
position: fixed;
height: 100vh;
width: 100%;
z-index: 5000;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #fff;
/* change if the mask should have another color then white */
z-index: 10000;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<div id="preloader">
<canvas id="noise" class="noise"></canvas>
</div>
Try these Codes, If it works for you. I found this on StackOverflow. Source: Disable scrolling when preload a web page
Js Code
$(window).load(function() {
$(".preloader").fadeOut(1000, function() {
$('body').removeClass('loading');
});
});
Css Code
.loading {
overflow: hidden;
height: 100vh;
}
.preloader {
background: #fff;
position: fixed;
text-align: center;
bottom: 0;
right: 0;
left: 0;
top: 0;
}
.preloader4 {
position: absolute;
margin: -17px 0 0 -17px;
left: 50%;
top: 50%;
width:35px;
height:35px;
padding: 0px;
border-radius:100%;
border:2px solid;
border-top-color:rgba(0,0,0, 0.65);
border-bottom-color:rgba(0,0,0, 0.15);
border-left-color:rgba(0,0,0, 0.65);
border-right-color:rgba(0,0,0, 0.15);
-webkit-animation: preloader4 0.8s linear infinite;
animation: preloader4 0.8s linear infinite;
}
#keyframes preloader4 {
from {transform: rotate(0deg);}
to {transform: rotate(360deg);}
}
#-webkit-keyframes preloader4 {
from {-webkit-transform: rotate(0deg);}
to {-webkit-transform: rotate(360deg);}
}
Code
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<body class="loading">
<div class="preloader">
<div class="preloader4"></div>
</div>
//Code
</body>
You need to set overflow: hidden and height: 100vh both on the body and the html tags.
/* Preloader Effect */
var noise = function(){
//const noise = () => {
var canvas, ctx;
var wWidth, wHeight;
var noiseData = [];
var frame = 0;
var loopTimeout;
// Create Noise
const createNoise = function() {
const idata = ctx.createImageData(wWidth, wHeight);
const buffer32 = new Uint32Array(idata.data.buffer);
const len = buffer32.length;
for (var i = 0; i < len; i++) {
if (Math.random() < 0.5) {
buffer32[i] = 0xff000000;
}
}
noiseData.push(idata);
};
// Play Noise
const paintNoise = function() {
if (frame === 9) {
frame = 0;
} else {
frame++;
}
ctx.putImageData(noiseData[frame], 0, 0);
};
// Loop
const loop = function() {
paintNoise(frame);
loopTimeout = window.setTimeout(function() {
window.requestAnimationFrame(loop);
}, (1000 / 25));
};
// Setup
const setup = function() {
wWidth = window.innerWidth;
wHeight = window.innerHeight;
canvas.width = wWidth;
canvas.height = wHeight;
for (var i = 0; i < 10; i++) {
createNoise();
}
loop();
};
// Reset
var resizeThrottle;
const reset = function() {
window.addEventListener('resize', function() {
window.clearTimeout(resizeThrottle);
resizeThrottle = window.setTimeout(function() {
window.clearTimeout(loopTimeout);
setup();
}, 200);
}, false);
};
// Init
const init = (function() {
canvas = document.getElementById('noise');
ctx = canvas.getContext('2d');
setup();
})();
};
noise();
$(document).ready(function(){
$('body, html').css({
overflow: 'hidden',
height: '100vh'
});
setTimeout(function(){
$('#preloader').fadeOut('slow', function(){
$('body, html').css({
overflow: 'auto',
height: 'auto'
});
});
}, 5000);
});
#preloader {
position: fixed;
height: 100vh;
width: 100%;
z-index: 5000;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #fff;
/* change if the mask should have another color then white */
z-index: 10000;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<div id="preloader">
<canvas id="noise" class="noise"></canvas>
</div>
Set the position of body as fixed and when the page is loaded, remove that.
document.body.style.position = "fixed";
window.addEventListener("load", () => {
document.body.style.position = "";
document.querySelector(".preloader").style.display = "none";
});
I want to integrate this script to my website homepage and i don't know how. I tried to integrate code to function.php but it doesn't work.
The script :
(function(){
var PleaseRotate = {},
currentOrientation = null,
isMobile = /Android|iPhone|iPad|iPod|IEMobile|Opera Mini/i.test(navigator.userAgent),
init = false;
var options = {
startOnPageLoad: true,
onHide: function(){},
onShow: function(){},
forcePortrait: false,
message: "Please Rotate Your Device",
subMessage: "(or click to continue)",
allowClickBypass: true,
onlyMobile: true,
zIndex: 1000,
iconNode: null
};
var cssRules = [
"#pleaserotate-graphic { margin-left: 50px; width: 200px; animation: pleaserotateframes ease 2s; animation-iteration-count: infinite; transform-origin: 50% 50%; -webkit-animation: pleaserotateframes ease 2s; -webkit-animation-iteration-count: infinite; -webkit-transform-origin: 50% 50%; -moz-animation: pleaserotateframes ease 2s; -moz-animation-iteration-count: infinite; -moz-transform-origin: 50% 50%; -ms-animation: pleaserotateframes ease 2s; -ms-animation-iteration-count: infinite; -ms-transform-origin: 50% 50%; }",
"#pleaserotate-backdrop { background-color: white; top: 0; left: 0; position: fixed; width: 100%; height: 100%; }",
"#pleaserotate-container { width: 300px; position: absolute; top: 50%; left: 50%; margin-right: -50%; transform: translate(-50%, -50%); -webkit-transform: translate(-50%, -50%); }",
"#pleaserotate-message { margin-top: 20px; font-size: 1.3em; text-align: center; font-family: Verdana, Geneva, sans-serif; text-transform: uppercase }",
"#pleaserotate-message small { opacity: .5; display: block; font-size: .6em}"
];
var cssKeyframeRules = [
"pleaserotateframes{ 0% { transform: rotate(0deg) ; -moz-transform: rotate(0deg) ;-webkit-transform: rotate(0deg) ;-ms-transform: rotate(0deg) ;} 49% { transform: rotate(-90deg) ;-moz-transform: rotate(-90deg) ;-webkit-transform: rotate(-90deg) ; -ms-transform: rotate(-90deg) ; } 100% { transform: rotate(90deg) ;-moz-transform: rotate(-90deg) ;-webkit-transform: rotate(-90deg) ; -ms-transform: rotate(-90deg) ; } }",
];
/* private functions */
function overrideOptions(updates){
var prop;
for (var prop in updates){
options[prop] = updates[prop];
}
}
function setBodyClass(state){
if(document.documentElement){
document.documentElement.className = document.documentElement.className.replace( /(?:^|\s)pleaserotate-\S*/g , '' );
document.documentElement.className += " pleaserotate-" + state;
}
}
function addRules(sheet){
var i;
for(i = 0; i< cssRules.length; i++){
sheet.insertRule(cssRules[i], 0);
}
sheet.insertRule("#pleaserotate-backdrop { z-index: " + options.zIndex + "}", 0);
if(options.allowClickBypass){
sheet.insertRule("#pleaserotate-backdrop { cursor: pointer }", 0);
}
if(options.forcePortrait){
sheet.insertRule("#pleaserotate-backdrop { -webkit-transform-origin: 50% }", 0);
}
for(i = 0; i< cssKeyframeRules.length; i++){
if (CSSRule.WEBKIT_KEYFRAMES_RULE) { // WebKit
sheet.insertRule("#-webkit-keyframes " + cssKeyframeRules[i], 0);
}
else if (CSSRule.MOZ_KEYFRAMES_RULE) { // Mozilla
sheet.insertRule("#-moz-keyframes " + cssKeyframeRules[i], 0);
}
else if (CSSRule.KEYFRAMES_RULE) { // W3C
sheet.insertRule("#keyframes " + cssKeyframeRules[i], 0);
}
}
}
function createStyleSheet(){
var style = document.createElement("style");
style.appendChild(document.createTextNode("")); // I'm told we need this hack... something to do with safari but I don't feel like checking for sure
document.head.insertBefore(style, document.head.firstChild);
addRules(style.sheet);
}
function createElements(){
var backdrop = document.createElement("div"),
container = document.createElement("div"),
message = document.createElement("div"),
subMessage = document.createElement("small");
backdrop.setAttribute("id", "pleaserotate-backdrop");
container.setAttribute("id", "pleaserotate-container");
message.setAttribute("id", "pleaserotate-message");
backdrop.appendChild(container);
if(options.iconNode !== null){
container.appendChild(options.iconNode);
} else {
container.appendChild(createPhoneSVG());
}
container.appendChild(message);
message.appendChild(document.createTextNode(options.message));
subMessage.appendChild(document.createTextNode(options.subMessage));
message.appendChild(subMessage);
document.body.appendChild(backdrop);
}
function createPhoneSVG(){
var svg = document.createElementNS('http://www.w3.org/2000/svg','svg');
svg.setAttributeNS('http://www.w3.org/2000/xmlns/','xmlns:xlink','http://www.w3.org/1999/xlink');
svg.setAttribute('id','pleaserotate-graphic');
svg.setAttribute('viewBox','0 0 250 250');
var group = document.createElementNS('http://www.w3.org/2000/svg','g');
group.setAttribute('id','pleaserotate-graphic-path');
if(options.forcePortrait){
group.setAttribute('transform','rotate(-90 125 125)');
}
var path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
path.setAttribute('d', 'M190.5,221.3c0,8.3-6.8,15-15,15H80.2c-8.3,0-15-6.8-15-15V28.7c0-8.3,6.8-15,15-15h95.3c8.3,0,15,6.8,15,15V221.3z' +
'M74.4,33.5l-0.1,139.2c0,8.3,0,17.9,0,21.5c0,3.6,0,6.9,0,7.3c0,0.5,0.2,0.8,0.4,0.8s7.2,0,15.4,0h75.6c8.3,0,15.1,0,15.2,0' +
's0.2-6.8,0.2-15V33.5c0-2.6-1-5-2.6-6.5c-1.3-1.3-3-2.1-4.9-2.1H81.9c-2.7,0-5,1.6-6.3,4C74.9,30.2,74.4,31.8,74.4,33.5z' +
'M127.7,207c-5.4,0-9.8,5.1-9.8,11.3s4.4,11.3,9.8,11.3s9.8-5.1,9.8-11.3S133.2,207,127.7,207z');
svg.appendChild(group);
group.appendChild(path);
return svg;
}
function setVisibility(visible){
var backdropElement = document.getElementById("pleaserotate-backdrop");
if(visible){
if(backdropElement){
backdropElement.style["display"] = "block";
}
} else {
if(backdropElement){
backdropElement.style["display"] = "none";
}
}
}
function orientationChanged(){
var triggerOn = currentOrientation && !options.forcePortrait || !currentOrientation && options.forcePortrait,
propogate;
if(triggerOn){
propogate = options.onShow();
setBodyClass("showing");
} else {
propogate = options.onHide();
setBodyClass("hiding");
}
if(propogate !== undefined && !propogate){
return;
}
PleaseRotate.Showing = triggerOn;
setVisibility(triggerOn);
}
function isPortrait(){
return ( window.innerWidth < window.innerHeight);
}
function checkOrientationChange(){
if(!isMobile && options.onlyMobile){
if(!init){
init = true;
setVisibility(false);
setBodyClass("hiding");
options.onHide(); // run this exactly once if not mobile
}
return;
}
if(currentOrientation !== isPortrait()){
currentOrientation = isPortrait();
orientationChanged();
}
}
/* public functions */
PleaseRotate.start = function(opts){
if(!document.body){
window.addEventListener('load', PleaseRotate.start.bind(null, opts), false);
return;
}
if(opts){
overrideOptions(opts);
}
createStyleSheet();
createElements();
checkOrientationChange();
window.addEventListener( 'resize', checkOrientationChange, false );
if(options.allowClickBypass){
document.getElementById("pleaserotate-backdrop").addEventListener("click", function(){
var propogate = options.onHide();
setBodyClass("hiding");
PleaseRotate.Showing = false;
if(propogate === undefined || propogate){
setVisibility(false);
}
});
}
}
PleaseRotate.stop = function(){
window.removeEventListener('resize', onWindowResize, false);
}
PleaseRotate.onShow = function(fn){
options.onShow = fn;
if(init){
// if we have already been initialized, force a check
init = false;
currentOrientation = null;
checkOrientationChange();
}
};
PleaseRotate.onHide = function(fn){
options.onHide = fn;
if(init){
// if we have already been initialized, force a check so that onHide gets called
currentOrientation = null;
init = false;
checkOrientationChange();
}
};
PleaseRotate.Showing = false;
/* plumbing to support AMD, CommonJS, or Globals */
if (typeof define === 'function' && define.amd) {
setBodyClass("initialized");
define(['PleaseRotate'], function() {
return PleaseRotate;
});
} else if (typeof exports === 'object') {
setBodyClass("initialized");
module.exports = PleaseRotate;
} else {
setBodyClass("initialized");
window.PleaseRotate = PleaseRotate;
overrideOptions(window.PleaseRotateOptions);
if (options.startOnPageLoad) {
PleaseRotate.start();
}
}
})();
If you want the JavaScript to be on the homepage only, you can do this:
function wpdocs_scripts_method() {
if ( is_home() ) {
wp_enqueue_script( 'custom-script', get_stylesheet_directory_uri() . '/js/custom_script.js', false ) );
}
}
add_action( 'wp_enqueue_scripts', 'wpdocs_scripts_method' );
Create a JavaScript file, and then place your code in there. Then replace the path and filename in the function above, and the script should be included on the homepage of your website. This code snippet should be placed in your functions.php file.
To read more: https://developer.wordpress.org/reference/functions/wp_enqueue_script/
I want to toggle between showing and hiding two divs on a mouseenter and click event. However, if the click event happens in the same position as the mouseenter area the functions go into a loop, illustrated in the gif below.
How can I delay the showOverlay function for a few seconds but maintain the mouseenter event working normally like in the gif below (i.e no delay):
Any help would be greatly appreciated?
var hover = document.querySelector('#hover');
var overlay = document.querySelector('#overlay');
var primary = document.querySelector('#primary');
var overlayShowing = false;
var clicked = false
function showOverlay() {
overlayShowing = true
overlay.classList.add('display');
setTimeout(function(){
overlay.classList.add('active');
}, 100);
primary.classList.add('nactive');
}
function hideOverlay() {
overlayShowing = false
overlay.classList.remove('active');
primary.classList.remove('hidden');
setTimeout(function(){
primary.classList.remove('nactive');
}, 100);
}
primary.addEventListener('transitionend', function() {
if(overlayShowing) {
primary.classList.add('hidden');
}
})
overlay.addEventListener('transitionend', function() {
if(!overlayShowing) {
overlay.classList.remove('display');
}
});
hover.addEventListener('mouseenter', function(event) {
showOverlay();
});
overlay.addEventListener("click", function() {
hideOverlay();
});
#primary {
opacity: 1;
display: block;
transition: 0.5s ease
}
#primary.hidden {
display: none !important;
}
#primary.nactive {
opacity: 0;
}
#hover {
font-size: 150px;
}
#overlay {
position: fixed;
height: 100vh;
width: 100vw;
top: 0;
left: 0;
background-color: black;
opacity: 0;
display: none;
transition: 0.5s ease
}
#overlay.active {
opacity: 0.8;
}
#overlay.display {
display: block;
}
<div id="primary">
<div id="hover">HOVER</div>
</div>
<div id="overlay"></div>
Just use a timeout to delay the showing:
var showTimeout;
function showOverlay() {
if(showTimeout) return;
showTimeout = setTimeout(() => {
overlayShowing = true;
overlay.classList.add('display');
setTimeout(function(){
overlay.classList.add('active');
}, 100);
primary.classList.add('nactive');
}, 500);
}
function hideOverlay() {
if(showTimeout) {
clearTimeout(showTimeout);
showTimeout = null;
}
overlayShowing = false
overlay.classList.remove('active');
primary.classList.remove('hidden');
setTimeout(function(){
primary.classList.remove('nactive');
}, 100);
}