Utilizing SVG with an integrated script to automatically adjust to the available space within different browser

I am attempting to develop a self-contained SVG document that automatically adjusts its size and centers itself when loaded in a web browser. It's important to note that this is not referring to embedding an SVG within an HTML document.

Below is the structure of the document:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN" "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd">
<svg
    xmlns:dc="http://purl.org/dc/elements/1.1/"
    xmlns:cc="http://creativecommons.org/ns#"
    xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
    xmlns:svg="http://www.w3.org/2000/svg"
    xmlns="http://www.w3.org/2000/svg"
    xmlns:xlink="http://www.w3.org/1999/xlink"
    version="1.2"
    width="600"
    height="400"
    docname="web-business-card.svg">

The inner dimensions of the SVG document are set to 600x400, and here is the included script:

<script type="text/javascript>
    var fitObject = function() {
      var svg  = document.documentElement;
      var zoom = Math.min((window.innerWidth/600),(window.innerHeight/400));
      var left = parseInt(((window.innerWidth-(600*zoom))/2)/zoom);
      var top  = parseInt(((window.innerHeight-(400*zoom))/2)/zoom);
      
      // dynamically set style attributes
      svg.style.zoom = zoom;
      svg.style.left = left+'px';
      svg.style.top  = top+'px';
    }
    
    document.addEventListener("DOMContentLoaded", fitObject);
    window.onresize = fitObject;
</script>

This script works well in the Chromium browser during testing but experiences issues in other browsers. I'm seeking guidance on understanding the problem and finding a solution. Can anyone assist me with this?

Answer №1

Did you know that SVG documents have the ability to scale themselves to fit their parent containers without the need for additional scripting?

All you need to do is include a viewBox attribute.

For instance, in your specific case, set width="100%" and height="100%", and then add viewBox="0 0 640 400".

Once this is done, the SVG will automatically adjust its size to match the browser window when it loads.

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

Both the client and server sides are in sync with the latest data, yet the rendering fails to display the recent updates

The technologies I am currently utilizing include Nodejs, Express, MySQL, and EJS. My current task involves: Creating an app.get function that retrieves necessary data (posts) from MySQL, then renders a file using that data app.get("/" + element.name, f ...

What steps should I take to incorporate this feature into my Meteor project?

After successfully installing the type.js package, I discovered that the code works fine when directly executed in the console. Here is the code snippet: $(function(){ $(".typedelement").typed({ strings: ["You don&apo ...

How to Test React Js API Calls with Jest?

I'm currently in the process of writing test cases for my API call function, but I'm encountering difficulties as I am unable to successfully run my tests. Below is the code for the API call function and the corresponding test cases. export async ...

Angular successfully compiled without any issues despite the explicit cast of a number into a string variable

As I delve into the initial concepts of Angular, I have come across a puzzling situation. Here is the code snippet: import { Component } from '@angular/core'; @Component({ selector: 'sandbox', template: ` <h1>Hello {{ nam ...

What is the best way to convert my JSON data to HTML using JavaScript?

My dilemma seems to be rooted in the use of backticks. Strangely, an error keeps popping up whenever I try to employ them in my IDE (Brackets). I attempted solutions by testing directly in my Browser and through NotePad++, but unfortunately, nothing seeme ...

Importing a newly harvested array from a .js file (array that has been exported)

I followed this procedure with assistance from T.J to resolve my issue To address the problem, I made changes to my process. The steps I took are as follows: I switched from exporting an array through a JS file to saving a JSON file instead. Using the .g ...

Fluctuate the window.location with jQuery or javascript

My goal is to create a functionality where clicking an image will toggle the window.location url between '#' and '#footer'. The current code I have for this is: <script> function clickarrow(){ var rd=Math.floor(Math.random() ...

Encountering difficulty when trying to establish onclick functionality on dynamically loaded table through

Currently, I am working on a website where I am building a timeline using AJAX. I encountered an issue while trying to set the onclick event on each table row. I initially used a class selector but it did not produce any effect. After reading a post on St ...

Adjust the HTML 5 range slider to update according to the selected value

Is it possible to create a custom marker on an HTML5 range input element? I'm looking for a way to change the design of the circle marker as it moves along the scale from 1 to 10. Specifically, I want to change the color of the marker based on its po ...

Is there a way to retrieve the value of bindings in the component controller using Angular 1.5 and Typescript?

In my quest to develop a versatile left-hand menu component that can dynamically display different menu structures based on input strings, I stumbled upon an interesting challenge. By binding a string to the <left-hand-menu-component> element like so ...

Navigating the Angular Controller life cycle

I have set up my application states using ui-router: $stateProvider .state('app', { abstract: true, views: { 'nav@': { templateUrl: 'app/navbar.html', controller: 'NavbarController' ...

What is the method for adding a prefix to every line in JavaScript?

I'm currently working on a React project and dealing with a string that may contain newlines. I'm looking for the most efficient way to inject a symbol at the start of each line. I've considered exploding the string into an array and adding ...

React is throwing an error that says, "You cannot use the import statement outside a

My journey with learning React has just begun. I followed the steps outlined in the starting guide at https://react.dev/learn/add-react-to-an-existing-project, but unfortunately, I encountered an error: "Cannot use import statement outside a module." Here ...

Issues with Datepicker functionality in Bootstrap 5 are causing it to malfunction or not display

I am having trouble incorporating a timepicker on my webpage with bootstrap 5. The calendar feature isn't loading properly, preventing me from selecting any dates. I'm unsure if the issue lies with an error on my end or if the plugin isn't c ...

Extracting data from SVG tags within a funnel visualization

I encountered an issue while attempting to scrape data from a specific source. The code I initially used was obtained from this Scraping using Selenium and python Although the code worked flawlessly in the past, it has recently started throwing errors. ...

Launching an Angular application from the local server

I have successfully deployed an Angular frontend on a server. It is functioning well, with three scripts: /runtime.0fad6a04e0afb2fa.js /polyfills.24f3ec2108a8e0ab.js /main.a9b28b9970fe807a.js My goal is to start this application in Firefox without ...

Attach an event listener to a class, then use the removeEventListener method to detach the listener and eliminate any remaining references, ensuring proper functionality of the

When creating a class in JavaScript, a normal function returns the class object. However, events return the event object and the class object is lost: function class(a){ this.name=a; document.addEventListener('click',this.click,false); xhr.add ...

limit mongoose search results to a specific year

Would it be possible to add an option for the api user to filter the wine query by year? However, if no year is specified, mongoose should not return an empty array. The same applies to the price property. For example, http://localhost:1234/api/wine?year= ...

Having trouble with a JQuery ajax post to a PHP server - receiving the error message "SyntaxError: Unexpected token < in JSON at position 0"

I am attempting to transmit json data to a server and retrieve a json response. My code is displayed below: JS: function login() { console.log("clicked"); //gather form values into variables var email = $("#email").val(); var password = $("#password"). ...

Utilizing Angular Forms for dynamic string validation with the *ngIf directive

I have a challenge where I need to hide forms in a list if they are empty. These forms contain string values. I attempted to use *ngIf but unfortunately, it did not work as expected and empty fields are still visible in the list. How can I address this iss ...