Removing the $(window).resize Event in jQuery - javascript

Part of the page I'm developing requires a $(window).resize event to be added to a div when a user clicks a button, in order to toggle between resizing it with the window and leaving it fixed at its original size:
function startResize() {
$(window).resize(function() {
$("#content").width(newWidth);
$("#content").height(newHeight);
});
}
What I can't work out is how to "turn off" this event when the button is clicked again, so that the content stops resizing.
function endResize() {
// Code to end $(window).resize function
$("#content").width(originalWidth);
$("#content").height(originalHeight);
}
Any help with this would be greatly appreciated.

function endResize() {
$(window).off("resize");
$("#content").width(originalWidth);
$("#content").height(originalHeight);
}
Note that this is extremely obtrusive and might break other code.
This is better way:
function resizer() {
$("#content").width(newWidth);
$("#content").height(newHeight);
}
function startResize() {
$(window).resize(resizer);
}
function endResize() {
$(window).off("resize", resizer);
}

function startResize() {
$(window).on("resize.mymethod",(function() {
$("#content").width(newWidth);
$("#content").height(newHeight);
}));
}
function endResize() {
$(window).off("resize.mymethod");
}
using a namespace on the query method will allow to to turn off the resize event for you method only.

Related

Why this .js script stops working and is causing a browser freeze?

I've downloaded this Drupal 8 template and the site is at www.plotujeme.sk. It has an responsive navigation with this .js script:
function sidebar_menu() {
var windowsize = jQuerywindow.width(),
jQuerynav = jQuery("nav"),
slide = {
clear: function () {
jQuerybody.removeClass('toggled');
jQuery('.overlay').hide();
jQuery('.easy-sidebar-toggle').prependTo("header");
//jQuery('#search').prependTo("body");
jQuery('.navbar.easy-sidebar').removeClass('toggled');
jQuery('#navbar').removeAttr("style");
},
start: function () {
jQuery('.overlay').show();
jQuerybody.addClass('toggled');
jQueryhtml.addClass('easy-sidebar-active');
jQuerynav.addClass('easy-sidebar');
jQuery('.easy-sidebar-toggle').prependTo(".easy-sidebar");
//jQuery('#search').prependTo("#navbar");
jQuery('#navbar').height(jQuerywindow.height()).css({
"padding-top": "60px"
});
},
remove: function () {
jQuerynav.removeClass('easy-sidebar');
}
};
if (windowsize < 1003) {
jQuerynav.addClass('easy-sidebar');
jQuery('.easy-sidebar-toggle').on("click", function (e) {
e.preventDefault();
if (jQuerybody.hasClass('toggled')) {
slide.clear();
} else {
slide.start();
}
});
/*
jQueryhtml.on('swiperight', function () {
slide.start();
});
jQueryhtml.on('swipeleft', function () {
slide.clear();
}); */
} else {
slide.clear();
slide.remove();
}
}
and:
jQuery(document).ready(function () {
"use strict";
sidebar_menu();
jQuery(window).resize(function () {
sidebar_menu();
});
});
Problem is, that if I open responsive navigation by clicking on hamburger button, it works several times and then it stops working, the page and a browser freezes or is unresponsive for a long time. I also noticed that (even in template preview) sometimes it does not work at all and nothing happens after clicking hamburger icon. When I resize window multiple times sometimes it works sometimes not.
Do you see any error in the script that could possibly cause this problem?
Update: I also tried to use jQuery('.easy-sidebar-toggle').off("click"); just before jQuery('.easy-sidebar-toggle').on("click", function() {...}); but got the same results.
jQuery(window).resize(function () {
sidebar_menu();
});
As a result, whenever sidebar_menu function changes the window size, this function is called again and again, like a recursion, hence the freezing
I think the reason might be the following lines in the resize handler:
jQuerynav.addClass('easy-sidebar');
jQuery('.easy-sidebar-toggle').on("click", ...
They are run every time the window is resized by even one pixel, so a few dozen times a second if you drag the window border. Not sure about the first line, whether it adds the class over and over, but the second line certainly adds an event handler multiple times and fills up the stack. That's the reason your browser freezes. It just can't process the hundreds of registered events.
Just a guess, though.

.delay() not working on my .show() JQuery

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.

jQuery function not started

I have a weird problem. I have a freight calculation field to be executed if the User deletes a digit input , I hide one content. While running the script in chrome console, it is loaded, but when using the call in html, js it does not run. This is what I have.
https://jsfiddle.net/diasbass/u3xr0921/
jQuery(document).ready(function($) {
$("#btnFreteSimulacao").click(function() {
$("#txtCep").keyup(function() {
if ($("#txtCep").val()) {
$('p.montagem').hide();
} else {
$('p.montagem').show();
}
});
});
});
The keyup event handler is inside the click function, probably it is of no use.
Also need to check $("#txtCep").val().length for showing and hiding the p.montagem
jQuery(document).ready(function($) {
$("#txtCep").keyup(function() {
if($("#txtCep").val().length ==0) {
$('p.montagem').hide();
} else {
$('p.montagem').show();
}
});
});
jsfiddle
Here you are mixing two asynchronous events 1) Button click 2) Input keyup. Your code expects to work when both are happening same time. I would suggest remove dependency on one event. Like below.
$( "#btnFreteSimulacao" ).click(function() {
// $("#txtCep").keyup(function() {
if($("#txtCep").val()) {
$('p.montagem').hide();
} else {
$('p.montagem').show();
}
});
// });
});
If thats not possible, try to look towards promises.

Switch click and hover events based on width

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);

How to hide div on mouseout?

I'm trying to achieve a simple hover effect. When a user hovers an image (a view filled with images), it should show an extra div. No problem there.
But when I want to do the opposite thing, hide the same div when the user leaves the area of the div, it doesn't work: the div won't go away when leaving the div area (which should be done by default when using the hover, no?).
This is the code I use:
$(document).ready(function () {
$('.views-field-field-photo-fid').out(function () {
showDiv($(this), $('.views-field-title'));
});
$('.views-field-field-photo-fid').out(function () {
hideDiv($(this), $('.views-field-title'));
});
});
function showDiv(sender, object) {
$(object).show();
}
function hideDiv(sender, object) {
$(object).hide();
}
So far, I've tried .mouseenter, .mouseleave, .hover, .out, but nothing works to hide the div after leaving the div area.
UPDATE
I found the solution, more or less:
$(document).ready(function() {
$('#uicarousel-news-preview-block-2 .views-field-field-photo-fid').hover(
function() { $(this).find('.views-field-title').show(); },
function() { $(this).find('.views-field-title').hide(); }
)
});
But since there are a lot of .views-field-title, it's hiding/showing them too. So I figured to use the find, but no solution there.
Any ideas?
There is no jQuery function called out, I am not sure whether you are using a plugin or not. Anyway, this how a correct hover declaration should look like:
<script style="text/javascript">
$(document).ready(function() {
$('.views-field-field-photo-fid').hover(
function() {
showDiv($(this), $('.views-field-title'));
},
function() {
hideDiv($(this), $('.views-field-title'));
});
});
function showDiv(sender, object) {
$(object).show();
}
function hideDiv(sender, object) {
$(object).hide();
}
</script>
I suggest that you take a look at the jQuery.hover documentation.

Categories

Resources