Only apply the hover effect in jQuery when the scrollTop position is equal to zero

I want to implement a hover effect on my header, specifically when the user is at the top of the page. I am working with Shopify and believe the best approach is to add a class when hovering over it and change certain CSS properties (such as text color and height). I currently have this code that achieves a similar result when scrolling. Is there a way to modify this code so that the same effect occurs when hovering over the element, but only if scrollTop = 0?

$(document).ready(function() {
  (function() {

    $(document).on('shopify:section:load', function(event) {      
      jQuery(window).trigger('resize').trigger('scroll');

      var Heightcalculate = $('header').height(); 
      // Responsive edits
      if( $(window).width() > 980){  
        //caches a jQuery object containing the header element
        var header = $(".scrollheader");
        $(window).scroll(function() {
          var scroll = $(window).scrollTop();

          if (scroll >= 1 ) {
            header.removeClass('scrollheader').addClass("coverheader");
            $('#phantom').show();
            $('#phantom').css('height', Heightcalculate+'px');
          } else {
            header.removeClass("coverheader").addClass('scrollheader');
            $('#phantom').hide();
          }
        });        
      }
      $('.no-fouc').removeClass('no-fouc');
      $('.load-wait').addClass('hide');

    }); 

Answer №1

When hovering, check the scroll position using $.scrollTop(), and apply a class if it's at the top.

var $header = $(".scrollheader");
$header.hover(function() {
  if ($(window).scrollTop() == 0) {
    $header.addClass('hovered');
  }
},function() {
  if ($header.hasClass('hovered')) {
    $header.removeClass('hovered');
  }
});
body {
  height: 500vh;
}
.scrollheader {
  position: fixed;
  top: 0; left: 0; right: 0;
}
.hovered {
  background: #171717;
  color: #fff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<header class="scrollheader">header</header>

You can also add an event listener for scrolling, and if the user is at the top of the page, add a class to indicate that and trigger a CSS hover effect on that class.

$header = $('.scrollheader');
$(window).on('scroll',function() {
  if ($(this).scrollTop() == 0 && ! $header.hasClass('top')) {
    $header.addClass('top');
  } else if ($header.hasClass('top')) {
    $header.removeClass('top');
  }
});
body {
  height: 500vh;
}
.scrollheader {
  position: fixed;
  top: 0; left: 0; right: 0;
}
.top:hover {
  background: #171717;
  color: #fff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<header class="scrollheader top">header</header>

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

Execute JavaScript only when the form in views.py is valid

I want to utilize a javaScript code to print a variable to a Dymo printer. The javaScript code has been tested and verified to work, but I am unsure how to access and execute it from my views.py file. Perhaps I can do it directly from the template, but the ...

Enhance your DataTables experience with the latest AJAX parameters added to ajax.reload()

Utilizing DataTables to generate lists has been quite beneficial. The AJAX URL I've incorporated includes nested variables at the end. "ajax": "ajax/appointments/cancelled.php?appointment_date="+localStorage['ajaxDate'], where localStora ...

What steps should I take to resolve the Heroku TypeScript and Node.js build error I'm experiencing?

This is my first time using Heroku. I encountered multiple errors in the Heroku logs when trying to deploy my project: 2023-02-03T09:02:57.853394+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=tech- ...

I received no response when I checked my Discord messages

I'm currently working on creating a bot that will send a daily morning message at 9 o'clock with a customizable reaction. Right now, it's successfully sending the message on Discord but there seems to be an issue with the reaction part. Can ...

Angular is showing an error indicating that the property "name" is not found on an empty object

After thorough checking, I have confirmed that the property does exist with the correct key. However, it is returning an error message stating name is not a property of {}. I attempted to assign this object to an interface along with its properties but enc ...

Adjusting the initial date on the Datepicker

I am currently working on developing a calendar using bootstrap datepicker that should enable users to select a day starting 24 hours from the current date. I came across a similar query posted on Stack Overflow in the past, but the suggested solution isn& ...

React.js pagination - removing empty values from an array

I'm currently working on implementing pagination logic that automatically updates the page numbers when the last index is clicked. For example: 1 2 3 4 5 If a user clicks on the number 5, it should display: 2 3 4 5 6 and so forth... I have succe ...

The calender icon in Bootstrap4 datepicker input is unresponsive to clicks

template.html {% block content %} {% endblock %} <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin= ...

Building a Basic Calculator with Jquery, Ajax, and Servlet

I need help in developing a basic calculator using jQuery, AJAX, and servlet. The calculator will have two input boxes for numbers, a dropdown list to select the operator, and another textbox to display the result. The unique feature of this calculator is ...

jQuery TextExt - Trouble with setting the URL for Ajax autocomplete

Currently, I am utilizing the jQuery TextExt plugin for autocomplete. While using its example json url (data.json), everything functions as expected without any issues. However, when attempting to use my own custom url, similar to the one below: $('# ...

Tips on adjusting sticky behavior for responsiveness using bootstrap-4

In my project, I am utilizing angular with bootstrap. The header of the project consists of two parts and a content area. However, when the resolution is small, the header wraps. Check out the header and content on large screens View the header and conte ...

Arranging a pair of tables next to each other with consistent spacing

Hello, I am a beginner on Stack Overflow and currently in the process of learning programming. My goal is to display two tables side by side with an equal amount of spacing between them while ensuring that they do not touch the edges of the page. Below i ...

Python's Selenium Throws No Such Element Exception

Looking to automate tasks involving hyperlinks on my university's SAP Portal, I decided to use Selenium. However, encountering difficulties as many web elements are dynamically generated using JavaScript, making them invisible to the webdriver. The e ...

What is the best way to ensure that my label and input element contents are centered and displayed on separate lines?

I need assistance with aligning the contents of my form. I want each label to appear on a separate line with the input content aligned below the label. Can someone help me achieve this? I have shared an image link and my code for reference. My goal is to ...

What are some effective strategies for designing the HTML/CSS layout when utilizing Electron?

Are people usually keying in the values manually, or is there a user interface (UI) builder available that works like the drag-and-drop UI builders found in Android and iOS? Just like how many websites today utilize site builders rather than requiring ma ...

Displaying images with text below on the navigation bar, complemented by a sleek dividing line

I have a design in mind where I want to display 3 images at the top of a navbar, followed by centered text directly underneath each image. The spacing of the images seems to be even, but I'm not sure if this is just a coincidence or if I need to speci ...

Exploring the impact of JavaScript tags on website performance in accordance with W3

While researching website optimization strategies today, I came across an article discussing the benefits of moving JavaScript scripts to the bottom of the HTML page. I am curious if this approach aligns with W3C's recommendations since traditionally ...

I am having trouble getting my divs to show up side by side in one line

I am struggling to get the second div (right-column) to move next to the first div (left-column) in order to create 2 columns of links. I would prefer not to create a separate stylesheet for this small page. <div class="container" style="height: 700px; ...

AngularJS $compile function is failing to render a custom template

Hi there, I am facing an issue while trying to render a custom template using the $compile function. The error message I keep getting is: unrecognized expression: {{senddata}} I have provided my code below for reference: app.controller('MainCtrl&ap ...

Guide to retrieve the file name into a text box upon selection (Avoid displaying as c:/fake path/)

I am trying to achieve the functionality where after choosing a file in a file input, the file name is automatically displayed in a text box named file_name without needing to click or submit any button. Unfortunately, I have been unable to find the correc ...