Code Monkey home page Code Monkey logo

jquery.inview's Introduction

Element 'inview' Event Plugin

Event that is fired as soon as an element appears in the user's viewport.

Usage

The script makes use of the new $.contains method - so it will only work with jQuery 1.8 upwards. If you need to use it with older versions of jQuery, drop a comment, and I'll post an alternative.

The event will only fire when the element comes in to view of the viewport, and out of view. It won't keep firing if the user scrolls and the element remains in view.

The variable after the event argument indicates the visible state in the viewport.

$('div').on('inview', function(event, isInView) {
  if (isInView) {
    // element is now visible in the viewport
  } else {
    // element has gone out of viewport
  }
});

To stop listening for the event - simply unbind:

$('div').off('inview');

If you would like the event only to trigger once per element while the page is loaded, you can use the .one() method instead of .on():

$('div').one('inview', ...);

Live events

Yep, inview events can also be used with .on/.delegate methods. Please note that this could slow down your app when the selector is too complex and/or matches a huge set of elements. The following code snippet only loads images when they appear in the browser's viewport.

// Assuming that all images have set the 'data-src' attribute instead of the 'src'attribute
$("body").on("inview", "img[data-src]", function() {
  var $this = $(this);
  $this.attr("src", $this.attr("data-src"));
  // Remove it from the set of matching elements in order to avoid that the handler gets re-executed
  $this.removeAttr("data-src");
});

Use cases

  • Reduce http requests and traffic on server by loading assets (images, javascript, html, ...) only when they are visible to the user
  • Endless scrolling (twitter-like)
  • Tracking (eg. to see whether a user has read an entire article)
  • ...

Browser Compatibility

The Test Suite succeeds in the following browsers that were tested:

  • Firefox 3+
  • Safari 3+
  • Chrome 7+
  • Opera 10+
  • IE 6+
  • Mobile Safari on iPad 4.2.2

jquery.inview's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

jquery.inview's Issues

Maintenance

@tiff Are you still maintaining this repository and are you plannning to do this in future?

Do you now which one is the preferred repository?

Also see zuk#18

Please updated Jquery Library

This plugin is very useful, but I can't seems to make it work using other libraries such as jquery-1.7+ some says it works in 10.1.2 something but no luck for me... TY

delay inview

I have animated SVG's within a panel and I was wondering if there was a way to delay the inview animation? I'm new at JS so go easy on me.

Triggers 'inview' event with isInView true when element is not really visible

