Resize script appends object, does it over and over again - javascript

I have the following code in a JavaScript file:
$(document).ready(function() {
detectscreen();
});
$(window).resize(function(){
detectscreen();
});
function windowWidth() {
if(!window.innerWidth) {
// user is being a git, using ie
return document.documentElement.clientWidth;
} else {
return window.innerWidth;
}}
function detectscreen() {
if (windowWidth()>1280) {
$('body').append('<div id="gearsfloat"></div>');
}}
Basically, what it does is append an object to the end of the document if the width is less than 1280 pixels, however what this does is append it every single time the page is resized.
I don't think I can use the once function because it would only run it once and then the next time it is resized, it's dead. Anything I can do?
NOTE: I, in fact, DO want it to be checked on the resize of the page, but the effect is that it happens over and over again.
if (windowWidth()>1280 && !$('gearsfloat')) {
$('body').append('<div id="gearsfloat"></div>');
}
The above (by Jason) works does not work but then it won't delete it when it gets less than 1280. Is there anything I can do?

Keep track of whether the element exists or not, and add/remove it when the condition changes. That way you will only add it once, it will be removed when it shouldn't be there, and you don't do any unneccesary adding or removing:
var gearsExists = false;
function detectscreen() {
var shouldExist = windowWidth() > 1280;
if (shouldExist != gearsExists) {
if (shouldExist) {
$('body').append('<div id="gearsfloat"></div>');
} else {
$('#gearsfloat').remove();
}
gearsExists = shouldExist;
}
}

if (windowWidth()>1280 && !$('gearsfloat')) {
$('body').append('<div id="gearsfloat"></div>');
}
Check if the element already exists first?

if you dont want the function to be called when the window is resized, then why are you binding the resize function?
wont the document ready function always be called before the resize function anyway, so you are guaranteed to have your element appended?

Related

.scroll() is only running once

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

Firing multiple Events on JQuery Resize

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.

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

unbind a jQuery plugin when no destroy argument is given

