Top method for centering a flexible SVG vertically once the page width becomes too narrow

Currently, I have two SVG images displayed side by side on a webpage. One SVG needs to maintain a fixed size while the other should scale as needed, and I have achieved this functionality.

However, I am facing an issue where I want the two SVGs to align vertically when the browser window is narrow enough. I believe I can solve this by dynamically adding or removing a class based on the window size and adjusting the CSS accordingly, but my attempts so far have been unsuccessful.

To demonstrate where I am in the process, here is a JSFiddle link: JSFiddle Link

$(function() {

  $(window).on('resize', function() {
    var chart = $("#rightEl");
    var container = chart.parent();
    var targetWidth = container.width();
    chart.attr("width", targetWidth > 300 ? 300 : targetWidth)
      .attr("height", targetWidth > 300 ? 300 : targetWidth)
    //when targetWidth is less than "n" I want them to align vertically
  }).trigger("resize");
})
#leftEl {
  width: 300px;
  position: absolute;
}

#right-wrapper {
  margin-left: 300px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>

<body>
  <div id="placeholder"></div>
  <svg id="leftEl" width="300" height="300" class="svg-container">
      <circle cx="150" cy="150" r="150" class="r" stroke="black" stroke-width="2"></circle>
    </svg>
  <div id="right-wrapper" width="300" height="300">
    <svg id="rightEl" viewBox="0 0 300 300" preserveAspectRatio="xMidYMid meet" width="300" height="300">
        <circle cx="150" cy="150" r="150" stroke="black" stroke-width="2"></circle>
      </svg>
  </div>
</body>

</html>

Answer №1

Presented below is a straightforward JavaScript implementation for monitoring window size. The if statement is configured to activate when the window width falls below 900 pixels, although you have the flexibility to customize this threshold.

The variable width is defined within the scope of this function using let, restricting its accessibility outside of the function.

window.addEventListener('resize', function( event ){

  // keeps track of the page's width
  let width = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);

if (width < 900) {

    yourVariableNameHere.classList.remove('classNameToRemove');

}

});

Answer №2

Implement media queries and update the CSS styling

https://jsfiddle.net/h93cqoaw/

#leftEl {
  width: 300px;
  position: absolute;
}

#right-wrapper {
  margin-left: 300px;
}

@media only screen and (max-width:650px){
  #leftEl {
  width: 300px;
  position: relative;
  }
  #right-wrapper {
  margin-left: 0;
}
}
<html>
  <body>
    <div id="placeholder"></div>
    <svg id="leftEl" width="300" height="300" class="svg-container">
      <circle cx="150" cy="150" r="150" class="r" stroke="black" stroke-width="2"></circle>
    </svg>
    <div id="right-wrapper" width="300" height="300">
      <svg id="rightEl" viewBox="0 0 300 300" preserveAspectRatio="xMidYMid meet" width="300" height="300">
        <circle cx="150" cy="150" r="150" stroke="black" stroke-width="2"></circle>
      </svg>
    </div>


  </body>

</html>

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

Triggering a click event on a specific element in a jQuery accordion

I've encountered an issue with a jQuery accordion script that I'm using to display events on this particular page: The problem lies in the fact that the script collapses whenever the user clicks anywhere inside the wrapper. What I actually need ...

The eccentricities of Angular Translate in Firefox and Safari

