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

Using Jquery to append HTML to a div and enhance it with Bootstrap Tooltip for the added elements

Within my div with the class "results", I am continuously adding new results. One type of result is a dice roll, displayed using <kdb> For instance: function resultBox(result, color="red"){ return "<kbd class='"+color+"'>"+result+"& ...

Notifications will be displayed with Alertifyjs to the individual who activated them

Just diving into the world of nodejs and express framework, so I appreciate your patience as I navigate through this learning process. I've implemented the alertifyjs library to display notifications for different alerts on my site. However, I&apos ...

Harvesting information from an HTML table

I have a table displaying the following values: turn-right Go straight turn-left How can I extract only the 2nd value, "Go straight"? Here is the code snippet I tried: var text = $('#personDataTable tr:first td:first').text(); The code above ...

Tips for dynamically updating an HTML value with Javascript

Summary of My Issue: This involves PHP, JS, Smarty, and HTML <form name="todaydeal" method="post"> <span id="fix_addonval"></span> <input type="radio" name="offer" id="offer_{$smarty.section.mem.index+1}" value="{$display_offe ...

The Bootstrap DateTimePicker is displaying on the screen in an inaccurate

I'm having an issue with the datetimepicker on my project. The calendar appears incorrectly in Chrome, but looks fine in Edge. Here's a screenshot from Chrome: https://i.stack.imgur.com/Hi0j4.png And here is how it looks in Edge: https://i.stac ...

I am attempting to extract text from an element, but instead of the text, I received a value and am unable to click on it. This particular element is a dropdown button in a Selenium test, with

<div class="select-wrapper initialized"> <span class="caret">▼</span> <input type="text" class="select-dropdown" readonly="true" data-activates="select-options-56a6924e-42d9-1f78-1b82-fe2c1cbdfbdd" value="R3PORTS ...

Clicking to enter fullscreen mode on a website will result in the Fullscreen API automatically closing

For my current project, I am creating an offline website and would like it to display in full screen when opened. I have been using the Fullscreen API, but it exits fullscreen mode when a user navigates to another page. After researching the issue, it seem ...

What are the steps for implementing this javascript code in an HTML document?

Recently, I've been seeking advice on how to address the issue of wanting a button click to automatically select the search box on my website. Suggestions have pointed towards using Javascript for this functionality, with the following code recommend ...

Is it possible for jQuery UI Autocomplete to utilize values from various input fields simultaneously?

I've hit a roadblock with this code and it's been giving me trouble for some time now. Here is the current state of my auto-complete script: jQ19(function(){ // minLength:1 - how many characters user enters in order to start search jQ19 ...

The tab indicator in Material-UI fails to update when the back button is clicked

My code is currently functioning well: The tab indicator moves according to the URL of my tab. However, there is a peculiar issue that arises when the back button of the browser is pressed - the URL changes but the indicator remains on the same tab as befo ...

After attempting to retrieve local .HTML content with JQuery ajax for the second time, the JavaScript code within index.html appears to be malfunctioning

My apologies for my limited proficiency in English... Currently, I am engaged in phonegap development where I am attempting to utilize JQuery ajax to retrieve local .HTML content and insert this extracted content into the div with the id="next-page" in in ...

Issue with uploading files on Android devices in Laravel and Vue JS

My Laravel/Vue JS web app allows users to upload files and photos. Everything runs smoothly except when accessed on Android devices, where the axios call seems to get stuck indefinitely. Below is the code snippet causing the issue: Vue JS component <t ...

How can I dynamically pass a background:url using JavaScript to CSS?

I have a CSS code snippet below that I would like to dynamically change the "background:url" part using Javascript. div{ background: url('pinkFlower.jpg') no-repeat fixed; -webkit-background-size: cover; -moz-background-size: cover; ...

Connecting an HTML button to a Python script

I'm struggling to connect my HTML form with a Python script in order to send an email to the recipient. Despite researching various websites, I can't seem to successfully send the message that I've inputted into the text box. Here's my ...

Screening strings and arrays based on multiple criteria

My code is below and I am trying to have the bot check for two specific conditions in the user's message. The message must contain "how" plus either "doing" or "bread". It works perfectly when using only "doing" but not when adding the "bread" conditi ...

Error encountered while creating SvelteKit: The module 'intl-messageformat' that was requested is in CommonJS format

Encountering an error during production build. Here's the output of npm run build executed on Node v16.20.1 npm run build > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1c7a6c6a317a757278796e5c2c322c322d">[email&# ...

The checkboxes seem to be malfunctioning following an ajax request

I've been attempting to utilize ajax to load data, but for some reason the checkboxes aren't functioning. Below is the HTML I'm trying to load via ajax: <div class="mt-checkbox-list" > <?php foreach($product_offerings as $row){ $c ...

Give Jquery a quick breather

My goal is to have my program pause for 3 seconds before continuing with the rest of the code. I've been researching online, but all I can find are methods that delay specific lines of code, which is not what I need. What I would like to achieve look ...

Sophisticated method for arranging three integers in javascript in descending order, followed by analyzing their relative distances

In developing an interactive infographic, I am working with three integers assigned to variables, each ranging from 0 to 50000. These numbers often have values that are close to each other, and I am looking for a way to identify when either 2, all 3, or no ...

Is it possible to return a promise within the .then function in AngularJS?

I have a unique service called "usersService". I want to create a special method that interacts with another custom service I built. This other service has two handy methods: getUser() and getCurrentUser(). The getCurrentUser() method relies on the injecte ...