toggle body background - javascript

I hope someone can help me with this, I have this javascript code that toggles my body background
function changeDivImage() {
imgPath = document.body.style.backgroundImage;
if (imgPath == "url(images/bg.jpg)" || imgPath == "") {
document.body.style.backgroundImage = "url(images/bg_2.jpg)";
} else {
document.body.style.backgroundImage = "url(images/bg.jpg)";
}
}
I activate it with this link:
change
my problem is that it works fine in IE and firefox, but in chrome, the links work twice then stop working, it basically switches to bg_2.jpg then once clicked again switches back to bg.jpg then it never works again :/
also, is there an easier way to accomplish this? css only maybe? basically i have two body background pictures and i want to be able to click on the link to toggle 1, then click again to toggle 2 instead, then back to 1, etc...
lastly, how can i make the two backgrounds fade in and out? instead of just switch between the two?

Use CSS classes!
CSS Rules
body { background-image: url(images/bg.jpg); }
body.on { background-image: url(images/bg_2.jpg); }
JavaScript:
function changeDivImage() {
$("body").toggleClass("on");
}
If you want to fade, you will end up having to fade the entire page. Use can use jQuery's fadeIn and fadeOut.

Here is your solution:
(This also supports additional images).
var m = 0, imgs = ["images/bg.jpg", "images/bg_2.jpg"];
function changeDivImage()
{
document.body.style.backgroundImage = "url(" + imgs[m] + ")";
m = (m + 1) % imgs.length;
}
Here is the working code on jsFiddle.
Here is the jQuery version on jsFiddle.
UPDATE: CROSS-FADING Version
Here is the cross-fading jQuery version on jsFiddle.
You wouldn't want the whole page (with all elements) to fade in/out. Only the bg should fade. So, this version has a div to be used as the background container. Its z-depth is arranged so that it will keep itself the bottom-most element on the page; and switch between its two children to create the cross-fade effect.
HTML:
<div id="bg">
<div id="bg-top"></div>
<div id="bg-bottom"></div>
</div>
<a id="bg-changer" href="#">change</a>
CSS:
div#bg, div#bg-top, div#bg-bottom
{
display: block;
position: fixed;
width: 100%;
/*height: 500px;*/ /* height is set by javascript on every window resize */
overflow: hidden;
}
div#bg
{
z-index: -99;
}
Javascript (jQuery):
var m = 0,
/* Array of background images. You can add more to it. */
imgs = ["images/bg.jpg", "images/bg_2.jpg"];
/* Toggles the background images with cross-fade effect. */
function changeDivImage()
{
setBgHeight();
var imgTop = imgs[m];
m = (m + 1) % imgs.length;
var imgBottom = imgs[m];
$('div#bg')
.children('#bg-top').show()
.css('background-image', 'url(' + imgTop + ')')
.fadeOut('slow')
.end()
.children('#bg-bottom').hide()
.css('background-image', 'url(' + imgBottom + ')')
.fadeIn('slow');
}
/* Sets the background div height to (fit the) window height. */
function setBgHeight()
{
var h = $(window).height();
$('div#bg').height(h).children().height(h);
}
/* DOM ready event handler. */
$(document).ready(function(event)
{
$('a#bg-changer').click(function(event) { changeDivImage(); });
changeDivImage(); //fade in the first image when the DOM is ready.
});
/* Window resize event handler. */
$(window).resize(function(event)
{
setBgHeight(); //set the background height everytime.
});
This could be improved more but it should give you an idea.

