How to simplify Javascript Multiples if? - javascript

Is there a way to simplify Javascript multiple if?
I have this code to make three different divs appear when scrolling to other divs but i'm new with javascript, I tried declaring all the variables first but i'm not sure how to write the if part
$(document).ready(function () {
var topOfOthDiv1 = $("#cuidamos").offset().top - 490;
$(window).scroll(function () {
if ($(window).scrollTop() > topOfOthDiv1) { //scrolled past the other div?
$("#cuidado").fadeIn(); //reached the desired point -- show div
} else {
$('#cuidado').fadeOut();
}
});
});
$(document).ready(function () {
var topOfOthDiv2 = $("#productos").offset().top - 490;
$(window).scroll(function () {
if ($(window).scrollTop() > topOfOthDiv2) { //scrolled past the other div?
$("#sabor").fadeIn(); //reached the desired point -- show div
} else {
$('#sabor').fadeOut();
}
});
});
$(document).ready(function () {
var topOfOthDiv3 = $("#encuentranos").offset().top - 490;
$(window).scroll(function () {
if ($(window).scrollTop() > topOfOthDiv3) { //scrolled past the other div?
$("#locat").fadeIn(); //reached the desired point -- show div
} else {
$('#locat').fadeOut();
}
});
});

Get rid of those redundant .ready() and .scroll() handlers, and put everything in one.
Then make a map of the ID of each element to be faded to its original .offset().top position.
Then in the .scroll() handler, iterate the map, and use the ID and top value of each to compare to the current scrollTop() position to decide if it should be faded or not.
The if statement itself can be eliminated as well by choosing the name of the method to be invoked dynamically using square brackets and the conditional operator.
$(function () {
var tops = {
cuidaado: $("#cuidamos").offset().top - 490,
sabor: $("#productos").offset().top - 490,
locat: $("#encuentranos").offset().top - 490
};
$(window).scroll(function () {
var top = $(window).scrollTop();
$.each(tops, function(id, this_top) {
$("#" + id)[top > this_top ? "fadeIn" : "fadeOut"]();
});
});
});

A solution should give a class to your divs and store the target with them.
How to store the target with your div ?
<div id="cuidamos" class="my-div-class" data-target-id="cuidado"></div>
<div id="productos" class="my-div-class" data-target-id="sabor"></div>
<div id="encuentranos" class="my-div-class" data-target-id="locat"></div>
As mentioned by #squint, you only need a event that do it for all your divs.
Then your code should be the following:
$(window).scroll(function () {
var windowTop = $(window).scrollTop();
var $div;
var divTop;
var $divTarget;
$('.my-div-class').each(function(div) {
$div = $(div);
divTop = $div.offset().top - 490;
$divTarget = $('#' + $div.data('target-id'));
if (windowTop > divTop) {
$divTarget.fadeIn();
} else {
$divTarget.fadeOut();
}
});
});

You can store the divs map first, then do what you want. Like this:
$(document).ready(function () {
var divsMap = {
'cuidamos': 'cuidado',
'products': 'sabor',
'encuentranos': 'locat'
};
$(window).scroll(function () {
$.each(divsMap, function(key, item){
var topOfDiv = $('#'+key).offset().top - 490;
if ($(window).scrollTop() > topOfDiv) { //scrolled past the other div?
$('#'+item).fadeIn(); //reached the desired point -- show div
} else {
$('#'+item).fadeOut();
}
});
});
});

var obj = {
"#cuidado" : $("#cuidamos").offset().top - 490,
"#sabor" : $("#productos").offset().top - 490,
"#locat" : $("#encuentranos").offset().top - 490
};
$(window).scroll(function () {
$.each(arr , function(key, val) {
if ($(window).scrollTop() > val) {
$(key).fadeIn();
}else{
$(key).fadeOut();
}
});
});

Related

How to add Position Fixed on specific Div and then remove that class on scroll

Here is the Jsfiddle i am working on
https://jsfiddle.net/farooqshad/jbdczk10/10/
Basically i want to add a class on scroll to specific div and then remove that class .
Here is my javascript
var YourDiv = $(".mainwrapper");
$(window).scroll(function() {
var scroll = $(window).scrollTop();
console.log(scroll);
if (scroll >= YourDiv.offset().top - 10) {
YourDiv.addClass('fixed');
console.log("fixed");
} else {
YourDiv.removeClass('fixed');
console.log("Not Fixed");
}
});
farooq try this solution
var YourDiv = $(".mainwrapper");
var foo=$(".footer1")
$(window).scroll(function () {
var scroll = $(window).scrollTop();
if (scroll >= YourDiv.offset().top - 10 && scroll<=foo.offset().top - 10) {
YourDiv.addClass('fixed');
}
else
{
YourDiv.removeClass('fixed');
}
});
and let me know if don't works
this is fiddle

How to add many divs in JavaScript code