My case was creating elements in an inactive tab (jquery ui tab, not browser's one, so just hidden div). Adding 'inview' event listeners to such elements immediately triggered 'inview' despite they were not really visible.

Adding

if (!$element.is(':visible')) {
    continue;
}

to checkInView after variables declaration worked for me, but maybe there's a better way.

Really sorry for robust issuing, but have no time now for pull request or more elaborate investigation.

support jquery 2.x

error with jquery-2.0.3

x.extend.each                             jquery-2.0.3.js:564
check_inview                              jquery.inview.min.js:1
(anonymous function)                jquery.inview.min.js:1

but work well with jquery 1.10.2

Doesn't work as expected with multiple elements

Doing the following gives me unexpected results ('inview' only fires for the final matching element):

$('.group').bind('inview', function(e, isInView, visiblePartX) {

For 'inview' to fire on all individual elements, I have to do this:

$('.group').each(function() {
    $(this).bind('inview', function(e, isInView, visiblePartX) {

Is this a bug or not?

Handling giving focus to a new position

Hi,

It works fine when scrolling, but as I have a tall document, when moving using jquery and giving focus to an element at the bottom of page, then find that even though the element has now moved into view, the inview event is not being fired.

Once you scroll a slight amount then it fires. Is there any way of getting the inview event to fire up when we give focus to a new element, or of manually triggering it after we give focus to the new element?

Thanks, Mickey

Does this work with overflow:scroll parent elements

I have .on('inview') attached to an element that is in a container that has overflow:scroll the inview event seems to fire before the element is even scrolled to in the container. Was the library intended for this use case?

Only fires once in Firefox 5.01 mac

I have this code working on all browsers I have tested on:

$(document).ready(function() {
$('.slide').each(function()
{
    $(this).bind('inview', function(e, isInView, visiblePartX, visiblePartY) {
        var elem = $(this);

        if (elem.data('inviewtimer')) {
            clearTimeout(elem.data('inviewtimer'));
            elem.removeData('inviewtimer');
        }

        if (isInView) {
            elem.data('inviewtimer', setTimeout(function() {

                if (visiblePartY == 'top') {
                    elem.data('seenTop', true);
                } else if (visiblePartY == 'bottom') {
                    elem.data('seenBottom', true);
                } else {
                    elem.data('seenTop', true);
                    elem.data('seenBottom', true);
                }

                if (elem.data('seenTop') && elem.data('seenBottom')) {
                    elem.unbind('inview');


                    elem.addClass('inview');
                }
            }, 100));
        }
    });
});

});

The html is simply 6 divs stacked on top of each other. The inview only fires once for Firefox 5.01 on the Mac. If I scroll down the page to reveal the next '.slide' nothing happens unless I resize the window or open and close Firebug.

Any ideas why? Is this a bug?

Uncaught TypeError: $ is not a function

uncaught

Guys,, need help! I am experiencing "Uncaught TypeError: $ is not a function" in WordPress. I already add a noconflict function and declare $ as var but it's still not working. I have attached a screenshot :(

(function ($) {
var body = $( 'body' );

$ ('#flashMessage').hide()

$('#previewButton').click(function() {
const title = $("#blogTitleInput").val();
const content = $("#blogContentInput").val();

$("#blogTitlePreview").text(title);
$("#blogContentPreview").html(content);

$("#flashMessage")
.slideDown(1000)
.delay(3000)
.slideUp();
});

}(jQuery));

Uncaught TypeError: $(...).easyResponsiveTabs is not a function

Downloaded this template:
https://colorlib.com/download/132/

Works fine on localhost. But get following error on my cloud server:

Uncaught TypeError: $(...).easyResponsiveTabs is not a function
    at responsiveTabs (main.js:168)
    at HTMLDocument.<anonymous> (main.js:398)
    at i (jquery.min.js:2)
    at Object.fireWith [as resolveWith] (jquery.min.js:2)
    at Function.ready (jquery.min.js:2)
    at HTMLDocument.J (jquery.min.js:2)

NOTE: This error is appearing on MAC Chrome browser. Working fine on other browsers.

Does not fire for async elements in view

I'm working on a dashboard with modules that load when inview. The script works great until I change date ranges and clear out the contents of the modules. When this happens the elements inview on change do not load because they never left the view. They do not fire until I scroll down and back again. So how do I make inview see the items as new elements again?

Here is a bin of the issue I'm having. The items start yellow and then get changed to red. On click of reset the items are changed back to yellow, but because the inview already fired off the items do not respond. Anyway to get inview to behave as if on a fresh page load?

http://jsbin.com/lameya/4/edit

Strategy for triggering inview on load

I'm looking for a strategy for triggering the inView event on load.

Here's my situation. I bring in an affixed nav if the site's header isn't in view.

$header.on('inview', function (event, isInView) {
  if ( isInView ) {
    deactivate(); // deactivate the affixed nav
  }
  else {
    activate(); // activate the affixed nav
  }
});

My issue is that this code doesn't trigger as expected on load. When a page loads scrolled I have to scroll the $header element into view then wait for it to go back out of view for the acivate() method to be called.

Initially I tried triggering the inview event on page load, but it causes activate() to be erroneously called then deactivate() to be called afterwards.

Making This Work in an iFrame

I'm working on an app which this script works great on. Unfortunately, I've had to enclose everything in an iframe so that I can keep user uploads (photos/videos) continuing across page change in the app.

When inside the iframe, inview no longer works. Would there be an easy fix to get it to watch the iframe's content viewport?

Listening on body does not work correctly.

	$( 'body' ).on( 'inview', '.arve-wrapper[data-arve-inview]', function() {
		$(this).removeAttr('data-arve-inview');
		console.log( $(this) );
		load_video( $(this) );
	});

I have this based on the img example. The console log shows that its triggered for all elements once the very first becomes visible. That should not be.

tried with $( document ) as well but same issue.

I have to do this to actually listen to elements and try to also do it for elements that are added later.

	function arve_inview() {

		$( '[data-arve-inview]' ).one( 'inview', function( event, isInView ) {
			if ( isInView ) {
				load_video( $(this) );
			}
		} );
	}

	arve_inview();

	$( document ).ajaxComplete(function() {
		arve_inview();
	});

Offset option

Would be great to add an option to provide an offset, so the "inview" event would be fired only when the element is visible from 100px for example.

I'm planning to use your plugin to animate elements when scrolling, but if the elements are only visible by a few pixels, the animation starts anyway... Not cool :)

Thanks for your work !

After refresh page with a predefined scrolltop

If I refresh a page with a predefined scrollTop value (middle of page for example) and if the binded element is already outside the viewport, the "inview" event isn't triggered.

I added an else statement in the checkInView function (l.121) where I trigger an "inview" event with a false parameter.

This works for me.

Bower issues

Hi,

Having issues with Bower that resolves back to this install.

protonet/jquery.inview=jquery.inview is not a valid repository name

Not sure if the / is valid ?

Thanks,
Tom

Delay animation?

Love this. Is there a way to delay or time the amount of time spent inview? I am using fullpage.js and our animation kicks off if a user goes past the section as it does appear on screen when scrolling by but only for a milisecond but that is long enough for the animation to start. Looking for a way to say something like "once in view for >1second, do something". Thanks.

Uncaught Type Error:

hi i am trying to upload picture but getting this error and upload button is not working

VM357:1 Uncaught TypeError: jQuery(...).uploadifyUpload is not a function
at :1:33

Confused by out of view vs inview priority

I'm using inview with fullpage.js and i'm getting into this strange issue sliding left and right:
Basically, when i'm in a specific section i wanna show the .fp-controlArrow only in the first slide, then hide them. So i assigned .hideFpNav to all slides i won't show those arrows, here is the code:
$('.hideFpNav').on('inview', function(event, isInView) { if (!isInView) { $(".fp-controlArrow").removeClass("d-none"); console.log("out of view - isInView value: ",isInView); } else { $(".fp-controlArrow").addClass("d-none"); console.log("in view - isInView value: ",isInView); } });
I attach a little gif to explain this behaviour, hope it's clear.
(In the video you'll see 3 slides:
1st: must see arrows
2nd: must hide arrows
3rd: must hide arrows )
issue

If(isinView)/else is not firing as expected

If(isinView)/else is not firing as expected.

isInView only fires when the top of the element comes into or exits the viewport. The bottom of the element does not fire isInView at all (Also related to previously submitted issue #2 with visiblePartY=='bottom').

Expected and actual results of the following example are detailed below:



<body style="padding:2000px 0;">

 <div style="min-height:2000px;background:red;"></div>

 <script type="text/javascript">

  $('div').bind('inview', function(e, isInView, visiblePartX, visiblePartY) {       
   if (isInView) {
    console.log('Element in view');
    if (visiblePartY == 'top') {
     console.log('Top of element in view.');
    } else if (visiblePartY == 'bottom') {
     console.log('Bottom of element in view.');
    } else {
     console.log('Element is entirely in view.')
    }
   } else {
    console.log('Element no longer in view.');
   }
  });
  
 </script>
 
</body>


Expected result when scrolling down the page from the top:

1) The top edge of the element comes into the bottom of the viewport, firing "isInView" (Console log "Element in view") and "visiblePartY == 'top'" (Console log "Top of element in view").
2) Scroll down continues
3) The top edge of the element goes out of the top of the viewport. Nothing fires.
4) Scroll down continues
5) The bottom edge of the element comes into the bottom of the viewport, firing "isInView" (Console log "Element in view") and "visiblePartY == 'bottom'" (Console log "Bottom of element in view").
6) Scroll down continues
7) The bottom edge of the element goes out of the top of the viewport, firing "isInView'/else (Console log "Element no longer in view").
8) Reverse scroll, now scrolling up the page
9) The bottom edge of the element comes into the top of the viewport, firing "isInView" (Console log "Element in view") and "visiblePartY == 'bottom'" (Console log "Bottom of element in view").
10) Scroll up continues
11) The bottom edge of the element goes out of the bottom of the viewport. Nothing fires.
12) Scroll up continues
13) The top edge of the element comes into the top of the viewport, firing "isInView" (Console log "Element in view") and "visiblePartY == 'top'" (Console log "Top of element in view").
14) Scroll up continues
15) The top edge of the element goes out of the bottom of the viewport, firing "isInView'/else (Console log "Element no longer in view").
16) Scroll ends