There's a cleaner way to do this. As a demo, see:
<button id="toggle" type="button">Toggle Background Color</button>
var togglebg = (function(){
var bgs = ['black','blue','red','green'];
return function(){
document.body.style.backgroundColor = bgs[0];
bgs.push(bgs.shift());
}
})();
document.getElementById('toggle').onclick = togglebg;
http://jsfiddle.net/userdude/KYDKG/
Obviously, you would replace the Color with Image, but all this does is iterate through a list that's local to the togglebg function, always using the first available. This would also need to run window.onload, preferably as a window.addEventListener/window.attachEvent on the button or elements that will trigger it to run.
Or with jQuery (as I notice the tag now):
jQuery(document).ready(function ($) {
var togglebg = (function () {
var bgs = ['black', 'blue', 'red', 'green'];
return function () {
document.body.style.backgroundColor = bgs[0];
bgs.push(bgs.shift());
}
})();
$('#toggle').on('click', togglebg);
});
http://jsfiddle.net/userdude/KYDKG/1/
And here is a DummyImage version using real images:
jQuery(document).ready(function ($) {
var togglebg = (function () {
var bgs = [
'000/ffffff&text=Black and White',
'0000ff/ffffff&text=Blue and White',
'ffff00/000&text=Yellow and Black',
'ff0000/00ff00&text=Red and Green'
],
url = "url('http://dummyimage.com/600x400/{img}')";
return function () {
document.body.style.backgroundImage = url.replace('{img}', bgs[0]);
bgs.push(bgs.shift());
}
})();
$('#toggle').on('click', togglebg);
});
http://jsfiddle.net/userdude/KYDKG/2/

Related

How to make the background image change without a button with HTML & Javascript

I'm trying to make the background image change without a button, with any click in the back but its not working.
I tried to set the default background image defined in the CSS:
background-image: url('https://img.wallpapersafari.com/desktop/1920/1080/63/70/jE2ups.jpg');
And use this JavaScript, but once the imagen change I cant go back to the old one.
function myFunction() {
document.body.style.backgroundImage = "url('https://raw.githubusercontent.com/hxst1/hxst1.github.io/main/img/p2.jpg')";
}
Also tried $document on click but im new at this and its not working either.
If you want to toggle between 2 images it can easily be done by toggling a class on the body
document.addEventListener('click', () => {
document.body.classList.toggle("bgr");
})
body {
background-image: url('https://img.wallpapersafari.com/desktop/1920/1080/63/70/jE2ups.jpg');
}
.bgr {
background-image: url('https://raw.githubusercontent.com/hxst1/hxst1.github.io/main/img/p2.jpg') !important;
}
Like Spectric commented you can toggle background image:
document.addEventListener('click',function (){
document.body.classList.toggle('body_change');
})
.body_change {
background-image: url('https://picsum.photos/300');
}
body {
background-image: url('https://picsum.photos/200');
}
<body>
</body>
try that:
document.addEventListener('click',function myBackground(){
document.body.style.backgroundImage = "url('https://raw.githubusercontent.com/hxst1/hxst1.github.io/main/img/p2.jpg')";
})
if you want to automatic change every 1,2,3 or any seconds, you can try this way.
document.addEventListener('click',function myBackground(){
changeBackground();
})
let images = [
'https://images.unsplash.com/photo-1485322551133-3a4c27a9d925?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=750&q=80',
'https://images.unsplash.com/photo-1507842217343-583bb7270b66?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=853&q=80',
'https://images.unsplash.com/photo-1600498148212-62bd3542ed63?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=750&q=80',
'https://images.unsplash.com/photo-1611091428036-e0211d8016f0?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=745&q=80',
'https://images.unsplash.com/photo-1600431521340-491eca880813?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=750&q=80'
];
let index = 0;
function changeBackground(){
document.body.style.backgroundImage = "url('"+images[index]+"')";
index = (index < images.length-1) ? (index+1) : 0;
}
// change backgroubd every 3 seconds
var interval = window.setInterval(function(){
changeBackground()
}, 3000); // 1000 = 1 second
// function to stop interval
// clearInterval(interval)
<h3>
change background
</h3>
It sounds like you are trying to toggle an image so you set the background image in css then switched it in javascript but forgot to write in the javascript the conditional statements (if/else). Basically if background is the first picture then change it to the second picture else change to first picture. Your code only says to change it to second picture.
function background(){
var body = document.body;
if(body.style.backgroundImage = "url('pic1')"){
body.style.backgroundImage = "url('pic2')";
} else {
body.style.backgroundImage = "url('pic1')";
}
}

Angular read-more button hiding (not truncating) div content

