If Statements not Targeting Intended Screen Widths - javascript

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.

Related

jQuery: clone div multiple times on scroll

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.

Only execute JS if the screen size is more than 1024px?

I have a sidebar that becomes position:fixed when the bottom of the div is visible (followed this tutorial). My problem is I only need the JS to work if the screen size is more than or equal to 1025px.
I know I need something along the lines of if($(window).width() > 1025), but I can't figure out where that needs to be. I'm not great with JS so any help would be appreciated.
Demo
JS
$(function () {
if ($('.leftsidebar').offset()!=null) {
var top = $('.leftsidebar').offset().top - parseFloat($('.leftsidebar').css('margin-top').replace(/auto/, 0));
var height = $('.leftsidebar').height();
var winHeight = $(window).height();
var footerTop = $('#footer').offset().top - parseFloat($('#footer').css('margin-top').replace(/auto/, 0));
var gap = 100;
$(window).scroll(function (event) {
// what the y position of the scroll is
var y = $(this).scrollTop();
// whether that's below the form
if (y+winHeight >= top+ height+gap && y+winHeight<=footerTop) {
// if so, ad the fixed class
$('.leftsidebar').addClass('leftsidebarfixed').css('top',winHeight-height-gap +'px');
}
else if (y+winHeight>footerTop) {
// if so, add the fixed class
$('.leftsidebar').addClass('leftsidebarfixed').css('top',footerTop-height-y-gap+'px');
}
else
{
// otherwise remove it
$('.leftsidebar').removeClass('leftsidebarfixed').css('top','315px');
}
});
}
}
This should work:
var flag = false;
// This will keep on checking for window size while you are scrolling.
$(window).on("scroll", function() {
if (flag){
// Do whatever you want here
alert("hey");
}
});
$(window).on("resize", function() {
if ($(window).width() >= 1025){
flag = true;
} else {
flag = false;
}
})
From my comment: Just put that if($(window).width() > 1025) inside the function provided to the scroll event.
e.g.
$(window).scroll(function (event) {
if ($(window).width() > 1024) {
// what the y position of the scroll is
var y = $(this).scrollTop();
// whether that's below the form
if (y + winHeight >= top + height + gap && y + winHeight <= footerTop) {
// if so, ad the fixed class
$('.leftsidebar').addClass('leftsidebarfixed').css('top', winHeight - height - gap + 'px');
} else if (y + winHeight > footerTop) {
// if so, ad the fixed class
$('.leftsidebar').addClass('leftsidebarfixed').css('top', footerTop - height - y - gap + 'px');
JSFiddle: http://jsfiddle.net/TrueBlueAussie/3w5dt/31/
Notes:
not that 1 PX matters, but you did say > 1024px, hence changing 1025 to 1024 :)
First of all you should have a look at the jQuery documentation. The $.browser function was removed in jQuery 1.9. This can end up in serious problems in your code.
Just add something like the follwing code in the first if condition:
if (!msie6 && $('.leftsidebar').offset()!=null && $(window).width() > 1025 ) {
...
}
That should be all. If you want, that javascript should react on window resize just add something like the following
$(window).on('resize', function( event ) { /* code here */ }).trigger('resize');
if(screen.width >= 1024)
{
$(window).scroll(function (event) {
//Write your function code here
});
}
I hope it will help you.

Javascript not declaring window size in tutorial

I'm working through a Lynda.com tutorial on responsive web experience. My Javascript is mostly working. From the instructor the goal of the JS is "we are determining the windowWidth based on the window outerWidth." Then we output that info and whether the screen is small, medium or large (the #media breakpoints).
As in, "945 (931+14) is large". My work so far is live with it.
The problem is that 'large' isn't changing to 'medium' and then 'small' as the window width changes.
Thanks!
If it's helpful, here's a codepen with all the HTML/CSS code. And here's the JS.
/* JavaScript Document */
var windowSize = '';
var windowWidth = 0;
var actualSize = 0;
$(document).ready(function () {
checkBrowserSize();
loadHero();
});
function checkBrowserSize() {
windowWidth = window.outerWidth;
var contentWidth = $('body').width();
var sizeDiff = windowWidth - contentWidth;
actualSize = windowWidth - sizeDiff;
if (actualSize > 800) { newWindowSize = 'large'; }
if (actualSize <= 800 && actualSize > 500) {newWindowSize = 'medium'; }
if (actualSize <= 500){ newWindowSize = 'small'; }
$('h1').html(windowWidth +' ('+contentWidth+'+'+sizeDiff+')'+' is '+newWindowSize);
}
function loadHero() {
$('#hero').load('content/hero_content_large.html');
}
Your problem is that the function only runs once on document ready. You have to bind your function to an onresize event so the function runs every time the resize event gets triggered (read about event handlers)
Here is a JavaScript example: http://www.w3schools.com/jsref/event_onresize.asp
And here is a jQuery example:
http://www.w3schools.com/jquery/event_resize.asp

Getting a floating div to stop upon reaching another div

I have a floating div on the sidebar that scrolls with the page. Is there a way to add code that makes it stop when it reaches the footer?
See code in action: http://openbayou.staging.wpengine.com
jQuery code used to float div:
$j=jQuery.noConflict();
$j(document).ready(function($) {
//this is the floating content
var $floatingbox = $('#one');
if($('#primary').length > 0){
var bodyY = parseInt($('#primary').offset().top) - 20;
var originalX = $floatingbox.css('margin-left');
$(window).scroll(function () {
var scrollY = $(window).scrollTop();
var isfixed = $floatingbox.css('position') == 'fixed';
if($floatingbox.length > 0){
$floatingbox.html();
if ( scrollY > 1561 && !isfixed ) {
$floatingbox.stop().css({
position: 'fixed',
top: 10,
});
} else if ( scrollY < 1561 && isfixed ) {
$floatingbox.css({
position: 'relative',
top: 0,
});
}
}
});
}
});
Why not just set the z-index of the sidebar behind the z-index of the footer?
EDIT: I didn't like the result of this so I went and made this work in jquery the way you want it...
try this for your scroll function:
$(window).scroll(function () {
floatingbox = $("#one");
if(floatingbox.length > 0){
//get our current scroll position
var scrollY = $(window).scrollTop();
//get the position of the tag cloud relative to the document
var contentY = ($("#sidebar .sidebar-tag-cloud").offset().top + $("#sidebar .sidebar-tag-cloud").outerHeight(false));
//calculate the largest possible top margin size before it starts to overlap the footer
var lastY = $("#footer").offset().top - $("#one").outerHeight(false);
//check if our scroll location is past the bottom of the tag cloud
if ( scrollY > contentY )
{
//check if the current top position is less than the maximum position
if(floatingbox.offset().top<lastY)
{
//keep scrolling
floatingbox.stop().animate({"marginTop":scrollY-contentY});
}else
{
//check if we have scrolled back up and have a space at the top
if(scrollY<floatingbox.offset().top)
{
floatingbox.stop().animate({"marginTop":scrollY-contentY});
}else
{
// hard set to the maximum position
floatingbox.stop().css({"marginTop":lastY-contentY});
}
}
}
}
});
I also made it a little more dynamic by getting the location of the bottom of the tag cloud and using that instead of your hard-coded number.
Alright, after looking at your latest jsfiddle. I have modified that code to work with yours. http://jsfiddle.net/Tgm6Y/4430/ This will not have the animate lag and should work well for you.
$('#one').followTo('#two','#pointFive');
just replace #two with #footer and #pointFive with "#sidebar .sidebar-tag-cloud" and this should work in your code.
UPDATE: Found a solution to my problem.
$(function () {
var msie6 = $.browser == 'msie' && $.browser.version < 7;
if (!msie6) {
var top = $('#one').offset().top;
$(window).scroll(function (event) {
var y = $(this).scrollTop() + 20;
if (y >= top) {
$('#one').addClass('fixed');
}
else {
$('#one').removeClass('fixed');
}
// don't overlap the footer - pull sidebar up using a negative margin
footertotop = ($('#footer').position().top);
scrolltop = $(document).scrollTop() + 760;
difference = scrolltop - footertotop;
if (scrolltop > footertotop) {
$('#one').css('margin-top', 0 - difference);
}
else {
$('#one').css('margin-top', 0);
}
});
}
});
What this does is it stops before the footer and I can configure the stopping point.
I appreciate all the help in solving my problem!

if element exist on document then add an addittional value into method

I really need some help with this, I dont know javascript well at all to be honest, a friend of mine put some of this together a few months ago ive just added $contentContainer and added these variables but I just need one more thing added to if for it to suite my needs...
<script type="text/javascript">
// DOM Container Resize Handler
var adjustStyle = function() {
var winWidth = $(window).width(),
width = parseInt(winWidth),
container = $('body .fixed');
contentContainer = $('body .content');
if (width >= 1454) {
container.css('width','1454px');
contentContainer.css('width','1210px');
} else if ((width < 1454) & (width >= 1212)) {
container.css('width','1212px');
contentContainer.css('width','968px');
} else {
container.css('width','970px');
contentContainer.css('width','726px');
}
};
$(function() {
var filterWrap = $("#filterWrap"),
offset = filterWrap.offset(),
topPadding = 15;
$(window).scroll(function() {
if ($(window).scrollTop() > offset.top) {
filterWrap.stop().animate({
marginTop: $(window).scrollTop() - offset.top + topPadding
});
} else {
filterWrap.stop().animate({
marginTop: 0
});
};
});
// DOM Container Resize Handler - Initialization
$(window).resize(function() {
adjustStyle();
});
adjustStyle();
});
</script>
I need to modify this script to search through the document and IF document DOES NOT contain ('body .asideContent') to add 252px to the object contentContainer.css method
Don't worry about the fileerWrap function this works fine :)
I really appreciate the help
Should be something like this :)
if($("body.asideContent").length === 0){
var width = contentContainer.css('width');
contentContainer.css('width',width + 252 + "px");
}

Categories

Resources