Display the element once the class enters the viewport

I am attempting to display a div only when certain elements with a specific class are visible in the viewport.

I made progress with this example: http://jsfiddle.net/blowsie/M2RzU/

$(document).ready(function(){
    $('.myclass').bind('inview', function (event, visible) {
      if (visible == true) {
        // element is now visible in the viewport
        $(this).removeClass('myclass');
          alert('found h2!')
      } else {
        // element has gone out of viewport
         $(this).addClass('myclass');
      }
    });
});

However, with this revised version: http://jsfiddle.net/deenbag/6D9x5/, the event is triggered each time any element with the class enters or exits the viewport. This means that even if one element is visible, the desired effect may be turned off if another element with the relevant class is not visible.

I also tried using this plugin but couldn't quite get it to work for my specific scenario:

Answer №1

One way to manage visible elements is to store them in an array:

var visibleElements = [];
$('.myclass').bind('inview', function (event, visible) {
    if (visible == true) {
        // element is now visible in the viewport
        if(!~visibleElements.indexOf(this)) visibleElements.push(this);
    } else {
        // element has gone out of viewport
        var index = visibleElements.indexOf(this);
        if(~index) visibleElements.splice(index, 1);
    }
    $('body').toggleClass('red', !!visibleElements.length);
});

Check out the demo here!


Alternatively, you can simplify the process with the following code:

var counter = 0;
$('.myclass').bind('inview', function (event, visible) {
    counter += visible*2-1;
    $('body').toggleClass('red', !!counter);
});

Although this method may introduce more errors.

View the simplified demo here!

Answer №2

Due to my limited reputation for commenting, I will provide a possible solution as an answer instead. Have you considered adding a counter to keep track of the elements with the myclass class that are currently "in view"? Each time the "inview" event triggers, you can update the counter. If the counter is 1, you switch on the element; if it's 0, you switch it off; if it's anything else, you do nothing. Check out this jsfiddle for reference.

$(document).ready(function(){
    numInView = 0;
    $('.myclass').bind('inview', function (event, visible) {
      if (visible) {
        numInView++;
      } else {
        numInView--;
      }
      if (numInView === 1) {
        $("h2").removeClass('myclass');
        $('body').css('color','red');
      } else if (numInView === 0) {
        $("h2").addClass('myclass');
        $('body').css('color','black');
      }
    });
});

Tip: When testing a condition, you don't always need to compare it to true unless you're specifically excluding "truthy" values. If the condition is true, it will pass without the explicit comparison to true. For example:

if (visible == true) {
    bar();
} else {
    bazz();
}

is equivalent to