I have a div on which I have a directive that binds HTML content and compile it (sort of ng-bing-html directive, but that also compile html to allow insertion of custom directives). The HTML code looks like this :
<div ng-repeat="text in texts">
<div class="content-display"
bind-html-compile="text | filterThatOutputsHTMLCodeWithCustomDirectives | nl2br">
</div>
</div>
The problem is I need to display only a restricted portion of each of the content-display divs, and have a "read more..." button that would expand the corresponding div to its full size. But I CANNOT truncate the text bound in the div, since it's not only text, but can contain HTML tags/directives.
I found this JQuery code, that accomplish what I want visually : https://stackoverflow.com/a/7590517/2459955 (JSFiddle here : http://jsfiddle.net/rlemon/g8c8A/6/ )
The problem is that it's not Angular-compliant, and is pure JQuery. And since my div in which I bind the HTML content is inside an ng-repeat... this solution wouldn't work when the texts array gets refreshed asynchronously.
Do you see a way to have the same behavior as in the answer linked earlier, but being more "Angular compliant" and applying it automatically to each of the content-display divs added by the ng-repeat ?
Consider using a CSS approach like the one described here: https://css-tricks.com/text-fade-read-more/
CSS:
.sidebar-box {
max-height: 120px;
position: relative;
overflow: hidden;
}
.sidebar-box .read-more {
position: absolute;
bottom: 0;
left: 0;
width: 100%;
text-align: center;
margin: 0; padding: 30px 0;
/* "transparent" only works here because == rgba(0,0,0,0) */
background-image: linear-gradient(to bottom, transparent, black);
}
Rather than use jQuery for the read more "reveal", you could create an AngularJS directive for the read more button.
Directive (untested):
angular.module('myApp')
.directive('readMore', readMoreDirective);
function readMoreDirective() {
return function(scope, iElement) {
scope.$on('click', function() {
var totalHeight = 0;
var parentElement = iElement.parent();
var grandparentElement = parentElement.parent();
var parentSiblings = grandparentElement.find("p:not('.read-more')");
// measure how tall inside should be by adding together heights
// of all inside paragraphs (except read-more paragraph)
angular.forEach(parentSiblings, function(ps) {
totalHeight += ps.outerHeight();
});
grandparentElement.css({
// Set height to prevent instant jumpdown when max height is removed
height: grandparentElement.height(),
'max-height': 9999
})
.animate({
height: totalHeight
});
});
};
}
One clean way would be using a class for truncated div, and remove it to display all the text :
Angular scope :
$scope.truncated = []; // make new array containing the state of the div (truncated or not)
for(var i; i < texts.length -1; i++){
$scope.truncated.push(0); // fill it with 0 (false by default)
}
$scope.textTruncate = function(index) {
$scope.truncated[index] = !$scope.truncated[index]; // toggle this value
}
Angular view :
<div ng-repeat="text in texts" ng-class="{truncated: truncated[$index]}">
<div class="content-display"
bind-html-compile="text | filterThatOutputsHTMLCodeWithCustomDirectives | nl2br">
</div>
<button ng-click="textTruncate($index)" >Read more</button>
</div>
CSS :
.content-display {
max-height: 1000px; /* should be your max text height */
overflow: hidden;
transition: max-height .3s ease;
}
.truncated .content-display {
max-height: 100px; /* or whatever max height you need */
}
That is what comes in my mind, not sure if it's the most efficient way.
Try using <p data-dd-collapse-text="100">{{veryLongText}}</p> inside the ng-repeat
Documentation Here
Finally, I ended up using the approach given in this answer with a slight modification : https://stackoverflow.com/a/7590517/2459955
Indeed, since I have a ng-repeat adding more divs into the DOM, the $elem.each() function wouldn't trigger for these additional divs. The solution is to use a JQuery plugin called jquery.initialize.
This plugin gives an $elem.initialize() function that has exactly the same syntax as $elem.each() but initialize() will call the callback again on new items matching the provided selector automatically when they will be added to the DOM. It uses MutationObserver.
The final code looks like this. I have some JQuery code in my module.run() entry (run once at module initialization):
var slideHeight = 400;
$(".content-collapse").initialize(function() {
var $this = $(this);
var $wrap = $this.children(".content-display");
var defHeight = $wrap.height();
if (defHeight >= slideHeight) {
var $readMore = $this.find(".read-more");
var $gradientContainer = $this.find(".gradient-container");
$gradientContainer.append('<div class="gradient"></div>');
$wrap.css("height", slideHeight + "px");
$readMore.append("<a href='#'>Read more</a>");
$readMore.children("a").bind("click", function(event) {
var curHeight = $wrap.height();
if (curHeight == slideHeight) {
$wrap.animate({
height: defHeight
}, "normal");
$(this).text("Read less");
$gradientContainer.children(".gradient").fadeOut();
} else {
$wrap.animate({
height: slideHeight
}, "normal");
$(this).text("Read more");
$gradientContainer.children(".gradient").fadeIn();
}
return false;
});
}
});
And the corresponding HTML (cleaned for demonstration purpose):
<div class="content-collapse" ng-repeat="text in texts">
<div class="content-display" bind-html-compile="::text"></div>
<div class="gradient-container"></div>
<div class="read-more"></div>
</div>
This solution allows for smooth expand/collapse animation that works fine without any CSS hack, it adds the "Read more" button only on answers that exceeds the desired size limit, and works even if the texts array is modified by asynchronous requests.
I had a similar issue. I had o implement this for a data table. I found following directive and it worked smoothly as per requirements:-
Ui Framework- Angular js
In Html
<tr data-ng-repeat="proj in errors">
<td dd-text-collapse dd-text-collapse-max-length="40"
dd-text-collapse-text="{{proj.description}}"></td>
in Javascript:-
app.directive('ddTextCollapse', ['$compile', function($compile) {
return {
restrict: 'A',
scope: true,
link: function(scope, element, attrs) {
/* start collapsed */
scope.collapsed = false;
/* create the function to toggle the collapse */
scope.toggle = function() {
scope.collapsed = !scope.collapsed;
};
/* wait for changes on the text */
attrs.$observe('ddTextCollapseText', function(text) {
/* get the length from the attributes */
var maxLength = scope.$eval(attrs.ddTextCollapseMaxLength);
if (text.length > maxLength) {
/* split the text in two parts, the first always showing */
var firstPart = String(text).substring(0, maxLength);
var secondPart = String(text).substring(maxLength, text.length);
/* create some new html elements to hold the separate info */
var firstSpan = $compile('<span>' + firstPart + '</span>')(scope);
var secondSpan = $compile('<span ng-if="collapsed">' + secondPart + '</span>')(scope);
var moreIndicatorSpan = $compile('<a ng-if="!collapsed">... </a>')(scope);
var lineBreak = $compile('<br ng-if="collapsed">')(scope);
var toggleButton = $compile('<a class="collapse-text-toggle" ng-click="toggle()">{{collapsed ? "(less)" : "(more)"}}</a>')(scope);
/* remove the current contents of the element
and add the new ones we created */
element.empty();
element.append(firstSpan);
element.append(secondSpan);
element.append(moreIndicatorSpan);
element.append(lineBreak);
element.append(toggleButton);
}
else {
element.empty();
element.append(text);
}
});
}
};
}]);

