Use jQuery to apply CSS to a div only when it becomes visible on the screen

I created a single page HTML with scrolling functionality. The structure of my divs - home and home2 - is as shown below. Both have a height of 100%. I am looking to add CSS to the second div (home2) using jQuery only when it becomes visible to the user in the browser. Can someone provide guidance on how to achieve this?

<div class="col-md-12 home" id="home">
    <div class="col-md-6 col-md-offset-3 menu2">
        <h1 class="home2head">Heading 1</h1>
        <p>Some content will go here. Something about the hotel and its specialties.</p>
        <p>Some content will go here. Something about the hotel and its specialties.</p>
        <p>Some content will go here. Something about the hotel and its specialties.</p>
        <p>Some content will go here. Something about the hotel and its specialties.</p>
        <p>Some content will go here. Something about the hotel and its specialties.</p>
        <p>Some content will go here. Something about the hotel and its specialties.</p>
        <p>Some content will go here. Something about the hotel and its specialties.</p>
    </div>
</div>
<div class="col-md-12 home2" id="home2">
    <div class="col-md-6 menu2" id="menu2">
        <h1 class="home2head">Heading 1</h1>
        <p>Some content will go here. Something about the hotel and its specialties.</p>
        <p>Some content will go here. Something about the hotel and its specialties.</p>
        <p>Some content will go here. Something about the hotel and its specialties.</p>
        <p>Some content will go here. Something about the hotel and its specialties.</p>
        <p>Some content will go here. Something about the hotel and its specialties.</p>
        <p>Some content will go here. Something about the hotel and its specialties.</p>
        <p>Some content will go here. Something about the hotel and its specialties.</p>
    </div>
</div>

I am unsure of how to properly utilize $(window).scrollTop(), if that is a potential solution to my issue.

Answer №1

It might be more effective to use mousein and mouseleave events instead of focusin and focusout. Due to the many contents within your div, the focusin and focusout events may struggle to properly gain focus. Additionally, consider adding checks for visibility or any other specific actions you want to take.

http://jsfiddle.net/mmue2hcd/

Html

<div class="col-md-12 home" id="home">
    <div class="col-md-6 col-md-offset-3 menu2">
         <h1 class="home2head">Heading 1</h1>

        <p>Some content will go here. Something about the hotel and its specialities.</p>
    </div>
</div>
<div class="col-md-12 home2" id="home2">
    <div class="col-md-6 menu2" id="menu2">
         <h1 class="home2head">Heading 1</h1>

        <p>Some content will go here. Something about the hotel and its specialities.</p>
    </div>
</div>

Javascript/Jquery

$(document).ready(function () {

    $('#home2').mouseenter(function () {
        $(this).addClass('cssfocused');
    })

    $('#home2').mouseleave(function () {
        $(this).removeClass('cssfocused');
    });


});

CSS .cssfocused { background-color: red; }

Answer №2

Here's a way you could try implementing this:

$(document).on('scroll', function() {
    var $element = $(".elementClass");
    if (isScrolledIntoView($element))
        $element.addClass('someclass');
    else
        $element.removeClass('someclass');
})

You can then verify its position on the window by referring to this post:

For a demonstration, you can view this example: http://jsfiddle.net/dmv1cty5/3/

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

Switching Text in ReactJS from V to X: A Tutorial