if (visible) {
    bar();
} else {
    bazz()
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What strategies can be employed to prevent the need for custom classes for each individual paragraph or list item in order to maintain consistent styles within a

Bootstrap typically removes default paragraph margins and list styles for a cleaner look. However, there may be cases where you want to maintain the default styles for paragraphs and lists within a section of user-generated content on a Bootstrap 5-styled ...

Ways to efficiently implement configuration settings in a functional approach

I've delved into the world of functional programming and I'm working on developing a package that needs to be configurable. My goal is to set up this configuration only once to maintain purity in my functions without relying on global state. Curr ...

CSS <ul> <li> spacing issue in Internet Explorer 7

My CSS <ul> <li> nested menu is functioning perfectly in IE 8 and Firefox, but in IE7 it is creating a small gap between the elements. Here is my CSS: #nav, #nav ul { margin: 0; padding: 0; list-style-type: none; list-style-po ...

Utilize jQuery to load AngularJS libraries into your web application

Trying to incorporate AngularJS into a jQuery-built webpage has been my latest challenge. While the rest of the site was developed using jQuery, I wanted to tap into the potential of AngularJS for a specific page. That's when I decided to do this: jQ ...

Utilizing React Router Dom to Showcase Home Route from a Sub-Route

www.mywebsite.com www.mywebsite.com/ www.mywebsite.com/1 I need my website to show the same content for each of the links above. Currently, it is not displaying anything for www.mywebsite.com and www.mywebsite.com/ function App() { return ( <Rout ...

The map markers are nowhere to be found on the map when using Internet Explorer

Take a look at this code I wrote... var styles = [ { "featureType": "landscape", "stylers": [ {"weight": 0.1}, {"color": "#E7EDEF"} ] }, ... { "featureType": "poi.park", "elementType": "labels", "stylers": [ ...

Autonomous boundary for list elements

I have a specific issue that can be observed in this fiddle: http://jsfiddle.net/h0qu4ffv/ where I set the margin-top of one list item to 50px, but all list items end up following this style. Is there a way to give each list item an independent margin, or ...

What is the best way to convert an ajax get request into a post request using jQuery?

I'm interested in transforming a GET request to a POST request: $.ajax({ url: '/items?ids=' + value.join(','), method: 'get', dataType: 'json' }) What changes do I need to make to turn this into a ...

Using Jquery to ensure that the Ajax call finishes before proceeding

I have created a jQuery script to transfer files from one FTP server to another. It currently moves all files at once, but I would like the files to be moved one by one without locking up the browser with "async=false". <script> var files = [ ...

Extract a specific pattern from a string using Javascript

Currently, I am attempting to extract a specific string from a tag in javascript using the following code: document.querySelector('.title h2').textContent However, when I execute this code, I am getting a result that includes unnecessary double ...

`Angular Image Upload: A Comprehensive Guide`

I'm currently facing a challenge while attempting to upload an image using Angular to a Google storage bucket. Interestingly, everything works perfectly with Postman, but I've hit a roadblock with Angular Typescript. Does anyone have any suggesti ...

What is the best way to ensure a dropdown menu stays visible while navigating through various If/Else blocks?

I am fairly new to working with PHP and MySQL, so I have been using the mysql_* functions despite knowing that they are no longer supported. However, I can't seem to find anyone else who has had a similar question to mine, which is why I am reaching o ...

Create a new list in Rails 6 that dynamically updates based on the selection made in the first list

I am in the process of developing an innovative application that will showcase two distinct lists, with the second list being generated dynamically based on the user's selection from the first list. This dynamic rendering will occur seamlessly on the ...

Press on the button that is currently in your field of view

I have a web page with multiple buttons inside div elements. I am looking to automate the process of clicking the "Buy" button that is currently visible on the screen when the user presses the B key. $(document).keydown(function(e) { if (e.keyCode == ...

How can I get an object returned from a Mongoose find method in NodeJS?

I am currently working on developing a node.js API with Mongoose, However, for a specific task, I need to retrieve the object as a variable from my find operation. This is what I have so far: exports.get_info = function(_id) { Session.findById(_id, f ...

Is there a way in Angular to activate the contenteditable feature through a controller?

I have a collection of items, and the currently selected one is displayed in more detail on another section of the screen. The detailed section allows users to modify specific parts of the chosen item using contenteditable. When a user adds a new item to ...

Smooth scrolling feature malfunctioning in mobile view

While working on my website, I noticed that the smooth-scroll feature works perfectly on desktop browsers. However, on mobile devices, when I click on a link, it does not scroll to the correct position. It always ends up much lower than expected. Any idea ...

Can I link the accordion title to a different webpage?

Is it possible to turn the title of an accordion into a button without it looking like a button? Here is an image of the accordion title and some accompanying data. I want to be able to click on the text in the title to navigate to another page. I am worki ...

How can I line up elements in different divs when the width is adjusting based on the window size?

Trying to align a search input and a result element in separate containers when the window size changes. Looking for a solution without using Javascript. One window size: https://i.sstatic.net/LiQtY.png A smaller window: https://i.sstatic.net/dgj4I.png C ...

Exploration of Non-height Divs

Repeatedly encountering the same issue - a fluid div with floated elements lacking a background due to having "no height." I've experimented with various solutions such as :after selectors, , and artificially setting a height, but none are particularl ...