I've been designing a web infographic with some animations within the page. So I added some JavaScript code in order to trigger the animations as the user reaches them on screen.
My question is how to add many div names in a JavaScript sentence?
The name of the div is "box_info_a", I just need to add some more, but have no idea how.
This is the code:
$(function()
var $window = $(window),
win_height_padded = $window.height() * 1.1,
isTouch = Modernizr.touch;
if (isTouch) {
$('.revealOnScroll').addClass('box_info_a');
}
$window.on('scroll', revealOnScroll);
function revealOnScroll() {
var scrolled = $window.scrollTop(),
win_height_padded = $window.height() * 1.1;
// Showed...
$(".revealOnScroll:not(.box_info_a)").each(function () {
var $this = $(this),
offsetTop = $this.offset().top;
if (scrolled + win_height_padded > offsetTop) {
if ($this.data('timeout')) {
window.setTimeout(function() {
$this.addClass('box_info_a ' + $this.data('animation'));
}, parseInt($this.data('timeout'), 10));
} else {
$this.addClass('box_info_a ' + $this.data('animation'));
}
}
}); // Close Showed...
// Hidden...
$(".revealOnScroll.box_info_a").each(function (index) {
var $this = $(this),
offsetTop = $this.offset().top;
if (scrolled + win_height_padded < offsetTop) {
$(this).removeClass('box_info_a lightSpeedIn')
}
});
}
revealOnScroll();
});
Just do this:
$(document).ready(function () {
$('#trigger').click(function () {
$('#target').addClass("oneClassToAdd anotherClassToAdd");
});
});
All you have to do is put two classes in the parentheses.

Match the height of 2 elements and log when higher

I have created a small script which checks the offset of 2 items and then when the item has a higher offset than the recorded screen height when scrolling.
It needs to log something 'lower'.
(function () {
$(document).ready(function () {
var heightScreen = $('.hero-screen').height();
var item1 = $('.contact-menu').offset().top;
$(window).scroll(function() {
if (item1 >= heightScreen) {
console.log('lower');
}
});
});
})();
The script works but only when I refresh the page when it is already out of the heightScreen variable.
If you want to log the height at the end of scrolling, you have do calculate it in the callbaclk.
try this.
$(document).ready(function () {
$(window).scroll(function() {
var heightScreen = $('.hero-screen').height();
var item1 = $('.contact-menu').offset().top;
if (item1 >= heightScreen) {
console.log('lower');
}
});
});

How to find Multiple div reach top?

I have a survey page divided into sections. As the user scrolls, each section's header sticks to the top of the screen until the next section is reached. I was able to do it for the first and second section but I am not sure how to do it for the third one. There must be a better way to do this.
Here is my code and a jsfiddle
Thank you
var s = $("#block2 .question-title-block");
var pos = s.position();
$(window).scroll(function() {
var windowpos = $(window).scrollTop();
if ($(this).scrollTop() > 404) {
$('#block1 .question-title-block').addClass("sticky");
if (windowpos >= pos.top) {
$('#block2 .question-title-block').addClass("sticky");
$('#block1 .question-title-block').removeClass("sticky");
}
else{
$('#block2 .question-title-block').removeClass("sticky");
}
}
else{
$('#block1 .question-title-block').removeClass("sticky");
$('#block2 .question-title-block').removeClass("sticky");
}
})
If you want it to be applied to as many elements as you want, don't use them individually, use their class. Here is what you can do:
var titleBlocks = $(".question-title-block");
$(window).scroll(function() {
var windowpos = $(window).scrollTop();
titleBlocks.each(function(){
$(this).toggleClass('sticky', $(this).parent().offset().top <= windowpos);
});
});
JS Fiddle Demo
try this (allows for any number of question blocks):
var containers = $('.question-block-container');
$(window).scroll(function () {
var windowpos = $(window).scrollTop();
containers.each(function () {
var container = $(this),
title = container.find('.question-title'),
contOffsetTop = container.offset().top,
conOffsetBottom = contOffsetTop + container.outerHeight() + 60; // 60 is margin bottom
if (windowpos >= contOffsetTop && windowpos <= conOffsetBottom) {
if (!title.hasClass("sticky")) {
title.addClass("sticky");
}
} else if (title.hasClass("sticky")) {
title.removeClass("sticky");
}
});
});
Example

(jQuery to Vanilla Javascript) fixed floating element

I am not a big fan of jQuery because it can cause a bigger load time on the page load(even if it's small), so I refrain from using jQuery as much as possible.
I am trying to convert this jQuery code to plain javascript, could someone lead me in the correct direction?
Non-working non-jquery javascript
window.onload = function()
{
var scrolledElement = document.querySelector('#comment');
var top = scrolledElement.offsetTop;
window.scroll(function()
{
var y = window.pageYOffset;
if (y >= top)
{
scrolledElement.classList.add('fixed');
} else {
scrolledElement.classList.remove('fixed');
}
});
});
and this is the actual code for jQuery.
$(document).ready(function () {
var top = $('#comment').offset().top - parseFloat($('#comment').css('marginTop').replace(/auto/, 0));
$(window).scroll(function (event) {
var y = $(this).scrollTop();
if (y >= top) {
$('#comment').addClass('fixed');
} else {
$('#comment').removeClass('fixed');
}
});
});
Here is what I have so far in jsfiddle. http://jsfiddle.net/knjQh/29/
Update your JS to attach a event on scroll
window.onload = function () {
var scrolledElement = document.querySelector('#comment');
var top = scrolledElement.offsetTop;
var listener = function () {
var y = window.pageYOffset;
if (y >= top) {
scrolledElement.classList.add('fixed');
} else {
scrolledElement.classList.remove('fixed');
}
};
window.addEventListener('scroll', listener, false);
}
Check
http://jsfiddle.net/raunakkathuria/knjQh/33/

Categories

Resources