How do I select an element inside of a div using Jquery

My Jquery isn't working with the way I'm selecting the <p> and <img> elements. How could I get it to work?
function projectanim(x)
{
var Para = x.getElementsByTagName("p");
var Imgs = x.getElementsByTagName("img");
if ($(x).height() != 200)
{
$(x).animate({height:'200px'});
$(Para[0]).animate({display:'inline'});
$(Imgs[0]).animate({display:'inline'});
}
else
{
$(x).animate({height:'25px'});
$(Para[0]).animate({display:'none'});
$(Imgs[0]).animate({display:'none'});
}
}
Without the HTML this is just a shot in the dark but I assume you're trying to get the paragraph and image in a specific div?
Try this:
var Para = x.find("p");
var Imgs = x.find("img");
Although depending on what you're actually passing as x will determine whether it will actually work...
function projectanim (projectId) {
$('p, img', $('div#' + projectId)) // Select p/img tags children of <div id="projectId">
.slideDown(); // show using slideDown, fadeIn() or show('slow')
}
// Example
projectanim ('protflolio_project');
The idea with jQuery is:
Use the right selectors
With the right methods
Examples
Different ways to select all img and p tags under a div which id is my_div:
// The easy way
p_and_img = $('#my_div p, #my_div img');
// Using the context parameter
p_and_img = $('p, img', $('#my_div'));
// Using the context parameter and making sure my_div is a div
p_and_img = $('p, img', $('div#my_div'));
// only the first p and img
p_and_img = $('p:eq(0), img:eq(0)', $('#my_div'));
Your question is really, really vague, but from what I can gather, this is what you're looking at achieving:
function projectanim(x) {
var self = $(x);
if (self.height() === 200) {
self.animate({ height : '25px' })
.find('p,img').fadeOut()
;
} else {
self.animate({ height : '200px' })
.find('p,img').fadeIn()
;
}
}
That being said though, barring browser compatibility and all that shizz, you really should be doing something like this using CSS more than Javascript.
Depending on your parent element (say, a <div>), you can write up CSS like the following:
div {
height : 200px;
transition : height .5s linear;
}
div.active {
height : 25px;
}
div img,
div p {
display : inline;
opacity : 100;
transition : opacity .5s linear;
}
div.active img,
div.active p {
opacity : 0;
}
and just toggle a class on/off with your Javascript:
function projectanim(x) {
$(x).toggleClass('active');
}
and everything should be automatic. Your Javascript becomes waaaaaay simpler, less coupled, more maintainable, and your styles are right where they should be (in CSS files).
"what i'm trying to do is fade the and to inline from none."
Do you just want and to fade in? Or do you want it to go from display:none to inline and fade in?
I'll show you how to do both, and you can take away parts if you just want the fade in feature.
First off set p, and img as display:none; and opacity:0, in the css like so
p, img
{
display:none;
opacity:0;
}
Secondly your js has to alter the display of both , and tags and fade in/out like so.
function projectanim(x)
{
if ($(x).height() != 200)
{
$(x).animate({height:'200px'});
document.getElementsByTagName("p").style.display = 'inline';
document.getElementsByTagName("img").style.display = 'inline';
$("p").animate({"opacity": "1"}, 1000);
$("img").animate({"opacity": "1"}, 1000);
}
else
{
$(x).animate({height:'25px'});
$("p").animate({"opacity": "0"}, 500);
$("img").animate({"opacity": "0"}, 500);
document.getElementsByTagName("p").style.display = 'none';
document.getElementsByTagName("img").style.display = 'none';
}
}