Actual result when scrolling down the page from the top:

1) The top edge of the element comes into the bottom of the viewport, firing "isInView" (Console log "Element in view") and "visiblePartY == 'top'" (Console log "Top of element in view").
2) Scroll down continues
3) The top edge of the element goes out of the top of the viewport, firing "isInView" (Console log "Element in view") and "visiblePartY == 'bottom'" (Console log "Bottom of element in view").
4) Scroll down continues
5) The bottom edge of the element comes into the bottom of the viewport. Nothing fires.
6) Scroll down continues
7) The bottom edge of the element goes out of the top of the viewport. Nothing fires.
8) Reverse scroll, now scrolling up the page
9) The bottom edge of the element comes into the top of the viewport. Nothing fires.
10) Scroll up continues
11) The bottom edge of the element goes out of the bottom of the viewport. Nothing fires.
12) Scroll up continues
13) The top edge of the element comes into the top of the viewport, firing "isInView" (Console log "Element in view") and "visiblePartY == 'top'" (Console log "Top of element in view").
14) Scroll up continues
15) The top edge of the element goes out of the bottom of the viewport, firing "isInView'/else (Console log "Element no longer in view").
16) Scroll ends

iPad Compatibility

The event doesn't fire until after scrolling has stopped on iPad, so elements don't fire as the user is scrolling down the page.

