I want to move an element (div) in the dom from one place to another using jQuery. I have the code working almost too well, in that it's appending my code every single time the browser is resized and then carries on until the browser crashes.
Here's my code:
$(window).resize(function() {
var bodyWidth = $(window).width();
if(bodyWidth < 740){
$('.GalleryHeader').appendTo('li');
}
});
How do I get this to only run once, so it only does the one time, and then perhaps put it back into it's original location in the dom when resizing back up over 740px.
Try
jQuery(function () {
var flag;
$(window).resize(function () {
var bodyWidth = $(window).width();
console.log(bodyWidth)
if (flag !== false && bodyWidth < 740) {
//move the element to new location
console.log('less')
flag = false;
} else if (flag !== true && bodyWidth >= 740) {
//put it back to original location
console.log('more')
flag = true;
}
}).resize();
})
Demo: Fiddle
Related
I have some javascript being fired when the screen reaches certain widths... I am trying to make it mobile responsive and need it to fire at different points on different devices...
var screenWidth = window.innerWidth;
if (screenWidth <= 812 && screenWidth > 414) {
$(window).scroll(function() {
var fromTopPxFirstBgChange = 2300;
var scrolledFromtop = $(window).scrollTop();
if (scrolledFromtop > fromTopPxFirstBgChange) {
$('body').addClass('secondBg');
}
else {
$('body').removeClass('secondBg');
}
});
}
if (screenWidth <= 414 && screenWidth > 375) {
$(window).scroll(function() {
var changeBg = 2190;
var scrolledFromtop = $(window).scrollTop();
if (scrolledFromtop > changeBg) {
$('body').addClass('secondBg');
}
else {
$('body').removeClass('secondBg');
}
});
}
if (screenWidth <= 375 && screenWidth > 320) {
$(window).scroll(function() {
var changeBgImage = 2380;
var scrolledFromtop = $(window).scrollTop();
if (scrolledFromtop > changeBgImage) {
$('body').addClass('secondBg');
}
else {
$('body').removeClass('secondBg');
}
});
}
So for the first one for example, I would like the screen to apply those changes at 414-812px.
Basically the background image is supposed to change when I am scrolled to the position on the page that I specified in each if statement (the class "secondBg" is a class I specified in the CSS with the new background image... I don't know if this is a JS error or a problem with other code. It seems to work uniform when I just have one if statement but when I add the three they sort of work and overwrite one another. I think the if statements are pretty clear and cannot see the problem.
You shouldn't be binding your listeners inside the if statements. You should instead have 1 listener and do checks inside like so:
$(window).scroll(function() {
if($(window).scrollTop() < 500) {
// Your code here
}
// add more checks here
});
Also, I'd throttle that as it's a really heavy operation. Take a look at this.
I'm trying to figure out how to repeatedly clone the contents of a div on scroll, thus giving the impression that the page goes on forever and ever. My markup thus far is as follows and a fiddle here too https://jsfiddle.net/guht49La/:
var inserated = false
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll >= 800 && inserated == false) {
var $button = $('.hd').clone();
($button).insertBefore('.ap');
inserated = true;
} else {
}
});
Although this only inserts it once, as I want to keep inserting it every 800px (for example) thus giving the impression that the page goes on forever and ever. Any suggestions on this would be greatly appreciated!
This will work
var inserated = false
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll >= 800) {
var $button = $('.hd').clone();
($button).insertBefore('.ap');
inserated = true;
} else {
}
});
This is a complete guess, but perhaps give this a go:
var nextInsert = 800;
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll >= nextInsert) {
var $button = $('.hd').clone();
($button).insertBefore('.ap');
nextInsert += 800;
} else {
}
});
It is working, but it clones the div just once because you changed the inserated variable to true after inserting the first clone. It will work indefinitely if you delete it:
var inserated = false
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll >= 800 && inserated == false) {
var $button = $('.hd').clone();
($button).insertBefore('.ap');
// inserated = true;
} else {
}
});
Notice that inserated = true; is commented out.
That code, however, can (and almost certainly) creates a huge amount of clones, so I'd suggest controlling the scrolling insertion point using something along the lines of Nat Karmios answer
My suggestion is similar to jbmartinez answer, except I would drop the inserated variable altogether and use classes to determine elements to be cloned:
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll >= 800) {
var $button = $('.hd').not(".cloned").clone();
$button.addClass("cloned");
($button).insertBefore('.ap');
} else {
}
});
Would still need to adjust the scrolling mark as noted above tho.
My website navigation needs to be converted into vertical nav so i measure the width of the viewport and bind it with resize and load function.then it executes the menuConvert() function. But in resizing window it causes multiple execution of the menuConvert() function.
My js codes are
$(window).bind('load resize', function(){
width = $(window).width();
console.log(width)
if(width < 800){
menuConverter(); // This is the function
}
});
I want to prevent the execution of the function if it is once executed.Can any one help
You can unbind event
$(window).bind('load resize', function(){
width = $(window).width();
console.log(width)
if(width < 800){
menuConverter(); // This is the function
//Unbind
$(window).unbind('load resize')
}
});
I would recommend the use of .on() and .off() inplace of .bind() and .unbind() respectively.
You can do something like
var flag800;
$(window).bind('load resize', function () {
if (width < 800) {
if (flag800 !== true) {
menuConverter(); // This is the function
flag800 = true;
}
} else {
flag800 = false;
}
});
Demo: Fiddle
use a simple bool variable.
var menexe = false;
$(window).bind('load resize', function(){
width = $(window).width();
console.log(width)
if(width < 800){
if(menexe === false){
menuConverter(); // This is the function
menexe = true;
}
}
});
I have some code that I found online that makes both divs on my website become equal lengths. However, this code only works after the page is refreshed and I have no idea what would cause this. Any help would be appreciated!
// EQUAL HEIGHTS
$.fn.equalHeights = function(px) {
$(this).each(function(){
var currentTallest = 0;
$(this).children().each(function(i){
if ($(this).height() > currentTallest) { currentTallest = $(this).height(); }
});
if (!px && Number.prototype.pxToEm) currentTallest = currentTallest.pxToEm(); //use ems unless px is specified
// for ie6, set height since min-height isn't supported
if ($.browser.msie && $.browser.version == 6.0) { $(this).children().css({'height': currentTallest}); }
$(this).children().css({'min-height': currentTallest});
});
return this;
};
// just in case you need it...
$.fn.equalWidths = function(px) {
$(this).each(function(){
var currentWidest = 0;
$(this).children().each(function(i){
if($(this).width() > currentWidest) { currentWidest = $(this).width(); }
});
if(!px && Number.prototype.pxToEm) currentWidest = currentWidest.pxToEm(); //use ems unless px is specified
// for ie6, set width since min-width isn't supported
if ($.browser.msie && $.browser.version == 6.0) { $(this).children().css({'width': currentWidest}); }
$(this).children().css({'min-width': currentWidest});
});
return this;
};
// CALL EQUAL HEIGHTS
$(function(){ $('#equalize').equalHeights(); });
This behavior happens because the plugin was not well written. I've modified it for you and now it should work.
Working DEMO
Plugin script:
// EQUAL HEIGHTS
$.fn.equalHeights = function(px) {
var currentTallest = 0;
$(this).each(function(){
$(this).siblings().each(function(i){
if ($(this).height() > currentTallest) {
currentTallest = $(this).height();
}
});
});
if (!px && Number.prototype.pxToEm) {
currentTallest = currentTallest.pxToEm();
}
$(this).siblings().css({'height': currentTallest, 'min-height': currentTallest});
return this;
};
You can modify the equalWidths plugin to work as this plugin.
put all your code in jquery ready function. inside ready function code executes when the DOM is ready
$(document).ready(function(){
//your code
});
I have the following code. It set a filter bar in a search results page in a fixed position in the window after scrolling down to a certain point:
var docked;
var filters = document.getElementById('filters');
var init = filters.offsetTop;
function scrollTop() {
return document.body.scrollTop || document.documentElement.scrollTop;
}
window.onscroll = function () {
if (!docked && (init - scrollTop() < 0)) {
filters.style.top = 0;
filters.style.position = 'fixed';
filters.className = 'docked';
docked = true;
} else if (docked && scrollTop() <= init) {
filters.style.position = 'absolute';
filters.style.top = init + 'px';
filters.className = filters.className.replace('docked', '');
docked = false;
}
}
My issue is (and it's more curiosity) - if I place this code at the top of my file (in the <head>), it doesn't work at all. The filter section doesn't scroll with the window as it should. However, when I place this code at the bottom of the file (right above the closing </body> tag), it works just fine.
Why is this? Does this have something to do with the way the code works? Or could it be just a quirk or bug in the rest of my file causing this?
Wrap your assignments in window.onload = function(){ /* your code here */ }; and it will run. The reason being that your assignment of var filters = document.getElementById('filters'); comes back as undefined since that element does not exist during page load at the time you reference it.
Example:
var docked;
var filters;
var init;
window.onload = function(){
filters = document.getElementById('filters');
init = filters.offsetTop;
};
if you do this, it should work:
$(document).ready(window.onscroll = function () {
if (!docked && (init - scrollTop() < 0)) {
filters.style.top = 0;
filters.style.position = 'fixed';
filters.className = 'docked';
docked = true;
} else if (docked && scrollTop() <= init) {
filters.style.position = 'absolute';
filters.style.top = init + 'px';
filters.className = filters.className.replace('docked', '');
docked = false;
}
}
);