Responsive Jquery toggle command - javascript

I am having an issue with my code. Whenever, I load up the page in the browser or in a mobile device, and I try to toggle it suddenly toggles multiple times when I just clicked on it once. I am trying to use this syntax code to make it responsive.
My CodePen
$(window).resize(function() {
$(".textcontent").hide();
if ($(window).width() <= 480) {
jQuery(function($) {
$(document).ready(function() {
$(".textcontent").hide();
$(".titleheader").click(function() {
$(this).toggleClass("active").next().slideToggle("fast");
return false;
});
});
});
}
});

The text toggles more than once because you are binding the click handler each time the resize event fires. Each bind attaches another handler so, depending on how many times the resize event fires, you might end up with many click handlers firing at once.
I suggest that you bind or unbind your click handler depending on the screen width, like so:
$(function() {
// function to toggle a text section
function toggleText(elm) {
$(elm).toggleClass("active").next().slideToggle("fast");
}
// resize event handler
$(window).on('resize', function() {
if ($(window).width() <= 480) {
// if window <= 480, unbind and rebind click handlers, and hide all text content
$(".titleheader").off('click').on('click', function() {
toggleText(this);
});
$(".textcontent").hide();
} else {
// if the window > 480, unbind click handlers and hide all text
$(".titleheader").off('click');
$(".textcontent").show();
}
}).trigger('resize'); // initialize - trigger the resize once upon load
});
WORKING EXAMPLE
You might also want to throttle or "debounce" your resize handler so it won't fire continuously in IE, Safari, and Chrome.
EDIT:
An alternate method is to set a flag to indicate whether the layout is "small" or "large". Then, only change the layout if the flag does not indicate the desired layout:
$(function() {
// layout flag (defaults to "not small")
var small = false;
// function to toggle a text section
function toggleText(elm) {
$(elm).toggleClass("active").next().slideToggle("fast");
}
// resize event handler
$(window).on('resize', function() {
if ($(window).width() <= 480) {
// if window <= 480 and the layout is "not small", bind click handlers and hide all text content
if (!small) {
console.log('made small');
$(".titleheader").on('click', function() {
toggleText(this);
});
$(".textcontent").hide();
// set the layout flag to "small"
small = true;
}
} else {
// if the window > 480 and the layout is "small", unbind click handlers and hide all text
if (small) {
console.log('made large');
$(".titleheader").off('click');
$(".textcontent").show();
// set the layout flag to "not small"
small = false;
}
}
}).trigger('resize'); // initialize - trigger the resize once upon load
});
WORKING EXAMPLE

Related

jQuery mouseenter & click events

