Scrolling and hovering now triggers the fixed button to toggle class seamlessly

Currently, I am attempting to modify the class of a button on my website.

The initial state of the button is wide, but as the user scrolls, it should shrink in size. When hovering over the shrunken button, it should expand back to its original width.

Although the functionality partially works, I have encountered an issue where, upon scrolling back up to the top (less than 100), the button remains small.

Any suggestions or insights would be greatly appreciated. I have tried various approaches without achieving the desired outcome.

$(window).scroll(function () {
    var scroll = $(window).scrollTop();
        $('.roundButtonBig').toggleClass("roundButton", ($(window).scrollTop() > 100)).animate(200);
});

$('.roundButtonBig').hover(function() {

    $(this).animate({"color":"#efbe5c","width":"200px","border-radius": "62px"}, 200);
    }, function() {
    $(this).animate({"color":"#e8a010","width":"60px"}, 200);
});
#screen {
  width:200px;
  height:4000px
}

.fixedButton{
    position: fixed;
    bottom: 0px;
    right: 0px; 
    padding: 20px;
}

.roundButtonBig {
    height: 60px;
    /* line-height: 80px; */
    width: 200px;
    border:none;
    background-color:#6FB583;
    font-size: 2em;
    font-weight: bold;
    border-radius: 62px;
    color: white;
    text-align: center;
    cursor:pointer;
    -webkit-transition: all .3s linear 0s;
    transition: all .3s linear 0s;
}

.roundButton{
  height: 60px;
  /* line-height: 80px; */  
  width: 60px;  
  font-size: 2em;
  font-weight: bold;
  border-radius: 50%;
  background-color: red;
  color: white;
  text-align: center;
  cursor: pointer;
  -webkit-transition: all .3s linear 0s;
  transition: all .3s linear 0s;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="screen">
  <a class="fixedButton" href="">
   <div class="roundButtonBig"></div>
  </a>
</div>

Answer №1

One issue to address is that the if scrolltop>100 check restricts the hover event to only occur when the page is scrolled at startup. It would be more effective to move the if scrolltop>10 check inside the hover function's curly braces.

Link to example

A new problem arises from this change: after scrolling down, hovering over an element, and then scrolling back up, the button fails to re-expand.

This occurs because there is a mix of animate styles and toggleClass - causing the animated style to be directly applied to the element without resetting when toggling the class. To resolve this, ensure consistent use of animate/toggle in both scenarios.

Updated code: Revised code example

$(window).scroll(function() {
  var scroll = $(window).scrollTop();
  $('.roundButtonBig').toggleClass("roundButton", ($(window).scrollTop() > 100));
  // this .animate(200) was not doing anything
});

$('.roundButtonBig').hover(
  function() {
    if ($(window).scrollTop() > 100) {
      $(this).toggleClass("roundButton");
    }
  },
  function() {
    if ($(window).scrollTop() > 100) {
      $(this).toggleClass("roundButton");
    }
  });
#screen {
  width: 200px;
  height: 4000px
}

.fixedButton {
  position: fixed;
  bottom: 0px;
  right: 0px;
  padding: 20px;
}

.roundButtonBig {
  height: 60px;
  /* line-height: 80px; */
  width: 200px;
  border: none;
  background-color: #6FB583;
  font-size: 2em;
  font-weight: bold;
  border-radius: 62px;
  color: white;
  text-align: center;
  cursor: pointer;
  -webkit-transition: all .3s linear 0s;
  transition: all .3s linear 0s;
}

.roundButton {
  height: 60px;
  /* line-height: 80px; */
  width: 60px;
  font-size: 2em;
  font-weight: bold;
  border-radius: 50%;
  background-color: red;
  color: white;
  text-align: center;
  cursor: pointer;
  -webkit-transition: all .3s linear 0s;
  transition: all .3s linear 0s;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="screen">
  <a class="fixedButton" href="">
    <div class="roundButtonBig"></div>
  </a>
</div>

Answer №2

Thank you, I keep overthinking things.

A simple hover in the css statement would have sufficed.

$(window).scroll(function () {
    var scroll = $(window).scrollTop();
        $('.roundButtonBig').toggleClass("roundButton", ($(window).scrollTop() > 100)).animate(200);
});
#screen {
  width:200px;
  height:4000px
}

.fixedButton{
    position: fixed;
    bottom: 0px;
    right: 0px; 
    padding: 20px;
}

.roundButtonBig {
    height: 60px;
    /* line-height: 80px; */
    width: 200px;
    border:none;
    background-color:#6FB583;
    font-size: 2em;
    font-weight: bold;
    border-radius: 62px;
    color: white;
    text-align: center;
    cursor:pointer;
    -webkit-transition: all .3s linear 0s;
    transition: all .3s linear 0s;
}

.roundButton{
  height: 60px;
  /* line-height: 80px; */  
  width: 60px;  
  font-size: 2em;
  font-weight: bold;
  border-radius: 50%;
  background-color: red;
  color: white;
  text-align: center;
  cursor: pointer;
  -webkit-transition: all .3s linear 0s;
  transition: all .3s linear 0s;
}

