"Applying a class to a div element when it becomes visible within

I am attempting to dynamically add a class to a div element when it comes into view on the webpage. I am utilizing a minified jQuery 1.11.0 script to achieve this functionality.

Below is the jQuery code I have implemented:

function isScrolledIntoView(elem) {
    var docViewTop = $(window).scrollTop();
    var docViewBottom = docViewTop + $(window).height();

    var elemTop = $(elem).offset().top;
    var elemBottom = elemTop + $(elem).height();

    return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
}

$(window).scroll(function () {
    $('.textbox').each(function () {
        if (isScrolledIntoView(this) === true) {
            $(this).addClass('visible');
        }
    });

});

Although I believe that my class is visible, for some reason, the visible class is not being added. Any insights into why this might be happening?

The CSS styles of the two classes involved are as follows:

.textbox {
    width: 70%;
    margin: 0 auto;
    opacity: 0;
    transition: all .5s;
    top: -10px;
    position: relative;
}
.textbox .visible {
    opacity: 1;
    top: 0;
}

Answer №1

it's functioning perfectly. Just make sure to define .textbox.visible in your CSS without any spaces between the classes. These are two separate classes for the same element, so they should be written consecutively. Refer to the code snippet below for clarity.

Alternatively, you can check out this jsFiddle link

(the red div represents your visible div)

function isScrolledIntoView(elem) {
    var docViewTop = $(window).scrollTop();
    var docViewBottom = docViewTop + $(window).height();

    var elemTop = $(elem).offset().top;
    var elemBottom = elemTop + $(elem).height();

    return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
}