Version compatible with jQuery v1.3.2?

Hi there,

The README directed me to drop a comment if I need an alternate version that works with a jQuery version prior to 1.4. I kinda do :)

Is something like that available?

Reinitialization

Hello,

I would like to know what would be the best way to reinitialize script after an AJAX call. I have post items, each in

container with data-color attribute. I use jquery.inview to change body background color:

$('article').on('inview', function(event, isInView) {
  if (isInView) {
    var spalva = $(this).attr('data-color');
    $('body').css('background-color', spalva);
  }
});

However, after and AJAX call this script only works with posts displayed on page load. Therefore I need to reinitialize jquery.inview after the call. I would be very grateful if someone could help me what would be the best way to do it.

visiblePartY == 'bottom' fired at the wrong time

visiblePartY is fired when the top of the element moves out of the viewport, not when the bottom of the element moves into the viewport, making it impossible to detect when the bottom of an element has appeared. Produced in FF3.6, Saf5, Chrome9 (Not tested IE, Opera). Jquery1.4.2.

Example, based on the simple example from README:


<div style="min-height:2000px;border:1px red solid;"></div>
<script type="text/javascript">
$('div').bind('inview', function(event, isInView, visiblePartX, visiblePartY) {
 if (isInView) {
  // element is now visible in the viewport
  if (visiblePartY == 'top') {
   // top part of element is visible
   console.log('Can see the top.');
  } else if (visiblePartY == 'bottom') {
   // bottom part of element is visible
   console.log('Can see the bottom.');
  } else {
   // whole part of element is visible
  }
 } else {
  // element has gone out of viewport
 }
});
</script>

[enhancement] Add missing bower.json.

Hey, maintainer(s) of protonet/jquery.inview!

We at VersionEye are working hard to keep up the quality of the bower's registry.

We just finished our initial analysis of the quality of the Bower.io registry:

7530 - registered packages, 224 of them doesnt exists anymore;

We analysed 7306 existing packages and 1070 of them don't have bower.json on the master branch ( that's where a Bower client pulls a data ).

Sadly, your library protonet/jquery.inview is one of them.

Can you spare 15 minutes to help us to make Bower better?

Just add a new file bower.json and change attributes.

{
  "name": "protonet/jquery.inview",
  "version": "1.0.0",
  "main": "path/to/main.css",
  "description": "please add it",
  "license": "Eclipse",
  "ignore": [
    ".jshintrc",
    "**/*.txt"
  ],
  "dependencies": {
    "<dependency_name>": "<semantic_version>",
    "<dependency_name>": "<Local_folder>",
    "<dependency_name>": "<package>"
  },
  "devDependencies": {
    "<test-framework-name>": "<version>"
  }
}

