What is the best way if I want to animate an element on scroll?
because I noticed that it lags a little bit while scrolling.
should I add the class like this?
$(window).scroll(function() {
if($(this).scrollTop() > 500) {
$(".element").addClass("animateElement");
}
}
or make a flag like this one.
animateFlag = true;
$(window).scroll(function() {
if($(this).scrollTop() > 500) {
if(animateFlag) {
$(".element").addClass("animateElement");
animateFlag = false;
}
}
}
The best way to animate something on scroll is to make the most optimized code. For example, you could use Vanilla JS with a flag like you described and also query for the element before scrolling which would result in something like so:
var animateFlag = true
var element = document.querySelector(".element")
window.addEventListener("scroll", function() {
if(this.pageYOffset > 0) {
if(animateFlag) {
element.classList.add("animateElement");
animateFlag = false;
}
}
})
.element {
background: yellow;
width: 200px;
height: 200px;
margin-bottom: 1000px;
}
.element.animateElement {
background: red;
}
<div class="element"></div>
Related
I'm using this MagicMouse which works just fine. When I hover over an element I want to animate the width and height values and then return them to normal once the user unhovers.
I have the following code which defines the values of the cursor in a jS array:
options = {
"cursorOuter": "circle-basic",
"hoverEffect": "pointer-overlay",
"hoverItemMove": false,
"defaultCursor": false,
"outerWidth": 30,
"outerHeight": 30
};
magicMouse(options);
Then I have this code to handle the hover:
$(document).on("mouseenter mouseleave", ".fwds3dcov-thumbnail", function (e) {
if (e.type == "mouseenter") {
console.log('hovering');
} else {
console.log('unhovering');
}
});
The mouse itself and the hover function work independently as expected, however I need to be able to animate the width and height values inside the if statement.
Can I do something like MagicMouse.outerWidth = 70?
I'm not familiar with updating values which originate from an array, if someone could point me in the right direction that would be greatly appreciated!
EDIT:
I tried this and it 'works' but it causes a bug where the cursor regenerates in the corner of the screen as if it's reinitialising on every hover event.
$(document).on("mouseenter mouseleave", ".fwds3dcov-thumbnail", function (e) {
if (e.type == "mouseenter") {
magicMouse({
"outerWidth": 60,
"outerHeight": 60
});
console.log('hovering');
} else {
magicMouse({
"outerWidth": 30,
"outerHeight": 30
});
console.log('unhovering');
}
});
I would suggest taking a look into magicMouse source code. You will see that the "cursor" is just another DOM element and that its shape depends on applied CSS classes.
This is basic way to override the default library behavior:
var magicMouseCursor = document.getElementById("magicMouseCursor");
var hoverEls = document.querySelectorAll(".magic-hover");
hoverEls.forEach((item, i) => {
item.addEventListener("mouseenter", event => {
magicMouseCursor.classList.add('is-hover');
});
item.addEventListener("mouseleave", event => {
magicMouseCursor.classList.remove('is-hover');
});
});
div#magicMouseCursor.is-hover {
width: 60px !important;
height: 60px !important;
}
A combination of the answer from Vladislav Leonov and my original code made this work.
Working code:
$(document).on("mouseenter mouseleave", ".fwds3dcov-thumbnail", function (e) {
var magicMouseCursor = document.getElementById("magicMouseCursor");
if (e.type == "mouseenter") {
magicMouseCursor.classList.add('is-hover');
} else {
magicMouseCursor.classList.remove('is-hover');
}
});
div#magicMouseCursor.is-hover {
transition: all 0.2s!important;
width: 60px !important;
height: 60px !important;
}
I have to show and hide a div on triple click on body of my website in mobile devices
the below code that I wrote in JavaScript is work fine in android devices but it doesn't work in IOS.
so would you please help me to resolve it?
the code is :
window.onload = function() {
document.querySelector('body').addEventListener('click', function(evt) {
evt.preventDefault();
if (evt.detail === 3) {
document.getElementById('mmu').style.height = '100px';
}
if (evt.detail === 1) {
document.getElementById('mmu').style.height = '0px';
}
});
}
#mmu {
width: 100px;
height: 0px;
position: fixed;
left: 0;
cursor: pointer;
top: 0;
background: red;
}
body {
height: 1000px;
background: #eee;
width: 100%;
cursor: pointer;
}
<div id="mmu"></div>
On iOS, the click event doesn't fire normally. Instead you will need monitor touch events such as touchend to check how many taps are made.
For example you might try to check if the taps are made within a sufficient timeout window like so
TOUCH_TIMEOUT_MILLISECONDS = 500
touch_count = 0
window.onload = function () {
document.querySelector('body').addEventListener('touchend', function (evt) {
touch_count += 1
setTimeout(function () {
touch_count = 0
}, TOUCH_TIMEOUT_MILLISECONDS);
if (touch_count === 3) {
document.getElementById('mmu').style.height = '100px';
}
if (touch_count === 1) {
document.getElementById('mmu').style.height = '0px';
}
evt.preventDefault();
});
});
Depending on what your requirements are you may also need to account for touchend and click events firing from the same action.
I want the following:
Detect page width on load and add/remove class if it's below/above 959px
If I resize the page I want to do the same
$(window).on("resize load", function(e) {
e = $("body").width();
if (e <= 959) {
$("#button").addClass("active")
}
if (e >= 960) {
$("#button").removeClass("active")
}
})
This code works, but it removes the active class even if I resize the window from 500px to 501px. I want that to only add the class if I go above 960px or remove it if I go below 959px. How can I do that?
EDIT
Thanks for the answers! In the meantime I figured out a solution that works and suit my needs.
$(window).one("load", function () {
r = $("body").width();
if (r >= 960) {
$("body").attr("mobile","0")
//do something
}
if (r <= 959) {
$("body").attr("mobile","1")
//do something
}
});
$(window).on("resize", function() {
r = $("body").width();
if ($("body").attr("mobile") == "0") {
if (r <= 959) {
//do something
$("body").attr("mobile","1")
}
}
if ($("body").attr("mobile") == "1") {
if (r >= 960) {
//do something
$("body").attr("mobile","0")
}
}
})
Explanation:
It's a very specific solution since I modify the tabindex values in mobile view and I don't want to change these values back to 0 on a simple resize, only in the case I switch from mobile view to desktop.
The width of the window is different than the width of the body. Using $('body').width() will account for the overflow, whereas using $(window).width() will give you the actual screen width.
$(window).on('load resize', function() {
$('#button').toggleClass('active', $(this).width() <= 959)
});
However, using media queries is much more straight forward if in fact, you are just adding CSS properties.
#button {
opacity: 0.5;
}
#media (max-width: 959px) {
#button {
opacity: 1;
}
}
You could ouse window.matchMedia for this. If you look at the perf test, matchMedia is a lot faster than resize.
var mq = window.matchMedia("(min-width:959px)");
// onload
setButton(mql);
// add listener for the query
mq.addListener(setButton);
function setButton(mq) {
if (mql.matches) {
// do something with your setButton
} else {
// no match....
}
}
Here you go with a solution https://jsfiddle.net/hLkv1xan/1/
$(window).on("resize load", function(e) {
e = $("body").width();
if (e <= 959) {
$("#button").addClass("active")
} else {
$("#button").removeClass("active")
}
});
.active{
background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="button">
Submit
</button>
I just modified your code a bit, change in the condition.
Hope this will help you.
I'm trying to make one of those annoying popups when leaving your browser. However, I want the event to be available after a certain amount of time. The event should be allowed to trigger after a certain amount of time. I've seen stuff such as delay and setTimeout, but I have no idea how to implement it on my code.
JavaScript:
$(document).on("mouseleave", function (event) {
if (event.pageY < 0) {
$(".leavemodal").fadeIn(600);
}
});
This is not tested but maybe you can try this.
$(document).ready(function() {
canRun = false;
waitPeriod = 1000;// waiting time
setTimeout(function() { canRun = true; }, waitPeriod);
$(document).on("mouseleave", function (event) {
if (!canRun) {
return false;
}
if (event.pageY < 0) {
$(".leavemodal").fadeIn(600);
}
});
});
If you want to use setTimeout() you can do something like this. Click event will be allowed 2 seconds after you mouseleave the element.
var click = false;
$('.el').mouseleave(function() {
if (click == false) {
setTimeout(function() {
console.log('You can click now')
click = true;
$(this).click(function() {
console.log('click')
})
}, 2000)
}
})
.el {
width: 200px;
height: 200px;
background: black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="el"></div>
I have some code in jQuery in which I want to make a switch animate on or off by clicking on a div. Here is the code. When I test it, it doesn't work. However if I remove toggle = true on line 7, it just works one way and I can't turn it back off.
$(document).ready(function () {
$("#switch").click(function () {
var toggle = false;
if (toggle == false) {
$("#circle").css("left", "27px");
$("#white_rect").attr("src", "green_rect.png");
toggle = true;
}
if (toggle == true) {
$("#circle").css("left", "1px");
$("#white_rect").attr("src", "white_rect.png");
toggle = false;
}
});
});
You need to declare the toggle variable outside of the click handler... else in every click call the variable will get reinitialized so the value of the variable will always be false.
$(document).ready(function () {
//declare it here
var toggle = false;
$("#switch").click(function () {
if (toggle == false) {
$("#circle").css("left", "27px");
$("#white_rect").attr("src", "green_rect.png");
toggle = true;
//also don't use a separate if block here as it will be affected by the execution of the above if block
} else {
$("#circle").css("left", "1px");
$("#white_rect").attr("src", "white_rect.png");
toggle = false;
}
});
});
$(document).ready(function () {
//declare it here
var toggle = false;
$("#switch").click(function () {
if (toggle) {
$("#circle").css("left", "1px");
$("#white_rect").attr("src", "white_rect.png");
} else {
$("#circle").css("left", "27px");
$("#white_rect").attr("src", "green_rect.png");
}
toggle = !toggle;
});
});
It is better to strictly divide appearance and logic. So use .classes and backgounded <div>s instead of <img>. Then you won't need any state variables and code shall be more simple.
HTML:
<div class="container">
<div class="switch off"></div>
</div>
CSS:
.container {
width:100%; height:100px; padding:40px; text-align:center;
}
.container .switch {
width:94px; height: 27px; display:inline-block; background-color:pink; cursor:pointer;
}
.container .switch.on {
background: url('http://squad.pw/tmp/img/01-on.png') no-repeat 0 0;
}
.container .switch.off {
background: url('http://squad.pw/tmp/img/01-off.png') no-repeat 0 0;
}
JS:
$('.switch').click(function() {
// Do visual logic
$(this).toggleClass('on');
$(this).toggleClass('off');
// Do business logic
window.toggle = !window.toggle;
});
Here is FIDDLE