I'm using a plugin which is called Sidr to create a Facebook like sidebar. It intialized with:
$('#menu_trigger').sidr({
name: 'sidr-right',
side: 'right'
});
Problem is, that I only want to have this effect at a specific viewport size. I know that many jQuery plugins come with a something like a destroy argument to unload the script. But this plugin does not.
Does anyone know how I could unbind this function off #menu_trigger when a specific browsersize is triggered.
Like:
enquire.register("screen and (max-width:560px)", {
$('#menu_trigger').sidr({
// unload, unbind
});
}
Thanks
http://jsbin.com/bemimu/8/edit
You can use unbind and pass in the plugin reference to the selected elements, then check the window size in JavaScript. $.sidr('close', 'sidr-right');
JS:
function clickForSidr() {
var ww = document.body.clientWidth;
if(ww < 560){
if(sidrIsOpen){
$.sidr('close', 'sidr-right');
}else {
$.sidr('open', 'sidr-right');
}
sidrIsOpen = !sidrIsOpen;
}
};
var sidrIsOpen = false;
$('.unbindme').on('click',function(){
clickForSidr();
});
MARKUP:
<div class="unbindme" >unbindme</div>

document ready after dom manipulation

I'm doing an application with Phonegap and I'm using a self-built slide transition to change the pages.
It works like this:
Every page is a div with 100% height and width, so if I change the Page, I set the next div right to the currently active and slide both to the left side.
Now to the Problem: the sliding works fine, but it's executed before the content of the right div is completely loaded. So the right div slides in empty, and only after a few hundred miliseconds the content will appear.
I tried it with document.ready, but as I've read this event is only executed the first time the DOM is loaded.
Does anybody know how I can wait for the DOM to be completely rendered again after I've manipulated the DOM with Javascript?
In your case, you can pick one element in the content of the next div and keep checking it with $(...).length. If the value is > 0, the DOM is loaded and you can change the page.
You may want to try this function:
Function.prototype.deferUntil = function(condition, timeLimit) {
var ret = condition();
if (ret) {
this(ret);
return null;
}
var self = this, interval = null, time = ( + new Date());
interval = setInterval(function() {
ret = condition();
if (!ret) {
if (timeLimit && (new Date() - time) >= timeLimit) {
// Nothing
} else {
return;
}
}
interval && clearInterval(interval);
self(ret);
}, 20);
return interval;
};
Usage:
(function() {
console.log('Next page loaded');
}).deferUntil(function() {
return $('#nextDiv').length > 0;
}, 3000);
The above example will check the div that has id="nextDiv" in every 20ms (not longer than 3 seconds). When the div is loaded, it will show 'Next page loaded' in the console.
You can try on this fiddle
There is a DOMNodeInserted event that is supposed to work like document.ready but for individual DOM nodes. But it is deprecated and has lots of issues. StackOverflow users found a good alternative to it that works quite well in all mobile browsers: Alternative to DOMNodeInserted
Here is a function that will trigger a callback once all images matching a jquery selector have finished loading
Js Fiddle Sample
//css
input {width: 420px;}
//html
<div id="container"></div>
<input type="text" value="http://goo.gl/31Vs" id="img1">
<br><input type="text" value="http://wall.alafoto.com/wp-content/uploads/2010/11/Fractal-Art-Wallpapers-09.jpg" id="img2">
<br><input type="text" value="http://pepinemom.p.e.pic.centerblog.net/ssg8hv4s.jpg" id="img3">
<br><input type="button" value="Load images" name="loadImages" id="btn">
<div id="message"></div>
//javascript
//Call a function after matching images have finished loading
function imagesLoadedEvent(selector, callback) {
var This = this;
this.images = $(selector);
this.nrImagesToLoad = this.images.length;
this.nrImagesLoaded = 0;
//check if images have already been cached and loaded
$.each(this.images, function (key, img) {
if (img.complete) {
This.nrImagesLoaded++;
}
if (This.nrImagesToLoad == This.nrImagesLoaded) {
callback(This.images);
}
});
this.images.load(function (evt) {
This.nrImagesLoaded++;
if (This.nrImagesToLoad == This.nrImagesLoaded) {
callback(This.images);
}
});
}
$("#btn").click(function () {
var c = $("#container"), evt;
c.empty();
c.append("<img src='" + $("#img1").val() + "' width=94>");
c.append("<img src='" + $("#img2").val() + "' width=94>");
c.append("<img src='" + $("#img3").val() + "' width=94>");
evt = new imagesLoadedEvent("img", allImagesLoaded);
});
function allImagesLoaded(imgs) {
//this is called when all images are loaded
$("#message").text("All images loaded");
setTimeout(function() {$("#message").text("");}, 2000);
}
You could use jQuery ajax to load the content, and on success run a function with the slide.
$("#page1").load('page2.html', function() {
//do your custom animation here
});
Althoug I'm not completely sure how you're loading the content. Is it static (Already there but just not visible?) Or is it loaded with ajax?
EDIT: You could just do a small .delay() or setTimeout with a few millisec, and then animate the sliding.
I had a similar problem making a masonry site responsive. I use window.onload which waits for all elements to complete loading before initialising masonry.js. I also placed the window.onload inside .onchange function and it fired everytime the viewport resized.
I am sure applying similar principles will solve your problem.
try once
$(window).bind('load',function(){
//code
});
Maybe you can set an event on your div.
myDiv.onafterupdate = myHandler;
function myHandler() {
// Do here what you want to do with the updated Div.
}
Does this help you?
In jquery you could use $() just after your DOM manipulation code.
$(function(){
//code that needs to be executed when DOM is ready, after manipulation
});
$() calls a function that either registers a DOM-ready callback (if a function is passed to it) or returns elements from the DOM (if a selector string or element is passed to it)
You can find more here
difference between $ and $() in jQuery
http://api.jquery.com/ready/

Categories

Resources