jQuery Else / If Prevent Inheriting Styles - javascript

I am wondering how I prevent elements from retaining the same inline styles in my else / if breakpoints.
What I am doing is trying to change styling based on window width. Very much the same approach as CSS media queries, except I need to increment a numeric value, which is something I cannot do with CSS, hence the jQuery.
When I get to my final else if - where I apply an opacity to the first 5 articles - if I resize my browser back down to the less than 720px, those articles retain the opacity, which I do not want.
Any help is greatly appreciated.
$(document).ready(function() {
function checkWidth() {
var windowSize = $(window).width();
if (windowSize >= 1 && windowSize <= 479) {
var posTop = 0;
$('#main article').each(function() {
$(this).css('top', posTop + 'px');
posTop += 160;
});
} else if (windowSize >= 480 && windowSize <= 719) {
var posTop = 0;
$('#main article').each(function() {
$(this).css('top', posTop + 'px');
posTop += 240;
});
} else if (windowSize >= 720 && windowSize <= 959) {
$('#main article').slice(0, 5).each(function() {
$(this).css('opacity', 0.4);
});
}
}
// Execute on load
checkWidth();
// Bind event listener
$(window).resize(checkWidth);
});​

Add $('#main article').css('opacity', 1); at the begining of checkWidth function. By the way, you should rename this function, because what it does is not how it sounds. And there is no need in posTop variable and last each loop. My variant with some refactoring:
$(document).ready(function() {
function changeStylesDependsOnWidth() {
$('#main article').css('opacity', 1);
var windowSize = $(window).width();
if (windowSize >= 1 && windowSize <= 479) {
$('#main article').each(function(i) {
$(this).css('top', i * 160 + 'px');
});
} else if (windowSize >= 480 && windowSize <= 719) {
$('#main article').each(function(i) {
$(this).css('top', i * 240 + 'px');
});
} else if (windowSize >= 720 && windowSize <= 959) {
$('#main article').slice(0, 5).css('opacity', 0.4);
}
}
changeStylesDependsOnWidth();
$(window).resize(changeStylesDependsOnWidth);
});​

Related

How optimizing javascript

