Showing a property only as you scroll through the page

Seeking assistance on creating a scrolling effect for a box shadow property using HTML, CSS, and JS.

The goal is to have the shadow appear with a subtle transition while scrolling and then disappear when scrolling stops.

Here's the code I've been working with:

<head>
    <title>website</title>
    <link href="style.css" rel="stylesheet" type="text/css">
    <script type="text/javascript" src="script.js"></script>
</head>
<body>
    <div id="mySidenav" class="sidenav" onscroll="scrollShadow()"></div>

CSS

.sidenav {
height: 100%;
width: 280px;
position: fixed;
z-index: 1;
top: 0;
left: 0;
background-color: skyblue;
overflow-x: hidden;
transition: 0.5s;
padding-top: 10px;
}

JS

function scrollShadow() {
document.getElementsByClassName("sidenav").style.boxShadow = "3px 0px 10px black"; 
}

Any advice or solutions would be greatly appreciated!

Answer №1

If you're finding it difficult to manage the style attribute, especially when dealing with multiple elements, consider applying a class to body and using CSS to style the elements instead.

(function iife() {
    var body = document.body;
    var timer;
  
    window.addEventListener('scroll', function onScroll() {
        clearTimeout(timer);
        body.classList.add('scrolling');
    
        timer = setTimeout(function removeClass() {
        body.classList.remove('scrolling');
        }, 150);
    }, false);
})();
*, *:before, *:after {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

#container {
  width: 100vw;
  height: 5000px;
  background: lightgrey;
  transition: background 5s;
}

.scrolling #container {
  background: red;
}

#fix {
  position: fixed;
  top: 50px;
  left: 50px;
  height: 120px;
  width: 20px;
  background: white;
  transition: all 300ms ease 0s;
}

.scrolling #fix {
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.35);
  transform: translateY(-3px);
}
<div id="container">
  <div id="fix"></div>
</div>

Answer №2

Using jQuery, you can implement a scroll method like so:

<script>
   $(function(){
       $(window).scroll(function(){
           if($(window).scrollTop()>=40){
                /*perform action */
               addShadowEffect();
           }
       });
   });

   function addShadowEffect() {
       document.getElementsByClassName("sidenav").style.boxShadow = "3px 0px     10px black"; 
  }
</script>

Answer №3

To start off, it's important to avoid mixing CSS with JS as it doesn't belong there. The recommended approach is to assign a class to the body element and style it with CSS accordingly. Determining when the user stops scrolling isn't natively possible, so setting a timeout that reverts changes unless the user scrolls again is a workaround. Ensure the window is fully loaded before targeting elements that may not exist yet. Below is a sample code snippet that demonstrates this:

window.addEventListener('load', function(){

    var timeout = null;
    var body = document.querySelector('body');
    var scrollClass = 'scrolled';

    window.addEventListener('scroll', function(){
        clearTimeout(timeout);
        body.classList.add(scrollClass);

        timeout = setTimeout(function(){
            body.classList.remove(scrollClass);
        }, 250);
    });

});
body {
  height: 2000px;
}

.sidenav {
    height: 100%;
    width: 280px;
    position: fixed;
    z-index: 1;
    top: 0;
    left: 0;
    background-color: skyblue;
    overflow-x: hidden;
    padding-top: 10px;
    transition: box-shadow 500ms ease-in-out;
}

.scrolled .sidenav{
    box-shadow: 3px 0px 10px #000;
}
<div class="sidenav"></div>

This solution should meet your requirements.

Sincerely, Tom

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

Angular error message: Trying to access the property 'name' of an undefined object leads to a TypeError

I'm having trouble phrasing this question differently, but I am seeking assistance in comprehending how to address this issue. The error message I am encountering is as follows: TypeError: _co.create is not a function TypeError: Cannot read property ...

What is the best way to maintain the selected row during pagination in Yii?

Currently, I am facing an issue with pagination while viewing table rows. My requirement is to select different rows from various pages and then submit the form. The problem occurs when I select rows from one page, navigate to another page to make more se ...

Configuring IP Whitelisting for Firebase Cloud Functions with MongoDB Cluster

What is the process for including my Firebase Cloud Functions in the IP whitelist of my MongoDB cluster? Error Message: ...

The ExpressJS EJS issue arises when trying to access a property that is undefined

