JavaScript width checking to disable event - javascript

I have some code which adds a class at a certain page scroll point, which I need for a particular scenario however I do not need this on mobile.
$(window).scroll(function() {
if ($(".navbar").offset().top > 500) {
$(".navbar-fixed-top").addClass("top-nav-collapse");
} else {
$(".navbar-fixed-top").removeClass("top-nav-collapse");
}
});
Could I combine this with something like...
function checkWidth() {
if ($(window).width() < 514) {
$('#menu2').addClass('f-nav');
} else {
$('#menu2').removeClass('f-nav');
}
}
$(window).resize(checkWidth);
To say switch the classes but only if the width is above say 480px?
I appreciate this is probably newbie but I wondered if the window scroll function could just be part of the if condition?

Try out this fiddle:https://jsfiddle.net/cxn6t946/
You need to put if ($(window).width() > 514) inside the scroll function and it will work.
Edited my answer as the previous fiddle had a problem. It worked fine on sceen size >514 and added top-nav-collapse on an offset>500. However on returning to screen size <514 the top-nav-collaspe class remained there. So had to rewrite the fiddle by incorporating resize.
Check out the updated fiddle:https://jsfiddle.net/cxn6t946/1/
Hope this helps.

If you place the conditional check on the event listener as opposed to the action of the event listener, you can save yourself some resources on mobile while also accomplishing your task.
Try:
if ($(window).width() > 514) {
$(window).scroll(function() {
if ($(".navbar").offset().top > 500) {
$(".navbar-fixed-top").addClass("top-nav-collapse");
} else {
$(".navbar-fixed-top").removeClass("top-nav-collapse");
}
});
}
By doing the conditional check before applying the event listener, you're not adding an event listener on mobile devices and saving the resources it would be using. This also keeps you from having to add any conditional logic to your functionality since it won't be getting called without the scroll listener being applied on devices smaller than 514px.

Related

slideToggle works multiple times when watching screen resize

I'm trying to apply the slideToggle function over a menu based on screen size , but this code is applying the function multiple times with just one click , tried every solution here but nothing works .
I know the problem is the click event inside a window resize, but the application should be like that, so please i need alternative solution to have a working code.
$(window).on("resize", function () {
if (screen.width < 768) {
$(".part-heading").click(function (e) {
$(this).next(".sections").slideToggle("slow");
});
}
});
You are registering multiple event listeners, one every time the screen size change. And when you click all of them will run. You can change your script as below, so check the size on each click rather than watching the resize:
$(".part-heading").click(function (e) {
if (screen.width < 768) {
$(this).next(".sections").slideToggle("slow");
}
});

How to run the script both 'on load' and 'on resize' (on a particular window width!) in jQuery?