Linking background colour change [css] to background image change [javascript]

I'm using the following code to change the background image when the page is refreshed
function changeImg(imgNumber) {
var myImages = ["../img/background_tile.png", "../img/background_tile_blue.png", "../img/background_tile_green.png", "../img/background_tile_purple.png"];
var newImgNumber =Math.floor(Math.random()*myImages.length);
document.body.style.backgroundImage = 'url('+myImages[newImgNumber]+')';
}
window.onload=changeImg;
Now I'm trying to make the CSS background-color change to the color of the image so that when the page is refreshed it doesn't flash white before it loads.
Website - http://lauramccartney.co.uk
Edit - I worked it out guys! I used this
function changeImg(imgNumber) {
var myImages = ["../img/background_tile.png", "../img/background_tile_blue.png", "../img/background_tile_green.png", "../img/background_tile_purple.png"];
var myColors = ["#d1261e", "#6167e6", "#3db322", "#a12cbb"];
var newImgNumber =Math.floor(Math.random()*myImages.length);
document.body.style.backgroundImage = 'url('+myImages[newImgNumber]+')';
document.body.style.backgroundColor = myColors[newImgNumber];
}
window.onload=changeImg;
Didn't make much of a difference so I also adjusted the background in the css to an inoffensive grey.
How about this :
Instead of just storing the img path, store it like color url('url-to-image'), and use that as the background while calling it.
So your array would look like : ['color1 url(url-1)', 'color2 url(url-2)', ...] and change the javascript to use document.body.style.background = array[array-index];
/*Makes background image change when refreshed*/
function changeImg(imgNumber) {
var myImages = ["red url(../img/background_tile.png)", "blue url(../img/background_tile_blue.png)", "green url(../img/background_tile_green.png)", "orange url(../img/background_tile_purple.png)"];
var newImgNumber =Math.floor(Math.random()*myImages.length);
document.body.style.background = myImages[newImgNumber];
}
window.onload=changeImg;
It's always better to delegate styling to css classes, like this:
theme.css:
.theme-1 {
background:red url(../img/background_tile.png);
}
.theme-2 {
background:green url(../img/background_tile_green.png);
}
.theme-3 {
background:orange url(../img/background_tile_purple.png);
}
apply-theme.js:
/* Apply random class to body */
function setRandomTheme() {
var styles = ["theme-1", "theme-2", "theme-3"],
random = Math.floor(Math.random() * styles.length);
document.body.className += ' ' + styles[random];
}
And if you want to change background instantly, without flash of unstyled content, call setRandomTheme right before closing body tag:
<body>
<p>La-la-la, some content</p>
… skipped some code …
<script type="text/javascript">setRandomTheme();</script>
</body>
Or from DOMContentLoaded event:
just add this to apply-theme.js after setRandomTheme declaration:
document.addEventListener('DOMContentLoaded', function () {
setRandomTheme();
});

