Ways to enhance an image by zooming in when the user reaches a designated area on the webpage

I have implemented a feature where an image zooms in to letter L when the user scrolls on the page. However, I want this zoom effect to occur only when the user reaches a specific section of the site, rather than immediately when the image loads. In my example, I would like the image to zoom in to letter L when the user scrolls to div id= "par3" and then zoom out as they continue scrolling. How can I achieve this functionality? Do I need to use event listeners for this?

const d1 = document.querySelector('.d1')
const d1InitialY = d1.offsetTop
document.addEventListener("scroll", evt => {
  const r = scrollY - d1InitialY
  const s = r < 0 ? 1 : 1 + (r / 200)
  d1.style.backgroundSize = (s * 100) + '%'
})
.d1 {
  width: 50%;
  aspect-ratio: 2/1;
  position: sticky;
  top: 0;
  background-image: url(http://picsum.photos/id/451/1500/750);
  background-size: 100%;
  background-position: 72% 43%;
}
<div>
  <div id= "par1">
<p>Paragraph1 sit amet, consectetur adipiscing elit... (Content truncated)</p>
  </div>
<div class="d1"></div>
<div id= "par2">
<p>Paragraph2 Cras volutpat velit non mi sagittis... (Content truncated)</p>
  </div>
  <div id= "par3">
<p>Paragraph3 Nulla rhoncus aliquam mauris, eu pre... (Content truncated)</p>

  </div>

  <div id= "par4">
<p>Paragraph4 Sed sed cursus leo. Nam molestie el... (Content truncated)</p>

  </div> 

Here is the code snippet I am currently using:

Answer №1

Utilize the IntersectionObserver feature to determine if #par3 is in the viewport and establish the appropriate size using this code snippet (toPar3 ? s : 1).

const d1 = document.querySelector(".d1");
const par3 = document.querySelector("#par3");
let toPar3 = false;
const par3InitialY = par3.offsetTop;
document.addEventListener("scroll", (evt) => {
  const r = scrollY - par3InitialY;
  const s = r < 0 ? 1 : 1 + r / 200;
  d1.style.backgroundSize = (toPar3 ? s : 1) * 100 + "%";
});
const observer = new IntersectionObserver((entries) => entries.forEach((entry) => (toPar3 = entry.isIntersecting)));
observer.observe(par3);
body {
  height: 200vh;
}

.d1 {
  width: 50%;
  aspect-ratio: 2/1;
  position: sticky;
  top: 0;
  background-image: url(http://picsum.photos/id/451/1500/750);
  background-size: 100%;
  background-position: 72% 43%;
}
<div>
  <div id="par1">
    <p>Paragraph1 sit amet, consectetur adipiscing elit. Maecenas tempor nunc mauris, sit amet placerat tortor lobortis dapibus. Nam lectus eros, maximus ac magna vel, congue consequat eros. Fusce id pretium diam. Cras sit amet pharetra ante. Sed quis commodo
      quam, vel facilisis ipsum. Vestibulum sodales iaculis arcu, et fringilla nisi ullamcorper sed. Donec interdum sit amet est non accumsan. Donec non augue feugiat, fermentum nunc non, convallis est. Cras vel ligula nec odio faucibus ultricies. Sed
      vulputate tortor eget pretium convallis. Cras interdum elit eget mi porta suscipit. Morbi ut velit diam. Etiam finibus eros et efficitur rutrum. Quisque viverra metus ac eleifend imperdiet. Quisque pretium ut purus vitae tempus. Duis varius risus
      congue velit faucibus, sed interdum purus consectetur.</p>
  </div>
  <div class="d1"></div>
  <div id="par2">
    <p>Paragraph2 Cras volutpat velit non mi sagittis condimentum. Cras tempor aliquet turpis sed pretium. Nunc aliquet sodales turpis quis ultrices. Duis auctor accumsan enim, quis maximus ex malesuada a. Donec a felis ut erat tempus euismod non vel neque.
      Proin lectus massa, sagittis at imperdiet nec, consequat ut neque. Sed vel placerat neque, vel varius urna. Vivamus interdum euismod urna a accumsan. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.</p>
  </div>
  <div id="par3">
    <p>Paragraph3 Nulla rhoncus aliquam mauris, eu pretium dolor auctor in. Maecenas a sollicitudin dolor, eget commodo quam. Proin et dui sed ligula vulputate egestas. Quisque eget augue vitae purus placerat pharetra. Aliquam rhoncus convallis lorem, sed
      facilisis odio blandit scelerisque. Vivamus viverra urna ac nulla interdum, eget ullamcorper leo maximus. Mauris nec feugiat enim. Nam congue, dui sit amet vestibulum posuere, leo mauris fermentum lorem, eget bibendum velit nunc quis leo.</p>


  </div>
  <div id="par4">
    <p>Paragraph4 Sed sed cursus leo. Nam molestie eleifend leo, nec fermentum risus maximus ac. Pellentesque eget placerat ipsum. Vestibulum tempor quam justo. Fusce dapibus turpis non ante faucibus suscipit. Fusce rhoncus eleifend ipsum et lacinia. Curabitur
      nec congue arcu. Mauris dignissim magna ligula. Nullam ultrices, metus sit amet ultrices porttitor, turpis ligula interdum enim, eu pellentesque purus quam ut arcu. Nullam aliquet vitae tortor vel tincidunt. Fusce maximus lacus diam, sed elementum
      ligula condimentum vel. Sed consequat orci ac nunc gravida, at accumsan magna porttitor.</p>

    <p>Mauris vulputate quam ac purus laoreet, nec ultrices eros placerat. Fusce id nisi ex. Nunc ornare tellus nisl, suscipit fermentum quam sodales sit amet. Ut ex magna, tempor nec ex sed, ornare ornare sem. Proin gravida turpis urna, vitae posuere purus
      consequat sit amet. Donec laoreet tempor massa. Praesent porta mauris vitae neque condimentum, non volutpat felis eleifend.</p>

    <p>Aliquam aliquam a est eget cursus. Ut eu tempus justo, rutrum dapibus ex. In hac habitasse platea dictumst. Nulla ornare nisi sit amet arcu semper maximus. Praesent eu augue eget mi sodales sodales. Praesent sodales neque malesuada, euismod est in,
      lobortis turpis. Nam blandit facilisis mauris. Ut ac ex rhoncus, ornare velit ac, aliquam nibh. Quisque euismod mauris quis nisl consectetur vulputate. Pellentesque mattis, tellus ut dictum dictum, urna ligula sodales magna, euismod malesuada ipsum
      quam nec elit.</p>

    <p>Duis sit amet eros non est lacinia posuere et et ex. Proin in dui ornare ex eleifend pharetra. Etiam eros urna, euismod eget porttitor et, tempor quis turpis. Nullam sollicitudin suscipit lorem, maximus pellentesque turpis dictum sed. Integer fringilla
      gravida tellus sit amet facilisis. Pellentesque vel porta justo. Proin vehicula eget tortor ut condimentum. Phasellus interdum urna a condimentum dapibus. Sed commodo elit a metus vestibulum, ac vehicula mi tincidunt. Duis ante quam, posuere eget
      purus et, mollis congue tortor. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nunc quis orci porttitor, dictum libero sit amet, feugiat ipsum.</p>

    <p>Nunc auctor lorem vitae neque sodales cursus. Sed scelerisque tempor tincidunt. Praesent eu pretium mi. Duis vitae venenatis nunc. Integer dolor sapien, vehicula ac dui id, fermentum malesuada justo. Donec ullamcorper enim sed nulla egestas condimentum.
      Etiam vitae dapibus sem, ut efficitur nulla. Donec laoreet, nunc quis aliquet blandit, erat nibh facilisis nibh, ut fermentum nisl dolor vel dui. Nunc pulvinar scelerisque urna, ut dictum purus placerat ac.</p>
  </div>
</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

Creating an HTTP request inside an Export Function in a MEANJS application

Initially, I utilized the Yo MeanJs generator to kickstart my project. As a newcomer in the world of MeanJs, things are starting to look quite complex for me. Currently, my MeanJs application is supposed to retrieve data from an HTTP request but, unfortun ...

Is there a way to turn off the auto-complete feature for JavaScript keywords in HTML within JSX in WebStorm?

While using WebStorm, I've noticed that it automatically completes JavaScript keywords as I type regular text in JSX. This behavior is starting to frustrate me because I have to constantly press ESC or click elsewhere to hide the auto-complete popup. ...

The click event is activated following the :active selector being triggered

My Angular application features a button with a slight animation - it moves down by a few pixels when clicked on: &:active { margin: 15px 0 0 0; } The button also has a (click)="myFunction()" event listener attached to it. A common issue arises w ...

Implementing script loading within the Angular scope

I'm attempting to load a custom script from the database based on client-side logic. I am having trouble figuring out how to make it function properly. Here is my controller code: 'use strict'; angular.module('youshareApp') . ...

Optimize your bootstrap carousel for mobile viewing by ensuring that the image and text are

My bootstrap carousel is displaying perfectly on desktop screens with images sized at 1200x400. However, when viewed on mobile devices, the images shrink so much that the text on them becomes unreadable. Additionally, the navigation dots at the bottom of t ...

differences between using form's get method and sending an angular $http.get request

When trying to make a GET request to a specific URL from my Angular frontend to an ExpressJS backend, I encountered some interesting behavior. In the frontend code snippet below: <li> <a ng-click="givequiz()">GiveQuiz</a> </l ...

Guide to substituting the index value with the user's specific choice

Let's simplify this. Suppose I have a list in my ng-repeat 1. A & index[0]<br> 2. B & index[1]<br> 3. C & index[2]<br> 4. D & index[3]<br><br> and there is an input field where the user can priorit ...

Error: The API_URL_KEY variable has not been declared

hardhat.config.js require("@nomicfoundation/hardhat-toolbox"); /** @type import('hardhat/config').HardhatUserConfig */ module.exports = { solidity: "0.8.18", }; /* @type import('hardhat/config').HardhatUserConfig* ...

Embedded Youtube code saved in database is not displaying on HTML form

My PHP update page allows me to modify a website's database that contains YouTube embed codes. However, when I try to edit the embed code on the update page, only "<iframe width=" displays instead of the complete original code. <html> <? ...

Implementing an object as a filter in an NG-repeat function

I've created multiple select dropdowns that are populated from a JSON file containing categories. My goal is to use the selections made by users in the dropdowns to filter a list of apps generated using ng-repeat. In my Plunker example http://plnkr. ...

Display 'Div 1' and hide 'Div 2' when clicked, then reveal 'Div 2' and hide 'Div 1' when a different button is clicked

I need help figuring out how to make two separate buttons work. One button should display 'Div 1' and hide 'Div 2', while the other button should show 'Div 2' and hide 'Div 1' when clicked. My knowledge of jquery an ...

Utilizing Parent Scope Variables in AngularJS Directives with Isolated Scopes

I'm feeling a bit lost here (edit: after clarification, my question is "Why isn't the directive recognizing the attributes passed to it?"), even though I thought I had a good grasp on it. I'm having trouble accessing the properties of the pa ...

Leveraging CSS attribute selectors within JSX using TypeScript

With pure HTML/CSS, I can achieve the following: <div color="red"> red </div> <div color="yellow"> yellow </div> div[color="red"] { color: red; } div[color="yellow"] { color: yellow; ...

Unable to connect to node.js webserver using the godaddy shared hosting URL

Upon entering www.example.com:3000 into my browser, I am encountering the following error message (where 'example' represents my domain name) This site can't be reached - www.example.com took too long to respond. I have taken the following ...

What is the best way to link JavaScript files from a Grails plugin in a separate Grails application?

I have developed a unique plugin that offers multiple Grails controllers and domain objects. Additionally, I have created several AngularJS UI components that I wish to utilize in various other projects. These specific files are located within the web-app ...

Trouble with card alignment in Bootstrap

I've been experimenting with creating a grid layout using cards and utilizing ng-repeat for generating the cards. Unfortunately, I'm running into an issue where there is no spacing between each card, as depicted in the image. https://i.stack.img ...

What causes the submit button to trigger an Ajax request?

There's something small that I need help with, and here it is. All of this is being done using jQuery. I have a function called "cont_refresh" that I use to refresh page content through an AJAX request to an external script for processing. In addit ...

Retrieve the image by its unique identifier while viewing a preview of the image before it is uploaded

Below is the script I am using to preview an image before it is uploaded. The HTML structure looks like this: <div> <img id="image" src="#"> </div> <input type="file" accept="image/gif, image/jpeg, image/png" onchange="readURL(th ...

How to update the selected autocomplete item in Vue using programming techniques?

Although I am still learning Vue, consider the following scenario: <v-autocomplete v-model="defaultUser" :hint="`User: ${defaultUser.username}`" :items="users" :item-text="item =>`${item.firstName} - $ ...

Is it possible to relocate an iframe outside the body of a post in Blogger?

For my blog posts, I have a goal of relocating the first iframe used outside of the post body and into a custom div called #myvideos. Some blog templates, such as this example, have already achieved this by moving a video out of the post body. I would like ...