While everything functions correctly in Chrome, there seems to be an issue with changing the language in Safari and Firefox. angular.module('angularApp') .config(['$translateProvider', function ($translateProvider) { $translateProv ...

Phrases are truncated in the initial line of each ion-item within the ion-list

In Ionic 3, I am facing an issue with my ion-list where the first line inside each ion-item is getting cut off. Specifically, the capital 'A' letter is not entirely visible. Can anyone provide assistance with this? Thank you. Below is my code sn ...

Difficulty in sharing cookies among subdomains

I have successfully stored my visitors' style sheet preference in a cookie, but I am facing an issue with sharing the cookie across subdomains. Even after specifying the domain, the cookie does not seem to be shared. What could be causing this proble ...

npm command syntax to accept multiple arguments

Struggling to pass arguments in an npm command and utilize them in my script For instance: npm run test -b chrome -e QA "scripts": { "test": "something.js ./xyz/abc/cdf --something \"{\\\"browser\\\": \&bsol ...

Express route encountered an error with an undefined value

Here's the method declaration: exports.postRedisValue = function(req,res) { let keyRedis = req.body.key; let valueRedis = req.body.value; console.log(keyRedis); //displays as undefined if(keyRedis && valueRedis){ ...

Using Sass to Loop through Specific Items

Currently, I am in the process of developing a SASS loop to iterate over a series of images (let's say 50). My goal is to increment the transition delay by 50ms for every nth-of-type image. However, it appears that the current for loop I have implemen ...

NodeJS Express throwing error as HTML on Angular frontend

I am currently facing an issue with my nodejs server that uses the next() function to catch errors. The problem is that the thrown error is being returned to the frontend in HTML format instead of JSON. I need help in changing it to JSON. Here is a snippe ...

Receive a response in fragments from express on the browser

As I work on creating a progress bar to track long-running server-side tasks that may take up to a few minutes, I am exploring different methods to display the progress of each task. While WebSockets and interval polling are options, I prefer using long-po ...

`CSS animation for vanishing line effect`

I want to create an animated logo that gives the illusion of being pulled up by a rope, represented by a vertical black line, from the bottom of the page to the top. As the logo moves upwards, I would like the rope to disappear behind it, but I'm uns ...

IE8 does not support Jquery ajax() for cross domain requests to remote servers

My current script includes an ajax request to a remote server that provides a plain text response. This setup functions properly in all browsers with the exception of IE8, which is not surprising. The script snippet looks like this: $.ajax({ url: &apos ...

What is the best method to display a component using a string in Vue 3?

I've been attempting to render a component from a string without success. Here are my codes: <template> <div v-html="beautifyNotification(notification)"></div> </template> <script> import { Link } from '@i ...

Leveraging Selenium to extract text from a dynamically populated DIV using JavaScript

I am currently utilizing Selenium to automatically retrieve all comments from a New York Times article. Once the comments are loaded, my goal is to extract them and save the information for future use. However, upon inspecting the source code of the articl ...

React and Express are incompatible due to the error message "TypeError: undefined is not a function

I am attempting to display the data from this array on my website using react and express: [{"LocationName":"LIBERTY DOGS","Address":"105 Greenwood Ave N, Seattle WA","Available":"Y"},{"LocationName":"FREEDOM DOGS","Address":"105 Greenwood Ave N, Seattle ...

Troubleshooting the issue of data retrieval failure in asp.net mvc controller using jquery.post()

I am currently working on an ASP.NET MVC web application that is written in VB.NET. My goal is to send data using jQuery to my controller. Below is the code for my controller: <HttpPost()> Function GetData(p As DataManager) As JsonResult ...

CSS error with contrasting colors, the reason behind it is unknown

Here is the code snippet I am working on: I have set the background color to #f1f5ff and the font color to #181818. Despite thinking that the contrast is good, I am still encountering an error where the text is not visible. I have tried changing 'c ...

A Guide to Accessing Numbered Properties within an Object

I am working with a large Object that has over 700 properties, all numbered. How can I efficiently iterate through each of these numbered properties? { '0': { emails: { categorized: [Object], all: [Object], primary: &a ...

What could be the reason for the electron defaultPath failing to open the specified directory?

Hi, I'm experiencing difficulties opening the directory path (/home/userxyz/Releases/alpha) using electron. This is what I have attempted: I have a similar path on Ubuntu: /home/userxyz/Releases/alpha When trying to access this path with the fo ...

Tips for integrating the SlitSlider jQuery plugin into your website

Trying to incorporate the SlitSlider carousel into my project has proven challenging due to a lack of thorough documentation. Has anyone successfully implemented this? I keep encountering the error message: TypeError: self._init is not a function You can ...

Execute a function prior to making a synchronous call

Seeking guidance on a complex issue that I have encountered. In my code, I am dealing with a synchronous AJAX call and need to execute a function before this particular call is made. The function in question is a simple one: $.blockUI(); This function ...