Multiple Image fadeIn onLoad (at the same time)

I want to fade in multiple images at the same time as the page loads. Just like this website does it: http://www.struckaxiom.com/work. I have the script to do it only on one image, but I want to have more images included.
This is the single photo script. Please help.
document.write("<style type='text/css'>#thephoto {visibility:hidden;}</style>");
function initImage() {
imageId = 'thephoto'
image = document.getElementById(imageId);
setOpacity(image, 0);
image.style.visibility = "visible";
fadeIn(imageId,ImageId2,0);
}
function fadeIn(objId, opacity) {
if (document.getElementById) {
obj = document.getElementById(objId);
if (opacity <= 100) {
setOpacity(obj, opacity);
opacity += 10;
window.setTimeout("fadeIn('"+objId+"',"+opacity+")", 100);
}
}
}
function setOpacity(obj, opacity) {
opacity = (opacity == 100)?99.999:opacity;
// IE/Win
obj.style.filter = "alpha(opacity:"+opacity+")";
// Safari<1.2, Konqueror
obj.style.KHTMLOpacity = opacity/100;
// Older Mozilla and Firefox
obj.style.MozOpacity = opacity/100;
// Safari 1.2, newer Firefox and Mozilla, CSS3
obj.style.opacity = opacity/100;
}
window.onload = function() {initImage()}
// -->
</script>
Thanks!
Simple array and loop are all you need.
First, add such array on top of the code:
var images = [ "thephoto1", "thephoto2", "thephoto3" ];
(With the ID of all desired images)
Next change the function name to initImages to reflect the fact it will initialize more than one image and finally add that loop:
function initImages() {
for (var i = 0; i < images.length; i++) {
imageId = images[i];
image = document.getElementById(imageId);
setOpacity(image, 0);
image.style.visibility = "visible";
fadeIn(imageId, 0);
}
}
That's it, no need to touch the other functions.
Live test case with cute cats: http://jsfiddle.net/yahavbr/e863X/ :-)
You could just wrap all of your images in a single container like this:
<div id="imageContainer">
<img src="img1.jpg">
<img src="img2.jpg">
<img src="img2.jpg">
</div>
Change your CSS to this:
<style type='text/css'>#imageContainer {visibility:hidden;}</style>
Change your first function to this:
function initImage() {
containerId = 'imageContainer'
container = document.getElementById(containerId);
setOpacity(container, 0);
container.style.visibility = "visible";
fadeIn(containerId,0);
}
By running the fading effect on the container you can then add as much content to the container and it will all fade in together and you never have to update your code.
The way they are doing is using jQuery (an excellent implementation). All of the images are in the same container and are selected using the jQuery class selector. Then they fade in all elements that fit within the viewable area. Their js file is not minimized so you could reverse engineer most of that functionality. The important thing to note is not that it is showing each row at a time but every element that fits in the viewing area. Their key function looks like this:
var elTop = $(el).offset().top - $(window).scrollTop();
var elHeight = $(el).height();
// if between top of footer and top of window
if (elTop + elHeight > 40 && elTop < $(window).height()) {
if ($.inArray($(el).attr("data-unique-id"), elementsInView) < 0) {
addToView(el);
}
} else {
if ($.inArray($(el).attr("data-unique-id"), elementsInView) >= 0) {
removeFromView(el);
}
}
addToView and removeFromView add and remove the element from an array, then fade is executed on the array.

Categories