I'm new to NodeJS and seeking assistance. I am working on a website where users can promote their virtual conferences for others to see. I have set up a form with the POST method, where the data gets pushed into an array and then displayed in an EJS f ...

TradingView widget chart embedded within a web page is failing to display when hosted on X

I am having trouble displaying a TradingView widget. When I embed the widget in an HTML file and open it in a regular browser, the chart shows up fine. However, when I embed the widget in a PHP or HTML file and try to open it using xampp, the browser doesn ...

CSS code to modify background color upon mouse hover

I am currently working on creating a navigation menu. Check out the code snippet here: http://jsfiddle.net/genxcoders/ZLh3F/ /* Menu */ .menu { height: 100px; float: right; z-index: 100; } .menu ...

The HTML code does not seem to be acknowledging the CakePHP link

When using Cakephp to generate a link with Html->link, the code looks like this: echo $this->Html->link('Download',array( 'plugin'=> 'galleries', 'controller'=> 'galleries', 'a ...

A guide to incorporating a textview into a React application using the Google Maps API

Wondering how to incorporate a textview within a react-google-maps component? Successfully setting up a Google map page in React using the react-google-maps API, I've managed to insert markers and link them with polylines. import React from "react"; ...

Transmit a basic JSON object from a Node.js server to an index.html webpage

People often overlook this seemingly simple solution when I search for it on Google. My goal is to send a basic json message or file to my index.html page. Here's the Node.js code: const express = require('express'); const app = express(); ...

How can I implement a Component to show the details of a blog post when clicked in Next.js?

Can someone help me figure out how to display individual blog post details in a modal when clicked on in a blog website, where the posts are stored in a Component rather than pages? The file structure is set up like this: Component |_ Posts.js |_ PostDet ...

Executing Python code through a website using PHP - is there a way to deactivate the button once it has been clicked?

Can you assist with the following issue? <?php if(isset($_POST['MEASURE'])) { shell_exec("sudo python /var/www/html/lab/mkdir.py"); } ?> Here is the HTML part: <form method="post" > <input type="submi ...

Learning how to integrate Next.js, React.js, and Redux into an HTML page for an enhanced user

My current project is built on Asp.Net MVC, but the technology used is not crucial. I integrated react.js and redux for searching a section of my html page using a cdn link. Now, I am considering deploying the server side of the application with next.js. ...

The jQuery autocomplete feature is malfunctioning, as it is unable to display any search

Creating a country list within an ajax call involves working with an array of objects: $.ajax({ url: '//maps.googleapis.com/maps/api/geocode/json?address=' + zipCode + '&region=AT', type: 'GET', dataType: &apo ...

Determine selected option in Radio Button

FORM : <form id="approvalPenambahanUserInt" name="approvalPenambahanUserInt" action="" method="post"> <div class="form-group"> <div class="col-sm-12"> <label for= ...

Using PHP to send variables to an AJAX function via parameters

I've encountered an issue while attempting to pass 4 variables through the parameters of the ajax function. The variables I'm trying to pass include the URL, action, ID, and timeout in milliseconds. Unfortunately, the function is not accepting th ...

Implementing a feature to add selected checkboxes and remove unselected checkboxes with PHP and MySQL

I am currently working with 3 tables in my database: product, category, and product_category. I am in the process of creating a form that allows users to edit (insert/delete) categories for a specific product. My challenge lies in inserting an array of che ...

Integrating VueJs into a pre-existing .net core 5 project

I am currently working on a .net core solution that consists of 9 different projects including api, dto, data, service, etc. I now have the requirement to incorporate a project that utilizes the Vue.js framework for the frontend within this existing .net ...

Implement the Vue.js @click directive in a location outside of an HTML element

I've set up a link like this: <a href="#" @click="modal=true">Open modal</a> Here's the data setup: export default { data () { return { modal: false } } } Is there a way to trigger the cli ...

``Protect your PDF Document by Embedding it with the Option to Disable Printing, Saving, and

Currently, I am facing a challenge to enable users to view a PDF on a webpage without allowing them to download or print the document. Despite attempting different solutions like Iframe, embed, PDF security settings, and Adobe JavaScript, I have not been s ...

Navigating back to the beginning of the webpage following the completion of a form submission utilizing Master Pages and Ajax

I am having an issue with my ASP.NET 4.0 page where I want to reset it to the top after a form submission so that the validation summary can be displayed properly. The setup involves using Ajax and a master page with the following simplified code: <f ...