In my current website project I've integrated Alvaro Trigo's FullPage plugin but since it had a very uncommon behaviour on mobile devices (also due to my project's design requirements), I've decided to switch it off when the viewport width is below 768px. For this purpose I just add a simple if-statement to the script:
$(document).ready(function(){
if ($(window).width() > 768 ) {
$('#fullpage').fullpage({
// code... code... code...
});
}
});
The problem is that it only takes effect after refreshing the page; so when I go below 768px and reload the page the plugin is switched off, but when I then resize the browser above the mentioned breakpoint, it's still off (and vice versa). I think I should add some lines of code dealing with resize, but unfortunately my current knowledge of JS/jQ doesn't let me do that.
Thanks in advance for your time.
This should work:
$(window).resize(function(){
if ($(window).width() > 768 ) {
//do your thing here
}
}
Use $(document).resize(function(){ /* do stuff*/ }) instead.
You can then use $(document).trigger('resize') on onload
Here is how to run an anonymous function both when DOM ready fires and when on resize fires:
$(document).ready(function() {
$(window).on('resize', function() {
//code to run
})
.trigger('resize');
});
You can use the jQuery resize event. See here
Put your code, what you want to do into a function. Call that function on document ready with $(function() {});, and when you resize the window.
$(function () {
function doSomething() {
$('#fullpage').fullpage({
//The code
});
}
$(window).resize(function () {
//Do it on resize
if ($(window).width() > 768) {
doSomething();
}
});
//Do it when page loads.
doSomething();
});

Jquery unbinding click() for an <a> tag

I have a simple
<a id="eID" href="#showCSSOnlyModalElement">Element</a>.
And I want to introduce some click functionality based on viewport/device size. However, unbinding this click event, disables the standard clickable functionality of the <a> element. I want to retain the default behavior of the <a> element for larger viewport/device.
$( window ).resize(function() {
if ((document.documentElement.clientWidth < 700) || (screen.width < 700)){
$('#eID').click(function(){//hideSomeOtherElements});
}
else {
$('#eID').unbind('click');
}
});
Testing:
Start with large desktop viewport. <a> works fine.
Resize to viewport = 500. The <a> and onClick functionality work fine.
Resize to large desktop viewport. The <a> does not work.
I have tried the .on/.off route also per jQuery documentation. Same result.
Please help.
I probably wouldn't bind/unbind, I'd just check when the click occurs:
$("#eID").click(function(e) {
if ((document.documentElement.clientWidth < 700) || (screen.width < 700)){
// Do something for smaller viewports
e.preventDefault(); // Prevents default behavior of click
// You can also use `e.stopPropagation()` to
// stop the event propagating, or use
// `return false` to do both.
}
else {
// Don't do anything, allow default behavior of click
// (You probably don't need the `else` at all, it's just to make
// clear you're not doing anything here.)
}
});
This is not only simpler, but easier to debug.
Try
function callback {
...
}
$('#eID').bind('click', callback);
$('#eID').unbind('click', callback);
The jQuery API recommends that you specify the callback otherwise bad things could happen.

jQuery Click event triggers more times on every window resize

People!
This is the first time I come here to ask something, so far, always when I had a problem, I could find a good answer here. So, in first place, thanks for this amazing community!
Now let's go to the problem:
I'm doing a responsive menu that check the window.resize event and, when it fits the minimum browser width, a click function for a button is allowed. If the browser width is greater, then the click function is unbound. I need to do this because the same element that is the button on the mobile version, is a visual element on the desktop version.
The problem is that, with the code that I have now, when the page is loaded, the click function works fine. But, if I resize the browser and click on the element again, it triggers more than once the state, sometimes leaving the impression that the function isn't triggered. And, if I resize the browser again, it triggers the click function more than the last time I clicked. Really annoying.
To help understand what is happening, I've made a simple example. Here's is the simple code (just to check the click function issue):
HTML:
<ul>
<li><span class="sub-toggle">Testing 01</span></li>
<li><span class="sub-toggle">Testing 02</span></li>
<li><span class="sub-toggle">Testing 03</span></li>
</ul>
CSS:
.sub-toggle{
display:block;
padding: 20px;
}
.sub-toggle.active{
background-color: #ffcc00;
color: #fff;
}
Javascript (jQuery):
jQuery(function($){
var i = 1;
// check if browser size is compatible with click event
onResize = function() {
// if browser size is ok, do the click function
if($(window).width() <= 480){
// click function
$('.sub-toggle').click(function(){
alert('click');
if($(this).hasClass('active')){
alert('active');
$(this).removeClass('active');
} else {
$(this).addClass('active');
}
});
} else{
// if browser size is greater than expected, unbind the click function
$('.sub-toggle').removeClass('active').unbind('click');
}
// just checking how many times the resize function is triggered
console.log('resize: '+ i);
i++;
}
$(document).ready(onResize);
var timer;
$(window).bind('resize', function(){
timer && clearTimeout(timer);
timer = setTimeout(onResize, 500);
});
});
(Edited to remove some unnecessary code)
If you want to see it in action, I've made a Fiddle (try resize the output frame to see it working): http://jsfiddle.net/C7ppv/1/
Maybe I've missing something really stupid, since I don't have a huge knowledge in JavaScript. But what I want to do is just trigger the click event once, even if multiple resizes.
I hope I could explain well my problem. I've searched and didn't found a solution for this issue (or maybe I just didn't know really well what to look for).
Any help would be appreciated!
Your code currently binds a new click events every time the method onResize is called and the window width is less than or equal to 480px.
Simply unbind any existing click events on the .sub-toggle element before binding a new one.
$('.sub-toggle').unbind('click').click(function() {
...
});
DEMO
The resize event is triggered multiple times during resizing, and each time you're binding a new click handler. My suggestion: bind only once, from outside the resize handler, and set a flag while resizing to let the click handler know if it should do something or not.
Then you won't even need to defer the handling of resize with setTimeout as you're doing.
DEMO
jQuery(function($){
var i = 1;
// flag to allow clicking
var clickAllowed = true;
// click function
$('.sub-toggle').click(function(){
if(clickAllowed) {
alert('click');
if($(this).hasClass('active')){
alert('active');
$(this).removeClass('active');
} else {
$(this).addClass('active');
}
}
});
// check if browser size is compatible with click event
onResize = function() {
//if browser size is ok, do the click function
if($(window).width() <= 480){
clickAllowed = true;
}
else{
// if browser size is greater than expected, disallow clicking
clickAllowed = false;
}
// just checking how many times the resize function is triggered
console.log('resize: '+ i);
i++;
}
$(document).ready(onResize);
var timer;
$(window).bind('resize', onResize);
});
Move $('.sub-toggle').click(function(){...} outside the onResize event handler and move if($(window).width() <= 480){...} into the click handler.

unbind jQuery infinite scroll when used alongside pjax

I'm using a very simple jQuery infinite scroll to eliminate the need for numbered pagination but I'm coming across a small issue.
When I go to the page that uses the infinite scroll and it loads it, the infinite scroll will work as planned but when I then navigate away from that page using pjax it will still run on all other site pages as it's still a loaded function?
What can I do to basically tell the infinite scroll function to only run on the pages I want it to or somehow reset it when pjax changes the page?
Here's my code for the infinite scroll so far:
$(window).on("scroll", function() {
if($(window).scrollTop() == $(document).height() - $(window).height()){
// Do scroll pagination, load content into #load-here ..
}
}
This is how I want the scroll to function:
$("a:not(.no-dynamic)").pjax("#main");
$(document).on('pjax:end', function() {
if($("#load-here").length == 0) {
$(window).off("scroll");
}
else
$(window).on("scroll");
});
I had similar issue. Fixed it by unbinding the scroll handler if a particular div (hidden pagination div) doesn't exists any more.
$(window).scroll(function()
{
if($('#pagination').length == 0){
$(window).unbind('scroll',<<scroll handler function>>);
return;
}
......
}
Try this:
Instead of $(window).scroll(), do:
$(window).on('scroll', function() {
// stuff
});
I've never used pjax, but according to the docs, there's an end callback you can use:
$(document)
.on('pjax:end', function() {
$(window).off('scroll');
});
The idea is to unbind the "scroll" event from window every time a pjax request ends.
handle window.onbeforeunload to unbind infinite scroll

Categories