Read more about bower.json on the official spefication and nodejs semver library has great examples of proper versioning.

NB! Please validate your bower.json with jsonlint before commiting your updates.

Thank you!

Timo,
twitter: @versioneye
email: [email protected]
VersionEye - no more legacy software!

visiblePartX and visiblePartY no longer available

Are the visiblePartX and visiblePartY arguments as used in your advanced.html example no longer available?

Said example doesn't seem to do anything and trying it with my own code returns undefined for both third and fourth arguments.

Listening for elements added to DOM

I'm loading stuff dynamically on a site, and noticed that inview doesn't trigger for stuff that's been added after the bind is initialized. Should I just trigger it again? I imagine there will be double binds then and possibly more strain on the CPU?

Баг при удаление класса элемента выходящего из зоны видимости флаг видимости не корректно возвращается

var $init = $('.onscroll-animate');
if ($init.length) {
for (var i=0, len=$init.length; i<len; i++) {
$init.bind('inview', function(event, isInView) {
var $this = $(this);
if (isInView) {
$this.addClass($this.data("animation"));
} else {
$this.removeClass($this.data("animation"));
}
console.log(isInView);
});
}
}

isInView - возвращает постоянно true или false для элементов которые в css определены за границами видимости.

Bind working in browser but not is mobile devices.

I have a chat box where it scrolls to the bottom and loads all the chats,(which includes images).
It's working fine in browser, but images not loading in the mobile devices

var wrap = $("html,body #chatdiv");
wrap.on("load scroll", function(e) {
$('.chats_attachments').bind('inview', function (event, visible) {
var status = $(this).attr("data-loaded");

			if(status == 0)
			{
				var src = $(this).attr("data-src");
				$(this).attr("src",base_url+"/assets/img/chats/"+src);
				
				$(this).load(function() {
				  $(this).attr("data-loaded",1);
				});
			}
	 });
});

Why this is happening, Check the screenshots
desktop
This is the mobile view... I have a fake image which willl be converted to the actual image using data-src attribute

mobile

Use offsetWidth/offsetHeight instead of jQuery width()/height() to improve performance

Another bottleneck of performance is the calculation of the elements width and height via jQuery methods width() and height().

How about using offsetWidth and offsetHeight for getting the elements width and height?

The difference between them is that offsetWidth/offsetHeight includes padding, border and margin.
But the performance would increase drastically.

jQueryApi doc of width: http://api.jquery.com/width/
offset doc: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement.offsetWidth

Comparison of performance:
http://jsperf.com/offsetwidth-vs-jquery-width
http://jsperf.com/jquery-css-vs-width-vs-native-width/4

Wrong behaviour after page resize

Hello.
This plugin works great. But I noticed one issue: after I resize page, event handler get wrong params. Element that is now in viewport gets isInView == false, and element that is under the viewport gets isInView == true. That's why "visible" class is removed and element in viewport just disappears.
After page reload with this page size it works ok.

I use this code:

$('div.section').on('inview', function(event, isInView, visiblePartX, visiblePartY) {
        var $this = $(this);

        if (isInView) {
            $this.addClass("visible");
        }
        else{
            $this.removeClass("visible");
        }
    });

Webkit based browsers works fine, problem in Opera 12, latest Firefox and IE.
Also I tried disable media-queries with no luck.

Or I have to rebind event handlers after each resize?

Screenshot - http://s7.hostingkartinok.com/uploads/images/2014/12/2e41d91a3098988412bd5634796e8a33.png

InView in reference to another container instead of viewport

Hi there!

I'm already using this plugin to load data automatically when a user reaches the bottom of the contents and it works great.

Now I'm trying to display a list on a fixed height div. The event 'inview' is firing as soon as I attach the event even though the element is not in view yet. My guess is that this is happening because the plugin always considers the whole viewport. Is there any way to tell the plugin that my viewport in this case is certain div and not the entire window?

Regards,
t3ch

Just not working when add visibility top or more classes

Hello,

I want to trigger counter to start when class .count is in view.
I have that class on top and on bottom of page, so using if(isInView) it get triggered only when I scroll down to bottom class and then top class is also triggered.

Is there solution beside making .count1 and .count2 ?

Thanks

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.