Is there another way to rewrite this code to be more optimized, because i see that it's very repetitive in the mousemove action, also if condition
if (dept === "Parlement européen") {
var popup_topo = $("<div class='popup_topo'><strong>" + dep + "<br/>" + total + " parrainages</strong></div>");
$(this).on("mousemove", function (event) {
if ($(window).width() < 480) {
var x = event.pageX - $(this).offset().left - 45;
var y = event.pageY - $(this).offset().top + 30;
} else if ($(window).width() > 480) {
var x = event.pageX - $(this).offset().left + 30;
var y = event.pageY - $(this).offset().top + 30;
}
$(this).append(popup_topo);
popup_topo.css({
top: `${y}px`,
left: `${x}px`,
});
})
.on("mouseleave", function (event) {
popup_topo.remove();
});
}
else {
var popup_topo = $("<div class='popup_topo'><strong>" + dept + "<br/>" + total + " parrainages</strong></div>");
$(this).on("mousemove", function (event) {
if ($(window).width() < 480) {
var x = event.pageX - $(this).offset().left - 45;
var y = event.pageY - $(this).offset().top + 30;
} else if ($(window).width() > 480) {
var x = event.pageX - $(this).offset().left + 30;
var y = event.pageY - $(this).offset().top + 30;
}
$(this).append(popup_topo);
popup_topo.css({
top: `${y}px`,
left: `${x}px`,
});
})
.on("mouseleave", function (event) {
popup_topo.remove();
});
}
Here are couple of simple suggestions:
The mousemove event (at least the vanilla version, and I'm assuming jQuery's is similar) gets called quite frequently. You could set a minimum time between iterations if you want to process considerably less code.
You use the same definition for y in two places; you can define it just once, outside the conditional block.
As commenters have mentioned, your outer conditional statement should probably be removed entirely.
(Note: You probably don't need or want to include if ($(window).width() > 480) -- unless you have a reason to treat a width of exactly 480 as a special case with no format specified.)

If window width doesn't work on resize

I've created a function that has to run only if the window is wider than 769px. It works when the page loads, but not on resize...
It looks like this:
$(window).on('load resize', function () {
if ($(window).width() >= 769) {
...funcion...
}
});
EDITED:
Full code below
$(window).on('load resize', function () {
if ($(window).width() >= 769) {
var $element = $('#cont_quote');
var $follow = $element.find('.img_quote');
var followHeight = $element.find('.img_quote').outerHeight();
var height = $element.outerHeight() - 300;
var window_height = $(window).height();
$(window).scroll(function () {
var pos = $(window).scrollTop();
var top = $element.offset().top;
// Check if element is above or totally below viewport
if (top + height - followHeight < pos || top > pos + window_height) {
return;
}
var offset = parseInt($(window).scrollTop() - top);
if (offset > 0) {
$follow.css('transform', 'translateY('+ offset +'px)');
}
})
}
});
HTML:
<section id="cont_quote">
<article class="cont_q">
Lorem ipsum
<img class="img_quote" src="img">
</article>
</section>
Try something like this:
$(document).ready(function(){
$(window).resize(function(){
if ($(window).width() >= 769) {
...funcion...
}
}
}
You can change on ready or on load, depending on what you need, but the the function should trigger on window resize.
I think you can try this solution this is just javaScript
var onWindowResize = function(e) {
width = e.target.outerWidth;
//uncomment if need height = e.target.outerHeight;
if(width >= 769) {
//remove alert just added for debug
alert("if");
}
else{
//remove alert
alert("else");
}
}
window.addEventListener("resize", onWindowResize);

Custom Javascript not working in Chrome

Browsed a lot, fiddled with it a lot. Came to the conclusion others may see the mistake that I am blind to.
The code is supposed to move the sidebar according to window height, sidebar height, content height, etc.
This is the code:
$(document).ready(function() {
var windowheight = $(window).height();
var identheight = $(".ident").height();
var sidebarheight = $(".sidebar").height();
var mainheight = $(".main").height();
var pos = $(window).scrollTop();
var diff = (((sidebarheight + 20) + identheight) - windowheight);
var cur = ((sidebarheight + 20) + (pos - diff)) - 2;
var max = (mainheight + 30);
contentScroll();
$(window).resize(function(){
windowheight = $(window).height();
identheight = $(".ident").height();
sidebarheight = $(".sidebar").height();
mainheight = $(".main").height();
pos = $(window).scrollTop();
diff = (((sidebarheight + 20) + identheight) - windowheight);
cur = (sidebarheight + 20) + (pos - diff);
max = (mainheight + 30);
contentScroll();
});
$(window).scroll(function (){
pos = $(window).scrollTop();
diff = (((sidebarheight + 20) + identheight) - windowheight);
cur = (sidebarheight + 20) + (pos - diff);
max = (mainheight + 30);
contentScroll();
});
function contentScroll() {
if (sidebarheight < mainheight) {
if (diff < identheight) {
if (pos >= identheight) {
$('.sidebar').css({
'margin-top' : (pos - identheight) + 'px'
});
}
} else {
if (pos >= diff && cur <= max) {
$('.sidebar').css({
'margin-top' : (pos - diff) + 'px'
});
}
if (pos <= diff) {
$('.sidebar').css({
'margin-top' : '0px'
});
}
}
}
}
});
I'm aware of it not being perfect, it's still in the rough phase. It works perfectly fine in FireFox, but not in chrome. The function is being called (tested with alerts). It just doesn't do anything.
Probably something about chrome reading syntax different.
If anyone that see's my mistake would kindly point me to it, it's been too long for me to keep cracking my head open over this.
This is the mock-website in question: http://klok-bremen.de/fff/
Use $(window).load instead of $(document).ready because the parent elements' heights will change after the images load.

JS detect mobile & desktop width & resize AND reload

I have a function that detects the window width and based on that does jquery things that mobile would have and does jquery things for desktop. I have two functions, one that alters content resize and one on reload. What I am trying to do is combine the two into one function. The problem now is anything in the resize function just resizes. Even $("html").width();
Anyone have any ideas or solutions? Thanks.
//ON RESIZE
$(window).resize(function () {clearTimeout(this.id);this.id = setTimeout(checkTimer, 500);});
function checkTimer() {
var width = $(window).width();
//MOBILE
if (width < 640) {
mobileView();
}
//TABLET
else if (width > 640 && width <966) {
appendFix();
}
//DESKTOP
else if (width >966) {
appendFix();
}
};
//ON RELOAD
var width2 = $(window).width();
//MOBILE
if (width2 < 640) {
mobileView();
};
//TABLET
if (width2 > 640 && width2 <966) {
appendFix();
};
//DESKTOP
if (width2 > 966) {
appendFix();
};
Think I found the solution.
$(window).resize(function () {clearTimeout(this.id);this.id = setTimeout(mobileSize, 500);});
function mobileSize() {
sizes();
}
$(window).load(function() {
sizes();
});
function sizes() {
var width = $(window).width();
if (width < 640) {
}
else if (width > 640 && width < 966) {
}
else if (width > 966) {
}
}

Trigger function at specific window size

I have a div that follows the browser as it scrolls and is contained within another div.
The following function keeps my div in place and moving when the user scrolls:
$(function() {
var offset = $("#sidebar").offset();
var topPadding = 15;
$(window).scroll(function() {
if ($(window).scrollTop() > offset.top) {
$("#sidebar").stop().animate({
marginTop: $(window).scrollTop() - offset.top + topPadding
});
} else {
$("#sidebar").stop().animate({
marginTop: 0
});
};
});
});
This works pretty well, except when the browser height is less than 400px, then it gets buggy.
So I thought I'd include a simple line to get it to only run when the browser is >=400 as such:
if (window.innerHeight >= 400) {
$(function() {
var offset = $("#sidebar").offset();
var topPadding = 15;
$(window).scroll(function() {
if ($(window).scrollTop() > offset.top) {
$("#sidebar").stop().animate({
marginTop: $(window).scrollTop() - offset.top + topPadding
});
} else {
$("#sidebar").stop().animate({
marginTop: 0
});
};
});
});
}
This seems to work fine so long as the initial browser height is greater than 400px. If the browser window is resized from it's initial height, the code will still execute, which is counter to what I want.
Essentially, is there a way to dynamically track the browser size and only run this code when the height is larger than 400px and not run when less than 400px?
Thanks for any help!
Just move the check into your event handler:
$(function() {
var offset = $("#sidebar").offset();
var topPadding = 15;
$(window).scroll(function() {
if (window.innerHeight >= 400) { // <=== Moved it here
if ($(window).scrollTop() > offset.top) {
$("#sidebar").stop().animate({
marginTop: $(window).scrollTop() - offset.top + topPadding
});
} else {
$("#sidebar").stop().animate({
marginTop: 0
});
}
}
});
});
Now the check is done when you're processing the scroll event, rather than just once at the outset preventing the scroll from being hooked at all.
Separately, because you're doing this on the scroll event, which happens pretty often, I'd try to minimize the number of times you wrap or look up elements. Instead of doing it on every event, since window isn't going to change and I suspect your sidebar isn't going to change either, wrap/look them up once:
$(function() {
var offset = $("#sidebar").offset();
var topPadding = 15;
var sideBar = $("#sidebar");
var $window = $(window);
$window.scroll(function() {
if ($window.height() >= 400) { // <=== Moved it here
if ($window.scrollTop() > offset.top) {
sidebar.stop().animate({
marginTop: $window.scrollTop() - offset.top + topPadding
});
} else {
sidebar.stop().animate({
marginTop: 0
});
}
}
});
});
That also makes it reasonable to use jQuery's height function on window for cross-browser compatibility.
To track the browser width & height as it is being resized:
$(window).resize(function()
{
var viewportWidth = $(window).width();
var viewportHeight = $(window).height();
// More code here...
};
However, I think there is a better way to keep your div in place, one that does not involve Javascript. Have you tried using position:fixed?

Categories

Resources