What is the best method for resizing individual SVG elements using jQuery or JavaScript?

A unique effect on my webpage involves an SVG comprised of scattered squares that enlarge when the user scrolls past a specific point. However, there is a problem with the scaling process which results in a horizontal scroll bar appearing. This occurs because the entire SVG block scales up, rather than each individual square.

Is there a way to target each individual rect element to enlarge smoothly with an easing motion, giving the illusion of growth without stretching the page layout? Additionally, once the user continues to scroll, can the squares revert back to their original size?

Explore the updated version of the webpage on JSFiddle

HTML:

<div class="move-wrapper">

<svg class="enlarge" version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
   viewBox="82 -117 1363 770" style="enable-background:new 82 -117 1363 770;" xml:space="preserve">
<style type="text/css">
  .st0{fill:none;stroke:#A7A9AC;stroke-width:5;stroke-miterlimit:10;}
</style>
<rect x="153" y="-34" class="st0" width="22.1" height="22.1"/>
<rect x="335.5" y="55.5" class="st0" width="22.1" height="22.1"/>
<rect x="529.5" y="343.1" class="st0" width="22.1" height="22.1"/>
<rect x="153.6" y="464.4" class="st0" width="22.1" height="22.1"/>
<rect x="976.5" y="166.4" class="st0" width="22.1" height="22.1"/>
<rect x="1288.3" y="-12.1" class="st0" width="22.1" height="22.1"/>
<rect x="941.9" y="575.3" class="st0" width="22.1" height="22.1"/>
<rect x="1355.9" y="434.9" class="st0" width="22.1" height="22.1"/>
</svg>

</div>

<div class="spacer"></div>
<div class="spacer"></div>

CSS:

.move-wrapper {
  width:100%;
  position:absolute;
}

.spacer {
  height:500px;
}

JS:

$(function() {

  $(window).on('scroll', function() {
    scrollPosition = $(this).scrollTop();
    if (scrollPosition >= 20) {
      $(".enlarge").css({"-moz-transform": "scale(1.5,1.5)", "webkit-transform": "scale(1.5,1.5)"});
    $(this).off('scroll');
    }

    if (scrollPosition >= 40) {
      $(".enlarge").css({"-moz-transform": "scale(1,1)", "webkit-transform": "scale(1,1)"});
        $(this).off('scroll');
    }
  });

});

Answer №1

Check out this potential solution: http://jsfiddle.net/_jered/0yy0nLam/

  • Transfer styles to CSS whenever feasible.
  • Encase each rect in an svg for precise positioning regardless of scale.
  • Adjust each rect by half its width to center the transform.

Keep in mind that the usage of x and y attributes in svg elements may not be universally supported. It seems to function in Chrome, but consistency across browsers may vary. A more dependable approach, though more labor-intensive, would be to use a CSS transform instead.

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

Create a draggable and droppable file upload container that functions similarly to an input with the type "file"

My goal is to create a native HTML5 multiple file upload feature using drag and drop functionality. Despite following tutorials like and http://www.html5rocks.com/en/tutorials/file/dndfiles/, I have not yet found the exact solution I am looking for. Ess ...

What causes the issue of text being blocked by a webgl shader background even when the text div is layered above and given a higher z-index?

I am looking to enhance a WordPress theme by dynamically generating glsl shaders using the three.js library for JavaScript, and then incorporating those shaders into various HTML elements, such as using them as backgrounds for text content. My current cha ...

Can a single Axios request in JavaScript include both a Body and Files?

Is it possible to send both a file and body with the POST request below in axios? axios.post("http://localhost:3000/upload", formData) How can I include something in the body:{} section as well? Server response: files: { myFile: { nam ...

Choosing a CSS selector for a class that does not have a specific ID

Looking for a way to select all elements with the class .tab-pane except for those with the id #home. I attempted using .tab-pane:not#home{...}, but it proved unsuccessful. Any ideas on how to achieve this? Sample HTML <div id="home" class="tab-pan ...

Utilizing Vue.js transitions to display content with a one-time transition limit

I have followed the Vue.js documentation given below to implement the show transition, but I'm struggling with stopping the hide effect on the second click. Is there a way to achieve this? https://v2.vuejs.org/v2/guide/transitions.html#a Can I conti ...

Printing without sufficient paper will result in an incomplete printout

https://i.stack.imgur.com/jNlRr.jpg I am facing an issue with printing the last column "Potensi". The text in this column is not fully printed. How can I resolve this problem? I am using PHP. Thank you ...

Upon including the enctype attribute as "multipart/form-data" in my form and submitting it, the form redirects to a different page

My website has two main pages: The first page is admin.php <?php session_start(); if (!isset($_GET['page'])){ $_GET['page'] = 'home'; }//end if include_once(dirname(__FILE__)."/function.php"); ?> <?ph ...

Guidelines for choosing input using jQuery

I am looking to retrieve the value of an input using jQuery. Specifically, I need to extract the value of a hidden input with name="picture" when the user clicks on the حذف این بخش button by triggering the function deleteDefaultSection( ...

Using async/await to handle the callback function

Here is a function that saves a user in the database: exports.saveUser = ({ first_name, last_name, email, password }) => { const query = "insert into users (first_name, last_name, email, password_hash) values ($1, $2, $3, $4) RETURNING *"; ...

Navigate through JSON data to uncover the tree structure path

In my project, I am working on creating a treeview user interface using the JSON provided below. I have included properties such as node-id and parentId to keep track of the current expanded structure. Next, I am considering adding a breadcrumb UI compone ...

Can the line "as is" be included in HTML code?

Can I incorporate the following JavaScript and JSON expressions directly into HTML code? CONTRATE > 50 && SALINC <= 50 || RETAGE >= 50 { "CONTRATE": 0, "SALINC": 0, "MARSTATUS": "single", "SPOUSEDOB": "1970-01-01" } I want to be able to ...

What is the best way to handle waiting for an API call in JavaScript export?

In my Vue app, I've set up my firestore app initialization code as shown below: if (firebase.apps.length) { firebase.app() } else { firebase.initializeApp(config) } export const Firestore = firebase.firestore() export const Auth = firebase.auth() ...

Issue with XAMPP: Editing PHP file does not update displayed content in browser

Initially, my code looked like this: <!DOCTYPE html> <html> <head> <link type="text/css" rel="stylesheet" href="css/style.css" /> <title>PHP file</title> </head> <body> <h1> <?ph ...

Preserving checkbox states upon click event

<form name="form_name" action="/" method="get"> <% if params["title"].present?%> <% if params["title"] == "1" %> <input type="checkbox" name="title" onclick="this.form.submit();" value="1" checked> ...

Using the md-date-picker along with the md-menu component

Whenever I try to click on the md-date-picker inside md-menu, it unexpectedly closes. You can view the issue on this CodePen link. This seems to be a bug related to ng-material as discussed in this GitHub issue. Any suggestions for a workaround? Here is t ...

Tips for adjusting the placement of enlarged images within colorbox

I recently discovered colorbox and decided to use it as my lightbox solution. However, I encountered a challenge with positioning the background (#cboxOverlay). I wanted to move it 120px to the left so that some content from the original page would still ...

Error: Angular is encountering an issue with accessing the property 'push' as it is currently undefined

I have successfully created a news ticker that works well in my codepen example. However, I am encountering an issue with integrating it into my code structure. The error message I am currently receiving is: Cannot read property 'push' of undefi ...

Is there a sweet TypeScript class constructor that can take in its own instance as an argument?

I have a scenario where I need to read in instances of Todo from a CSV file. The issue is that Papaparse does not handle dynamic conversion on dates, so I'm currently dropping the object into its own constructor to do the conversion: class Todo { ...

I am unable to retrieve images using the querySelector method

Trying to target all images using JavaScript, here is the code: HTML : <div class="container"> <img src="Coca.jpg" class="imgg"> <img src="Water.jpg" class="imgg"> <img src="Tree.jpg" class="imgg"> <img src="Alien.jpg" class=" ...

Establishing specific categories for a universal element

I have been working on creating an input component that functions as a custom select for enums in my application. I have tried defining them for different types using concise one-liners but have run into various typing issues. Here is what I have so far: ...