Prevent hover animation in jQuery when the div is at the top of the page

I have a specific goal in mind: When hovering over the div labeled "hey," I want a background transition to occur. However, once the div reaches the red part of the page, I do not want that hover effect to continue on the div.

When you hover over my ".ok" div (the one labeled hey), it undergoes a color and background transition.

But here's the catch - when it hits the red section, I don't want the hover effect to persist on the ".ok" div anymore.

Issues to be aware of: I tried implementing an if-else statement without success. So, I placed it within my $(window).scroll function, but it only triggers upon actual scrolling. It doesn't work on page load.

Fiddle: https://jsfiddle.net/jzhang172/j2yrumyg/3/

$(function(){

var cheese = $('.ok').offset().top; //Define top of 'hey'

// Animates when it reaches the red part of the page

$(window).scroll(function() {
    if ($(window).scrollTop() >= cheese) {
        $('.ok').addClass('top');
    } else {
        $('.ok').removeClass('top');
    }
});

// This section is independent of the scroll event and controls hover changes on the ".ok" div.

if ($(window).scrollTop() >= cheese) {

} else if ($(window).scrollTop() <= cheese) {
    $('.ok').hover(function(){
            $(this).addClass('proj-hover');
          },function(){
            $(this).removeClass('proj-hover');
          });
}

// Animate on click

$('.ok').click(function(){
    if ($(window).scrollTop() >= cheese) {

  } else {
      $("body, html").animate({ 
              scrollTop: $('.other').offset().top 
          }, 600);

  }

});
});
*{
  box-sizing:border-box;
}
body,html{
  padding:0;
  margin:0;
}
.div{
  height:100vh;
  width:100%;
  background:#6464FF;
}
.other{
  height:1000px;
  width:100%;
  background:#FF6161;
}
.ok{
  position:absolute;
  bottom:0;
  left:50%;
  margin-left:-100px;
  width:200px;
  height:50px;
  line-height:50px;
  background:black;
  color:white;
  text-align:center;
  transition:1s;
}