I have been utilizing a Switch component from react-switch in my project. import Switch from 'react-switch'; render() { return <Switch onChange={this.onChangeStatus} onClick={this.onChangeStatus} c ...

An abundant array of options spread across numerous dropdown menus

I have been tasked by a client to do something new that I haven't done before, so I am seeking the best approach. The project involves creating a form with three dropdown menus where users can select from thousands of options. For instance: Users mu ...

Set a dynamic pixel height for a div to enhance the smoothness of slideToggle animation

I'm struggling with creating a slideToggle menu bar for my responsive layout that uses percent width instead of pixels. The issue I'm facing is that the slideToggle function appears to be jumpy due to this setup. Are there any better alternatives ...

What is the reason behind HTML5 Canvas drawing layering a fresh path onto the current path with each new point added?

Trying to explain the issue is a bit challenging, which is why I created a JS Fiddle to demonstrate what's happening: http://jsfiddle.net/dGdxS/ - (Only compatible with Webkit browsers) When you hover over the canvas, you can draw, but you may need to ...

Could you share the most effective method for implementing a live search feature using javascript or jquery?

While attempting to create a live search for a dataset containing over 10,000 rows, I specified the DOM structure that is available. Despite my efforts to check each result after a single input during the live search process, my browser keeps hanging. Is t ...

How can user input be converted into a JavaScript variable?

Looking for help with my webpage - I want users to input their name and age. After hitting submit, I'd like the first input to be stored in a variable called 'name', and the second input in a variable called 'age'. Is this doable? ...

What strategies can I use to control the DOM within the onScroll event in ReactJS?

I am currently working on implementing an arrow-up button that should be hidden when I am at the top of my page and displayed once I scroll further down. However, I am facing issues with manipulating the DOM inside my handleScroll function to achieve this. ...

The canvas's document.getElementById function is unable to find any matching element,

Hello everyone, I am currently diving into the world of javascript and trying to expand my knowledge. However, I have encountered a problem that has me stumped, and I could really use some assistance. While exploring, I came across this page: http://www.w ...

Looking to streamline a JavaScript function, while also incorporating jQuery techniques

I've got this lengthy function for uploading photos using hidden iFrames, and while it does the job well, it's quite messy. I'm looking to simplify it into a cleaner function with fewer lines of code for easier maintenance. function simplif ...

What is the best way to automatically hide the Materialize CSS mobile navbar?

Recently, I completed a website called Link. Using only Materialize CSS, Vanilla JS, and plain CSS, I developed a single-page application that effectively hides and reveals different sections based on event listeners. Everything functions smoothly except ...

Trouble with Swiper carousel loading new slides

Currently, I am working on a project using Cordova and jQuery. I have implemented the Swiper library by idangero for handling slides. The problem arises when I add new slides and try to display them. Here is the relevant jQuery code snippet: if(row.pict ...

When anchor links (href) are incorporated within a flex layout and flex-direction is set to row, they may not function as

I've designed a website with three horizontal pages, each filling the entire screen. There's a fixed menu with links that scroll to specific pages when clicked. However, users can also scroll horizontally to navigate between screens. If two page ...

Issue with non-responsive images in Bootstrap 3

Here is the bootstrap configuration that I am currently using: http://www.bootply.com/118172 I'm having an issue with the responsiveness of the image. It's not shrinking to match the height of the div on the left side. Can anyone help me trouble ...

Tips for preserving order of items in MVC framework

I have been working on organizing my carousel items and I need a sortable list view to help me choose the right format for the site. I managed to make the items sortable using this jQuery command: $(function() { $("#subsortsortable tbody.content") ...

How can I show a tooltip when hovering over a tab using uib-tab?

Currently facing an issue with HTML/Bootstrap. My tabs are displayed using the uib-tabset directive on Angular Bootstrap (UI Bootstrap). I am trying to implement a tooltip that appears when hovering over a tab that is disabled. Does anyone know how I can a ...

Using jQuery to send data from a form to a PHP script via

I'm having an issue with posting data via AJAX to PHP. The original data is pulled in using JavaScript, like this: var taskID = jQuery(this).attr('data-id'); var taskTitle = jQuery(this).attr('data-title'); var taskContent = jQuer ...

Struggles with CSS hover effects on text and buttons

Beginner in the world of HTML & CSS Struggling with the following: Hover Effect: Looking to implement a hover effect where hovering over either the staff name text or the circle button above it triggers the appearance of a square border (refer to 'A ...

I seem to be having trouble with my JavaScript code when attempting to search for items within

I want to implement an onkeyup function for a text input that searches for patient names from column 2 in my table. However, it seems to be not working properly as I don't get any results in return. Below are the snippets of what I have done so far. ...

conceal parent window element upon clicking an image within an iframe

I'm facing a challenge with hiding certain buttons in a parent window when opening a modal by clicking an image inside an iframe. Below is the code snippet that I am using: In the parent window - <iframe id="gallery" src="links/gallery.html" wid ...

Prevent further button clicks after the correct answer has been selected?

Consider a multiple-choice quiz with several questions. This is how my HTML is structured. <div class="question" id="question1"> <div class="row"> <div class="name name1 col-XS-12 col-sm-6 col-lg-3" data-answer="correct" ...