$(window).scroll(function () {
    $('.textbox').each(function () {
        if (isScrolledIntoView(this) === true) {
            $(this).addClass('visible');
        }
    });

});
.textbox {
    width: 70%;
    margin: 0 auto;
    opacity: 0;
    transition: all .5s;
    top: 0px;
    position: relative;
background:red;
height:300px;
}
.textbox.visible {
    opacity: 1;
    top: 0;
}
.anotherdiv {
width:100%;
background:blue;
height:100vh;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="anotherdiv">

</div>
<div class="textbox">

</div>

Answer №2

The problem lies in the inequalities, they need to be written as follows:

elemTop <= docViewTop &
docViewBottom <= elemBottom

The value of elemBottom must exceed docViewBottom (since it should be closer to the top), and elemTop should be below docViewTop (to ensure that docViewTop is further away from the top, making the value greater).

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

Instead of receiving plain text in my PHP response to an AJAX call, I am getting back an array

Python if($un!="" && $psw!=""){ $query=mysqli_query($db,"SELECT * FROM users WHERE (username='$un' OR email='$un') AND password='$psw'"); $exist=mysqli_num_rows($query); if($exist==1){ session_start(); $_SESSI ...

Wordpress Issues with Displaying Arabic Text Correctly

The issue arises when displaying Arabic text in menus, both the top menu and main menu. The text appears distorted and unreadable, with characters like 2Ø®Ø§Ù†Ù‚Ø§Û showing up. However, in other areas of the page such as the body content, the ...

What is the best way to showcase my customized license plate on the following page?

I need help with incorporating my number plate builder into a website. I have utilized JQUERY and JAVASCRIPT for the styling aspect, but now I want to display the designed plate on the next page. Can someone guide me on how to achieve this using PHP, JQUER ...

Retrieve all elements from JSON using jQuery

JavaScript: function loadDoc(url) { $.ajax({ url: 'mytestjson', dataType: 'json', cache: false }).success(function (result) { console.log(result); //var txt = result.newBranches[0].newNon ...

The success function is failing to display the Ajax response

Is there a way to correctly display the ajax response of my code? I noticed that when using async=true, only the last value of yy is shown. However, I want to display it for all values from 0 to a. Interestingly, everything works fine when using async=fa ...

Stop objects from shifting while easily applying a border

I have a code that adds a red border around elements when you mouseover them and removes it when you mouseout. However, the elements jump around when the border is added because it changes their dimensions. Is there a way to stop this jumping behavior? ...

Issues with tabbed navigation functionality in jQuery

I'm encountering some difficulties with the tabbed navigation I created using CSS. Essentially, when a button is clicked, it should remove the hidden class from one div and add it to the other. However, what actually happens is that the div which sho ...

Is there a way to have the menu displayed on a single line and consistently centered?

I am working on a menu that needs to stay centered at the top of the screen, with a consistent appearance and just one line, regardless of the screen width. However, I'm encountering an issue where the menu mysteriously transitions into a two-line for ...

Creating a JSON object from form selections in order to construct an SQL query can be achieved by utilizing a jQuery AJAX request to communicate with a PHP script

I need help creating an HTML form with two list-boxes and a check-box that will filter results on a webpage. How can I set it up so that when the Submit button is clicked (.onclick(function(){})), a jQuery AJAX call is triggered to a PHP script on my loca ...

jQuery DataTables covering a CSS-anchored menu bar

My webpage has a pinned navigation menu bar at the top and some tables with interactive features using jQuery's DataTables. However, after implementing jQuery, I encountered an issue where the tables cover the menu when scrolling down, making it uncli ...

Displaying the second image twice in a jQuery image slider

When attempting to implement a slider on my website, I encountered an issue where the second image appears twice in a row before the slider starts working as expected. I'm struggling to figure out why this is happening. Here is the jQuery code I am u ...

Design a dynamic rectangular division using CSS and Bootstrap 4 that adapts to different screen sizes

I am encountering difficulties attempting to replicate a full-width rectangle div on a website, particularly with issues related to responsiveness and mobility. Here is an example of the design I am trying to recreate. And here's what I've acco ...

Can one look through a div to the one beneath it by moving the cursor?

Hey there! I have a unique question for you. I've been trying to achieve a specific effect where two divs are stacked on top of each other, and the content of the lower div is only revealed in a certain area around the cursor. Is it possible to make o ...

Firing a unique jQuery event without triggering bubbling

I am looking for a way to trigger a unique jQuery event on an object that does not bubble. While I know that I can use return false or stopPropagation to prevent bubbling, I am wondering if there is a way to trigger a custom event and specify that it shoul ...

Having Trouble with Finding Visible Divs?

Below is the code snippet I am working with: var len = $(".per:visible").length; $("#add-person").click(function(){ if ($(".persons div:visible").next().is(':hidden')){ $(".persons div:visible").next().slideDown('slow' , ...

Using Kendo UI Mobile, take advantage of a button to trigger the click action of another

Consider the following situation: HTML <a id="mButton" data-role="button" data-click="clickFn">myButton</a> <asp:ImageButton runat="server" ID="aspButton" style="display: none"></asp:ImageButton> SCRIPT function clickFn(e) { ...

What causes the burger dropdown to be concealed by additional content?

While viewing my menu on an iPhone SE in responsive mode, I noticed that all of my burger menu items are hidden except for the one that fits perfectly in the space between my header and main content. https://i.sstatic.net/7K9FD.png I am using Mantine wit ...

Error: Google Chrome encountered an unexpected token } that caused a syntax error

I encountered an error that reads: Uncaught SyntaxError: Unexpected token } This error only appears in Chrome, while other browsers like Mozilla and IE do not show it. Here is my script causing the issue: <script type="text/javascript" language="jav ...

Navigate to specific location within a hidden overflow

<ul id="the-list" style="overflow:hidden;height:100px;> <li><a id="link1" href="#">Link 1</a></li> <li><a id="link2" href="#">Link 2</a></li> <li><a id="link3" href="#">Link 3< ...

Adding a new element with Jquery when a dropdown option is selected

What is causing this issue to not function properly? <script> $(document).ready(function(){ $('#custom_field option').click(function(){ $('#custom_field_input').append('<tr><td></td> ...