Execute A Function If An Element Is Visible/Invisible - Visible.js

File Size: 4.69 KB
Views Total: 3410
Last Update:
Publish Date:
Official Website: Go to website
License: MIT
   
Execute A Function If An Element Is Visible/Invisible - Visible.js

The Visible.js jQuery element visible detection plugin which utilizes MutationObserver to execute a callback function when an element gets visible or invisible.

How to use it:

1. Import the main JavaScript file Visible.js after the latest version of jQuery library.

<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" 
        integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" 
        crossorigin="anonymous">
</script>
<script src="Visible.js"></script>

2. Bind the becameVisible and becameUnvisible events to a specific element as follows:

$('#el').on('becameVisible', function() {
  // do something
});

$('#el').on('becameUnvisible', function() {
  // do something
});

3. A full example.

<button onclick="toggle();">Toggle</button>

<button onclick="hide();">Hide</button>

<button onclick="show();">Show</button>

Status: <span id="status">[Empty]</span>

<div id="container">
  <h3 id="myContent">This text will be hide or shown</h3>
</div>
function toggle() {
  $('#container').toggle();
}

function hide() {
  $('#container').hide();
}

function show() {
  $('#container').show();
}

$(document).ready(function() {
  $('#myContent').on('becameVisible', function() {
      $('#status').text('Visible');
  });

  $('#myContent').on('becameUnvisible', function() {
      $('#status').text('Invisible');
  });
});

This awesome jQuery plugin is developed by dzavodnikov. For more Advanced Usages, please check the demo page or visit the official website.