.roundButton:hover {
  width:200px;
  border-radius: 62px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="screen">
  <a class="fixedButton" href="">
   <div class="roundButtonBig"></div>
  </a>
</div>

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 is the technique for utilizing JavaScript to toggle the opening and closing of a Bootstrap 5 navbar dropdown?

My website is built using Bootstrap 5, and I am working on creating a navbar dropdown functionality. On desktop, I want the dropdown to open on hover and lead to a new page when clicked. However, on mobile, I only want the dropdown to open and close on cli ...

Modify vanilla JavaScript carousel for compatibility with Internet Explorer

I am currently in the process of creating a website that incorporates a carousel similar to the one found at the following link: https://codepen.io/queflojera/pen/RwwLbEY?editors=1010 At the moment, the carousel functions smoothly on opera, chrome, edge ...

Is There a Sparse Array Element in JavaScript?

Is there a more efficient method to check for the presence of an array element within multiple layers of a structure? For example: if (typeof arr[a][b][c] === 'undefined') { ...do something... } If [a] or [b] are missing, we cannot accurately t ...

The JSON data fails to load upon the initial page load

I am having trouble getting JSON data to display in JavaScript. Currently, the data only shows up after I refresh the page. Below is the code I am using: $(document).ready(function () { $.ajax({ url:"http://192.168.0.105/stratagic-json/pr ...

angular $stateProvider behaving unexpectedly with routing

Within my main file titled index.html, I have incorporated the following basic markup... <body ng-app="starter" ng-controller="AppCtrl"> <div ui-view></div> </body> In my separate file called app.js, I am utilizing $stateProvi ...

Steps to generate a fresh array from a given array of objects in JavaScript

Looking to transform an existing array into a new array of objects in Vue.js. Here's the initial array : import { ref } from 'vue'; const base_array = ref([ {id: 1, name: Pill, timing: [morning, noon, evening, night]}, {id: 2, name: Ta ...

How can I pass an argument to Node within a package.json script instead of the script itself?

In my project's package.json, I have a script that looks like this: "scripts": { "test": "... && mocha --full-trace test/db test/http test/storage test/utils", I am trying to pass the --async-stack-traces o ...

The z-index overlapping problem in webkit browsers is a result of Angular 7 animations

I have implemented staggered animations in my Angular 7 application to bring elements to life upon page load. However, I am facing a strange z-index problem with one of my components. Here is the animation code: @Component({ selector: 'track-page& ...

What steps can be taken to remove the search parameter responsible for the error?

Imagine having a webpage that displays search results based on the parameters in the URL, like this: https://www.someurl.com/categories/somecategory?brands=brand1,brand2,brand3 This URL will show listings for only brand1, brand2, and brand3. Additionally ...

Is it possible to make the body background image adjust its size to the browser window

Looking to change the body background using a jQuery script. The goal is to scale the background image to fit the browser window size. I've come across a script called , but it seems to affect the class img and not the background-img. Any suggestions ...

jQuery returns varying values for checked status when using click() method versus manual click

I'm facing an issue with a checkbox generating dynamic content. Whenever I try to pre-create the dynamic content on page load by using click(), the "checked" attribute is not set until after the click function finishes. Strangely, when I manually cli ...

Is there a way to utilize JSON parse for converting deeply nested keys from underscore to camelCase?

A JSON string containing an object is on my mind: const str = `[{"user_id":"561904e8-6e45-5012-a9d8-e2ff8761acf6","email_addr":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="caa0a3a6a5bc8aaca ...

JavaScript Filtering Techniques

Looking for a simpler way to remove an item from a list of 10 items without using arrow functions. My current method is shown below, but I'm seeking a more efficient solution. function getFilteredItems(myItems) { var items = ['item1& ...

JavaScript scroll event not firing

I have searched multiple questions on SO to avoid duplication, but none of the solutions worked for me. My goal is to toggle the visibility of a button based on scroll position. I tried creating a scroll event listener to trigger a function that checks th ...

Struggling to get the Hover feature on Link from Material-UI to function properly

I've been attempting to hover over Link from Material UI, but unfortunately, it's not working as expected. The CSS styles are not being applied for some unknown reason, and I can't seem to figure out why. Additionally, the Button class is al ...

Issue with Chrome related to svg getScreenCTM function

Check out the jsFiddle demo I am attempting to utilize the getScreenCTM function to retrieve the mouse position based on SVG image coordinates. It seems to work in IE and Firefox, but not in Chrome. When I define the attributes width and height in the SV ...

What is the technique for hiding the bottom tab navigator upon leaving a specific screen in React Native version 5?

In the home screen, I want only the bottom tab navigator to be visible, and then hidden until the user returns to the home screen. The example provided below is tailored for working in the App.js file, but my situation is different. const Tab = createBot ...

Pass the radio button value and accompanying text to a PHP script

I am struggling with sending both the radio button value and text to php. Currently, I can only send the radio button value. However, I want to also include the text after the radio button without altering the checkbox information. <input name="li ...

Using jQuery ajax to insert multiple data points

To process my form values, I target the form class <form class="my_form_class">: jQuery.ajax({ type:"GET", url: "/wp-admin/admin-ajax.php", data: my_form_class, context: this, success:function(data){ ...

Blunder! Error code EINVALIDTAGNAME encountered while trying to install a package

I'm encountering an issue while trying to add a new package to my React application. The error I'm receiving is: $ npm install xlsx npm ERR! code EINVALIDTAGNAME npm ERR! Invalid tag name "react-scripts start": Tags may not have any characters th ...