How do I make the following, run only once per pageload...
$(window).scroll(function(){
if($(document).scrollTop()>=$(document).height()/5)
$("#spopup").show("slow");else $("#spopup").hide("slow");
});
Here is what I use to close the pop up in case that makes a difference...
function closeSPopup(){
$('#spopup').hide('slow');
}
http://codepen.io/john84/pen/vgWVRp
I was reading up on the .one() function but am unsure as where to put it
http://api.jquery.com/one/
At the end of the function call, redefine the function.
$(window).scroll(function(){
if($(document).scrollTop()>=$(document).height()/5)
$("#spopup").show("slow");else $("#spopup").hide("slow");
$(window).scroll(function(){});
});
The first time they scroll, it will execute the function (based on your if/else) and after completing that action, it clears the javascript linked to on scroll
there is many ways to do this. i think setting a flag is going to work :
var isopen = false;
$(window).on('scroll', function(){
if($(document).scrollTop() >= $(document).height()/5 && isopen == false) {
$("#spopup").show("slow");
isopen = true;
$(window).off('scroll');
}
});
Related
I'm trying to make my footer disappear when on a mobile device and only when the keyboard is open. Which I have working perfectly, however the issue is that the footer reappears before the keyboard has time to close. Which is because I'm using the event from the textbox having focus not the keyboard being open. So I thought the best way to resolve this is with a .delay() however, this isn't working at all. Anyone have any ideas here?
<script>
var isMobileView = false; //global variable
$(document).ready(function () {
function setScreenWidthFlag() {
var newWindowWidth = $(window).width();
if ( $(window).width() > 600) {
isMobileView = false;
}
else {
isMobileView = true;
}
}
$(".tbinputArea").focus(function() {
if(isMobileView)
$("#footer").hide();
});
$(".tbinputArea").focusout(function() {
if(isMobileView)
$("#footer").delay(500).show();
});
setScreenWidthFlag();
$(window).on("resize", function (e) {
setScreenWidthFlag();
});
});
</script>
$("#footer").delay(500).show(0);
Try this.
refer this explanation precisely explained the reasons for it http://www.mattlunn.me.uk/blog/2012/06/jquery-delay-not-working-for-you/
Delay is just for queue delay not any event delay so try to add some events within like fadeIn or similar.
I'm trying to create a small snippet for a sticky sidebar with jQuery. For some reason, the function inside of .scroll() is only running once instead of running at every scroll event. What could I be doing wrong?
var sticky = $('#sticky');
var staticSticky = $(sticky).offset().top;
$(window).scroll(moveEl(sticky, staticSticky));
function moveEl(element, staticElToTop){
if( $(window).scrollTop() >= staticElToTop ){
$(element).css('top', $(window).scrollTop() + 'px');
}
}
See here for the entire attempt: http://codepen.io/ExcellentSP/pen/GqZwVG
The code above is not fully functional. I'm just trying to get the scroll event to work properly before I continue.
You need to wrap content of your your moveEl method into the function (to be returned for $(window).scroll()) like this:
var sticky = $('#sticky');
var staticSticky = $(sticky).offset().top;
$(window).scroll(moveEl(sticky, staticSticky));
function moveEl(element, staticElToTop) {
return function() {
if( $(window).scrollTop() >= staticElToTop ){
$(element).css('top', $(window).scrollTop() + 'px');
}
}
}
Explanation:
The key difference is that you call a function and it returns undefined by default, so it equals to $(window).scroll(undefined). Since you actually called it, you see it's fired only once which is obvious.
As soon as you return a function within moveEl method, .scroll() gets a handler, so it becomes $(window).scroll(handler). So it will work now as expected.
In doing that $(window).scroll(moveEl(sticky, staticSticky));, you ask to javascript to execute the function. You don't pass its reference.
$(window).scroll(function(){
moveEl(sticky, staticSticky);
});
I have been using the JQuery Code below to handle a little bit of responsiveness for a menu on a Drupal site. In the two commented lines in the resize function, I am essentially trying to enable and disable the opposite events dependent on the screen size. My first question would be since this handler triggering would be in the resize function, would it cause any kind of significant performance hit to attempt something like this? My second question would be how? I've been trying to use the on and off functions to enable/disable those handlers as needed, but I don't think I'm getting the overall syntax correct. I figure it would be best to break the existing event handlers into functions, but have left them as is for the code example.
jQuery(document).ready(function($) {
$('.nav-toggle').click(function() {
$('#main-menu div ul:first-child').slideToggle(250);
return false;
});
if( ($(window).width() > 600) || ($(document).width() > 600) ) {
$('#main-menu li').mouseenter(function() {
$(this).children('ul').css('display', 'none').stop(true,
true).slideToggle(1).css('display',
'block').children('ul').css('display', 'none');
});
$('#main-menu li').mouseleave(function() {
$(this).children('ul').stop(true, true).fadeOut(1).css('display', 'block');
})
}
else {
$('.drop-down-toggle').click(function() {
$(this).parent().children('ul').slideToggle(500);
});
}
$(window).resize(function() {
if($(window).width() > 600) {
$('div.menu-navigation-container ul.menu').css('display','block');
$('div.menu-navigation-container ul.menu ul.menu').hide();
//**Disable dropdown click and enable mouse enter and mouse leave**
}
else{
$('div.menu-navigation-container ul.menu').hide();
//**Disable mouse enter and mouse leave but enable dropdown click**
}
});
});
Use a throttle function
function throttle (callback, limit) {
var wait = false; // Initially, we're not waiting
return function () { // We return a throttled function
if (!wait) { // If we're not waiting
callback.call(); // Execute users function
wait = true; // Prevent future invocations
setTimeout(function () { // After a period of time
wait = false; // And allow future invocations
}, limit);
}
}
}
$(window).on('resize', throttle(yourResizeFunction, 200))
Read why here: http://www.paulirish.com/2009/throttled-smartresize-jquery-event-handler/
As I said, move your event binding outside of the resize function as binding event handlers within resize/scroll is not a good idea at all as you'd bind the same event over and over for every pixel resized!.
An example would look like this:
$(document) // or you can even use 'div.menu-navigation-container' as opposed to document
.on("click", ".click", function() {})
.on("mouseenter", ".hover", function() {})
.on("mouseleave", ".hover", function() {});
$(window).resize(function() {
//A bit of breathing time when the resize event pauses. Remember, the statements within the resize will trigger for every pixel resize, otherwise.
setTimeout(function() {
if( $(window).width() > 600 ) {
$('div.menu-navigation-container ul.menu').css('display','block');
$('div.menu-navigation-container ul.menu ul.menu').hide();
//I am assuming your selector on which the events are bound to be '.menu-trigger' as you did not post any HTML. Replace this with the appropriate selector.
$(".menu-trigger").removeClass("click").addClass("hover");
}
else{
$('div.menu-navigation-container ul.menu').hide();
//I am assuming your selector on which the events are bound to be '.menu-trigger' as you did not post any HTML. Replace this with the appropriate selector.
$(".menu-trigger").removeClass("hover").addClass("click");
}
}, 250);
});
Hope that helps.
I want to toggle events based on width. for mobile only click event should work. for desktop hover event should work. while page loading my code working properly when resize my code is not working.
please help me why my code is not working. Thanks in advance
$(document).ready(function(){
function forDesktop(){
$(".popover-controls div").off('click');
$(".popover-controls div").on('hover');
$(".popover-controls div ").hover(function(e){
//popup show code
});
}
function forMobile(){
console.log("mobile");
$(".popover-controls div").off('hover');
$(".popover-controls div").on('click');
$(".popover-controls div").click(function(e){
//popop show
});
}
function process(){
$(window).width() > 600?forDesktop():forMobile();
}
$(window).resize(function(){
process()
});
process();
});
Its very simple, 1st you cant write this much of code for every event. We have to come up with very simple solution, here is how it works
1st check the width of the Page in JS and assign Desktop/Mobile Class on body :
function process(){
if( $(window).width() > 600){
$("body").removeClass("mobile").addClass("desktop");
}else{
$("body").removeClass("desktop").addClass("mobile");
}
}
$(window).resize(function(){
process()
});
Now, you have execute the command for hover and click:
$(document).on('mouseover', 'body.mobile .popover-controls div',function(e){
alert("hover");
});
$(document).on('click', 'body.desktop .popover-controls div',function(e){
alert("click");
console.log("click");
});
I Hope this will work for you. :)
Check the Js fiddle Example: http://jsfiddle.net/asadalikanwal/xcj8p590/
I have just created for you, also i have modified my code
You could use a JavaScript Media Query to determine the width of the screen as detailed here.
var mq = window.matchMedia( "(min-width: 500px)" );
The matches property returns true or false depending on the query result, e.g.
if (mq.matches) {
// window width is at least 500px
} else {
// window width is less than 500px
}
First Detect the Mobiles/Tablets Touch Event:
function is_touch_device() {
return 'ontouchstart' in window // works on most browsers
|| 'onmsgesturechange' in window; // works on ie10
};
Then Try like this:
function eventFire() {
var _element = $(".popover-controls div");
// True in Touch Enabled Devices
if( is_touch_device() ) {
_element.click(function(e) { .... });
}
else {
// apply Hover Event
_element.hover();
}
}
No need to detect width of devices ;)
There is one more solution with third party and Most popular library is Modernizr
This worked for me. It's a combination of the matchMedia() functionality #Ḟḹáḿíṅḡ Ⱬỏḿƀíé shared as well setTimeout() functionality #Jeff Lemay shared at TeamTreeHouse.com
The primary thing I contributed to was the use of the .unbind() functionality. It took me quite a while to figure out that this was necessary so the .hover() and .click() functions don't cross wires.
//Add/remove classes, in nav to show/hide elements
function navClassHandler(){
if($(this).hasClass('active')){
$('.dropdown').removeClass('active');
}else{
$('.dropdown').removeClass('active');
$(this).addClass('active');
}
}
function handleNav() {
//instantanteous check to see if the document matches the media query.
const mqM = window.matchMedia('(max-width: 1025px)');
const mqD = window.matchMedia('(min-width: 1025px)');
$('.dropdown').unbind(); //necessary to remove previous hover/click event handler
if (mqM.matches) {
console.log("Handling mobile");
$('.dropdown').click(navClassHandler);
} else {
console.log("Handling desktop");
$('.dropdown').hover(navClassHandler);
}
}
// we set an empty variable here that will be used to clearTimeout
let id;
/* this tells the page to wait half a second before making any changes,
we call our handleNav function here but our actual actions/adjustments are in handleNav */
$(window).resize(function() {
clearTimeout(id);
id = setTimeout(handleNav, 500);
});
//As soon as the document loads, run handleNav to set nav behavior
$(document).ready(handleNav);
I have a piece of javascript code here. When a hyperlink is clicked, the load_button() function is called which just sets the variable load_switch to true. I have a piece of code inside $(window).scroll(function() { which will fire the code when the user scrolls. So at the moment, the user clicks the hyperlink to set the variable to true, and then my load_posts function (which I omitted from the code I included to make it easier to read, see below) fires when the user scrolls.
I would like to know how I can make the function fire without the user having to scroll first to activate it. I am editing a previously programmed function which used to be an infinite scroll (hence the function being called when the user scrolls). Here is my javascript:
<script language="javascript">
var load_switch = false;
function load_button(){
load_switch = true;
}
$(document).ready(function() {
$('.loader').hide();
var load = 0;
$(window).scroll(function() {
if(load_switch) {
//load_posts function goes here
}
});
});
</script>
Name your function
var load_switch = false;
function load_button(){
load_switch = true;
}
// Name your function instead of defining it inline
function onScroll() {
if(load_switch) {
//load_posts function goes here
}
}
$(document).ready(function() {
$('.loader').hide();
var load = 0;
$(window).scroll(onScroll);
// Call it whenever you'd like
onScroll();
});
You can use triggerHandler:
$(window).triggerHandler('scroll');
Note this will run all event handlers. If you don't want that, you need to store the desired event handler in a variable:
function handleScroll() {
//load_posts function goes here
}
function load_button(){
$(window).on('scroll', handleScroll);
}
$(document).ready(function() {
$('.loader').hide();
handleScroll(); // Call it manually
});
Also note your approach was bad. Instead of running the event handler always and exiting if a boolean flag is false, get rid of that flag and add or remove the event handler instead of setting the flag to true or false.