I can' t find a solution for a RWD problem on my website.
I have one breakpoint (575.98px).
If resolution is above that breakpoint, "mouseenter" event is active to show hidden section:
if ($(window).width() > 575.98) {
$(".name").on("mouseenter", () => {
$(".description").fadeIn(250);
but for resolution below a breakpoint I want to off "mouseenter" event and active "onClick" event.
if ($(window).width() <= 575.98) {
$(".name").on("click", () => {
$(".description").show();
Currently, code is not working below decided breakpoint.
Please give me any hints of solution.
you can check out the px event.
$(".name").on("mouseenter", function() {
if ($(window).width() > 575.98){
$(".description").fadeIn(250);
}
});
$(".name").on("click", function() {
if ($(window).width() <= 575.98){
$(".description").show();
}
});

On Click events fires multiple times whenever the browser is being resized

I have this mobile menu that I'm currently building at the moment and I'm facing an issue with on('click') events. Whenever I try resizing the browser the event fires multiple times. At first load the script and event works fine, but when I start resizing the browser the event fires multiple times.
Below is a sample of the code I'm working on. Is there a way it fires only when once after resizing. I tried a temporary solution but it does not seem to take effect.
(function($){
'use strict';
var mobileMenu = {
init : function() {
$('.region-primary-menu').addClass('primary-mobile-menu');
$('.primary-mobile-menu .menu.-primary > .menu-item').addClass('mobile-menu-item');
$('.primary-mobile-menu .menu.-primary > .mobile-menu-item').on('click', function() {
$(this).toggleClass('active');
console.log('click');
})
},
clear : function() {
$('.primary-mobile-menu, .mobile-menu-item').removeClass('primary-mobile-menu mobile-menu-item');
}
}
$(document).ready(function() {
if ($(window).width() < 1180) {
mobileMenu.init();
}
else {
mobileMenu.clear();
}
});
$(window).on('resize', function(e) {
var resizeTimer;
clearTimeout(resizeTimer);
var resizeTimer = setTimeout(function() {
if ($(window).width() < 1180) {
mobileMenu.init();
}
else {
mobileMenu.clear();
}
}, 100)
});
})(jQuery)
It is because of click event being attached in mobileMenu.init(); function. On resize, a new clickevent is getting attached. You can use jQuery.off
$('.primary-mobile-menu .menu.-primary > .mobile-menu-item').off('click').on('click',
Because in your $(window).on('resize', function (e)... you do this :
if ($(window).width() < 1180) {
mobileMenu.init();
}
And in the mobileMenu.init() function definition you attach an event listener, so whenever you resize the window beneath 1180 size, it's going to attach more event listeners.
$('.primary-mobile-menu .menu.-primary > .mobile-menu-item').on('click' ...
Anyways the other answer tells you how to remove the event listener, which is what you should do to fix it.

Jquery ignores if-statement when resizing

I've written a function which makes my top-bar ($header) fixed if you scroll down on device ( < 992 ) which works fine. And when I resize, I use the function fixedTopCheck() again and it removes the .fixed class (in the else statement). This also works fine. But then when I scroll, it suddendly gives top the class .fixed again. So this part is getting ignored if ($(window).width() < 992) (which only happens when resizing, if I refresh with a window above 992px it works fine).
So is this resizing messing with the recognition of $(window).width()? (When I console log it, it shows the correct width size).
My code:
$(function()
{
var $header = $('header.top');
var $input = $header.find('input[type=search]');
var $search = $header.find('div.search');
var $container = $('main#content');
var $searchBtn = $search.find('button.icon-search');
var $closeBtn = $search.find('span.icon-cross');
$closeBtn.css('display', 'none');
function fixedTopCheck()
{
if ($(window).width() < 992)
{
$(window).on('scroll', function()
{
if ($(window).scrollTop() > 75)
{
$searchBtn.css('display', 'inline-block');
$closeBtn.css('display', 'none');
// Turn top into fixed menu
$header.addClass('fixed');
$container.addClass('fixed');
// Hide search bar and make it smaller
$input.css('display', 'none');
// Prevent search button to search
$searchBtn.on('click', function(e) {
e.preventDefault();
});
// Open search bar when clicking button
$(document).on('click','.icon-search',function()
{
$searchBtn.unbind('click');
$input.css('display', 'inline-block');
$searchBtn.css('display', 'none');
$closeBtn.css('display', 'inline-block');
$input.focus();
});
// Close search bar when clicking button
$(document).on('click','.icon-cross',function()
{
$searchBtn.on('click', function(e)
{
e.preventDefault();
});
$input.css('display', 'none');
$searchBtn.css('display', 'inline-block');
$closeBtn.css('display', 'none');
});
}
else
{
// Reverse fixed menu
$header.removeClass('fixed');
$container.removeClass("fixed");
$input.css('display', 'inline-block');
// Return search function
$searchBtn.unbind('click');
// Reset search form when going top and search form is still opened
$searchBtn.css('display', 'inline-block');
$closeBtn.css('display', 'none');
}
});
}
else
{
console.log("hello");
// Remove fixed top
if($header.hasClass("fixed"))
{
$header.removeClass("fixed");
}
if($container.hasClass("fixed"))
{
$container.removeClass("fixed");
}
$searchBtn.css('display', 'inline-block');
$closeBtn.css('display', 'none');
}
}
fixedTopCheck();
// if window is resized check again
$( window ).resize(function() {
fixedTopCheck();
});
});
Your code is following a lot of bad practices.
dont nest your event listeners inside each other. this will cause setting an event listener on the same component everytime its container event triggers (on each resize is VERY heavy aswell).
instead of using bind and unbind, make a check the width inside each event and follow actions depending on that.
another solution for replacing bind and unbind in your case is to keep the default button events, but disable the button so it cannot be clicked instead of unbind.
This will answer your question:
adding events inside resize, will not make them only work on that size in the if statement, you have to put the event outside the resize event and check whenever that event happens on the scroll and size.
When the page is loaded and the width of the page is <992px, the scroll event is created. When you resize to >992px the scroll event will still exist.
I would recommend binding the scroll event only once on page load (not after each resize) and check the width inside of that method to decide what it should do when it's scrolling.

jQuery on scroll listener after click event

What is the proper way to activate an on scroll listener after a click event?
I'm currently using:
$('.button').click(function (event) {
$(window).on("scroll", someFunction);
}
someFunction = function() {
//do stuff
$(window).off("scroll"); //disable scroll listener
}
On a click event I enable the scroll listener which runs someFunction. The function does stuff and disables the scroll listener when finished. The scroll listener is enabled again on click.
My concern is that I'm not doing it right. Please advise!
Note: The scroll listener cannot run indefinitely. It starts on click and must finish at the end of myFunction.
Note: I'm not trying to detect when user stops scrolling..
You could use jQuery .one():
$('.button').on('click', function() {
$(window).one('scroll', someFunction);
});
Every single click adds an additional scroll event listener. I would encapsulate the binding with an additional variable:
var isScrollBindingActive = false;
$('.button').click(function (event) {
if (!isScrollBindingActive) {
isScrollBindingActive = true;
$(window).on("scroll", someFunction);
}
}
someFunction = function() {
//do stuff
$(window).off("scroll"); //disable scroll listener
isScrollBindingActive = false; // allow binding again if wished
}
You can do it the following way:
$('.button').click(function (event) {
$(window).bind("scroll", someFunction);
}
someFunction = function() {
//do stuff
$(window).unbind("scroll"); // remove scroll listener
}

Accordion looping on resize

I have a menu that is hidden in an accordion when viewing on screens less than 600px.
On screens larger than 600px the menu is visible.
jsfiddle- http://jsfiddle.net/ashatron/zbzqoz2f/
it works ok, but when i resize the window to be greater than 600px, then go back to less than 600px then press view sitemap it loops the animation multiple times.
I think its running the function for every resize event, which is queing up the accordion and then looping it. But I'm not sure how best to order the syntax to get it to work.
Any help would be appreciated!
footernavmenufn = function() {
var current_width = $(window).width();
if (current_width < 600) {
$('.footer-accordion-head').show();
$('.footer-accordion-body').hide();
$('.footer-accordion-head').click(function () {
$(".footer-accordion-body").slideToggle('400');
// console.log('hmmm');
return false;
}).next().hide();
} else {
$('.footer-accordion-head').hide();
$('.footer-accordion-body').show();
}
};
$(document).ready(function () {
footernavmenufn();
});
$(window).resize(function(){
footernavmenufn();
//console.log('OMG-WHY-YOU-NO-WORK');
});
The issue is that everytime window is resized and the condition is met, you're binding a new click event handler, so after a while there'll be multiple event handlers causing chaos. Ideally your code should be something like
$(document).ready(function () {
$('.footer-accordion-head').click(function () {
$(".footer-accordion-body").slideToggle('400');
console.log('hmmm');
return false;
});
$(window).resize(footernavmenufn);
footernavmenufn(); // or $(window).trigger("resize");
});
footernavmenufn = function () {
var current_width = $(window).width();
if (current_width < 600) {
$('.footer-accordion-head').show();
$('.footer-accordion-body').hide();
} else {
$('.footer-accordion-head').hide();
$('.footer-accordion-body').show();
}
};
Updated Fiddle
Why do you have this code? Crazy one. Remove it:
if (current_width < 600) {
$('.footer-accordion-head').show();
$('.footer-accordion-body').hide();
$('.footer-accordion-head').click(function () {
$(".footer-accordion-body").slideToggle('400');
return false;
}
move the click declaration into the $(document).ready function.
at the moment everytime you resize the page that click function is being added again - so the repeat is once per page resize.
forked jsfiddle with change

Categories

Resources