.top{
  position:fixed;
  top:0;
  left:0;
  transition:.7s;
  margin-left: 0px;
  width:100%;
}
.proj-hover{
  background:white;
  color:black;
}
.blue{
  background:blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="div">
  
  <div class="ok">Hey</div>
</div>
<div class="other"></div>

Answer №1

Make sure to check if it has the class top. If it does, then remove the proj-hover class.

Check out this demo on JSFiddle

Your updated code should look something like this :

$(function(){

    var cheese= $('.ok').offset().top; //Set 'hey' element's position from top

    //
    //Animate when it reaches a certain point on the page
    //
    $(window).scroll(function() {
        if ( $(window).scrollTop() >= cheese  ) {
            $('.ok').addClass('top');
        } else{
            $('.ok').removeClass('top');
        }
    });

    //
    //Changes hover on ".ok" div based on conditions
    //

    $('.ok').hover(function(){
        if(!$(this).hasClass("top"))        
            $(this).addClass('proj-hover');
    },function(){
        $(this).removeClass('proj-hover');
    });
    
    //
    //Click event animation
    //
    $('.ok').click(function(){
        if ( $(window).scrollTop() >= cheese  ) {
    }
    else{
        $("body, html").animate({ 
            scrollTop: $('.other').offset().top 
        }, 600); 
    }
    });
});

I hope this explanation helps!

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

The jQuery Remove function that went haywire

Currently, I am delving into the world of Javascript/jQuery and attempting to construct a list of items in a table based on user input. The concept is simple - a user types text into a form, the JavaScript/jQuery captures that input and showcases it as a ...

Switch between accordion items

Currently, I have a React Js accordion in which clicking on an item opens the panel. To close it, you need to click on another item. However, I am looking to enhance this functionality by allowing the active panel to be closed after clicking on the AccButt ...

Display JSON information in a table within a dropdown menu

I have a JSON dataset where each key is represented as a column in a table. I am looking to populate each column with data from the JSON as select boxes. For example, I want to display all "country" values from the JSON as select options in the COUNTRY col ...

As I navigate through Chrome's inspect tool, I notice that certain elements are overlapping

https://i.sstatic.net/kwlIM.png After opening Chrome, I noticed that some elements are overlapping. This issue can be seen in the image provided. How can I resolve this problem? ...

Distinctive shaped container edge

I am looking to design a unique HTML box that includes a little tip at the bottom. Using HTML and CSS, I have created this specific design shown in the code below. Take a look. .item{ width: 200px; height: 130px; background: gray; background-rep ...

retrieve information from an Ajax request beyond just a string

I am seeking to retrieve multiple data sets from a grails action using jQuery's ajax call. In the past, I have only used ajax for receiving strings, but now I need to fetch lists (multiple lists). Below is my grails action: def getSpecificData() { ...

The footer fails to appear even after inspecting the element following the successful submission of my PHP email form

After implementing a PHP mail form on my website, I noticed that upon page load after filling out the email form, my footer does not appear and the tags are missing from the inspect element. The pages linked below show the issue: edit: Please note that th ...

Issues with PHP login/logout functionality found - PHP

My login/logout php code is not displaying correctly in my navigation bar. I want the navbar to show 'logout' when the user is logged in, and vice versa. On top of my header.php page: <?php session_start(); require "includes/dbh.inc.php" ...

It is not possible to utilize .next() from $this within a jQuery each function

I'm currently working on a script to check if the height of an element exceeds 55px. If it does, I want the wrapping div to collapse to 55px and display a "Read-more" link. The issue I'm facing is that the DOM navigator methods .next() and .hide ...

Start the jQuery animation only when the ajax information differs

I am using setInterval to create a timer that runs every 20 seconds. It utilizes jQuery's ajax function load() to populate the toparticles div with data from another URL on the site. After the data is successfully loaded, it applies a jQuery highlight ...

Issue encountered when attempting to upload a file from OneDrive using AJAX and JQuery

I'm encountering an issue while trying to develop a drag and drop file upload interface. It works flawlessly for local files, but when attempting to drag from OneDrive in Explorer into the designated 'drop' area, the console throws a net:ERR ...

"Centering an Image in ASP.NET HyperLink Control: A Step-by-Step

Here is the setup for my control: <asp:HyperLink CssClass="link-image" ID="Link1" runat="server"/> Code-behind in C#: Link1.ImageUrl = "imagePath"; Resulting HTML code: <a class="link-image" id="MainContent_Link1"> <img alt="" src=" ...

What is the best way to determine if an element with an ID containing the term 'date' is present using jQuery?

I am looking to implement a datetimepicker specifically for input elements with an ID containing the term 'date'. Essentially, I want something along these lines: $("where id has word 'date'").each(function(){ $(this).datetimepick ...

Learning how to interpret and implement this particular syntax within JavaScript Redux Middleware can be a valuable skill

Currently, I am diving into the world of redux middleware by referring to this informative article: http://redux.js.org/docs/advanced/Middleware.html The code snippet presented below serves as an illustration of how a logging middleware works. const log ...

Error: React/Express - The renderToString() function encountered an unexpected token '<'

As I work on implementing server-side rendering for my React/Express application, I have hit a snag due to a syntax error related to the use of the react-dom/server renderToString() method. In my approach, I am following a tutorial mentioned here - The sn ...

Attempting to modify the color of a selected Three.js object causes all objects in the scene to have their colors altered

For example, check out this JSFiddle link. The interesting part occurs during the mousedown event: var hits = raycaster.intersectObjects( [object1, object2, object3] ); if ( hits.length > 0 ) { console.log(hits[ 0 ].object) hits[ 0 ].object.m ...

Utilize JQuery addClass to implement CSS animations that run only once by setting a boolean variable to true or

I am working on a CSS animation that I want to trigger when the page is visible in the browser. To achieve this, I am using a function that determines the position (referred to as "posish"). The animation should run once when the page comes into view or wh ...

Avoiding cross-site cookie warnings when working with PostgreSQL through pgAdmin

Currently, my tech stack includes Python 3.7.4, Django 3.0.6, JavaScript, and Postgres 12.3.1. Upon loading my page, I am encountering the following warnings in the console: Cookie “PGADMIN_KEY” will be soon treated as cross-site cookie against “http ...

Passing component properties using spaces in VueJS is a simple and effective

I am encountering an issue where I want to pass component props from my view, but I am facing a challenge due to the presence of a space in the value. This causes Vue to return the following error: vendor.js:695 [Vue warn]: Error compiling template: - inva ...

Change background according to URL query

My goal is to dynamically change background images based on a URL parameter, specifically the destination code. With numerous background images available, it's crucial to display the correct one depending on the URL string. For instance, if the URL re ...