javascript send variable as a style parameter

screen_w = window.innerWidth;
screen_h = window.innerHeight;

I am trying to retrieve the dimensions of the window and store them in variables. Is there a way to then use these variables in my CSS styles?

For example:

img
{
  width: screen_w;
  height: screen_h;
}

I have attempted

<script type="text/javascript"> 
<style>
img..
</style>
</script>

but it does not seem to work. Is this even possible, or is there another method for passing a variable?

Thanks in advance.

///Added

The link below -----v

suggests creating a node that represents your style

<script type="text/javascript">

var head = document.getElementsByTagName('head')[0],
    style = document.createElement('style'),
    rules = document.createNode('img { width: screen_w; height: screen_h; }');

style.type = 'text/css';
if(style.styleSheet)
    style.styleSheet.cssText = rules.nodeValue;
else style.appendChild(rules);
head.appendChild(style);

</script>

then in my HTML I just need to insert my image.

<img src="slide1.jpg">

but somehow it still does not pass through properly.

However, I can get the "document.getElementById" to work. Is there a way to do this without a button, like using onLoad()?

function changeSize()
{
document.getElementById("picture").height= screen_h;
document.getElementById("picture").width= screen_w;
}
</script>

</head>

<body>

<img id="picture" src="slide1.jpg" width="300" height="98" />
<br /><br />
<input type="button" onclick="changeSize()" value="Change size of image" />

Answer №1

It is not possible to pass variables to CSS.

But, you have the option to use JavaScript to directly alter the styling of images, such as dimensions.

Answer №2

If you want to change CSS using JS, check out this helpful question:

Learn how to create a <style> tag with Javascript

Answer №3

<script >
window.onload = function() {
    $.ajax({url: "api/<route-name>", success: function(result){
        console.log(result.data[16]['value']);
        document.documentElement.style.setProperty('--my-variable-name', result.data[14]['value']);
    }});
}
<style>
.gender_radio .radio-list .is-checked {
    background-color: var(--my-variable-name) !important;
}

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

obtain the text content from HTML response in Node.js

In my current situation, I am facing a challenge in extracting the values from the given HTML text and storing them in separate variables. I have experimented with Cheerio library, but unfortunately, it did not yield the desired results. The provided HTML ...

Updating style of element in EJS following POST request in Node.js using Express

I am working on a form page that is supposed to display a Success Alert (Boostrap) once the user fills out the form and clicks the Submit button. <form class="well form-horizontal" action="/contact" method="post" id="contact_form"> ... (input fiel ...

Waiting for the result of an AngularJS promise

When I click a button in my AngularJS app, the following code is executed: if (!$scope.isChecked) { $scope.getExistingName($scope.userName).then(function (data) { $scope.userName = data; }); } // Additional processing code foll ...

Struggling to generate a div using my JS/jQuery code

Currently working on a post-it web application to improve my skills in JavaScript and jQuery. I've encountered a few errors that have me stumped. Although I'm new to StackOverflow, I often use it as a helpful resource. You can find the code here ...

Using GSAP to create a staggered animation with a negative delay

Seeking a Solution: I am curious if there is a method to incorporate a negative delay into the staggerFrom / staggerTo functions within greensock? Issue at Hand: The current animation I have in place is extending longer than desired. It would be benefic ...

React Nextjs implementation of a fixed navigation bar to stick at the top

Hello, I am experiencing some issues setting up a sticky navbar in Next.js. The current navbar doesn't seem to be functioning as expected. Is there anyone who can assist me with the code provided below? import React, { useEffect } from 'react&apo ...

Handling CORS in Vue.js applications

As a newcomer to Vue, I am currently grappling with a CORS issue in my application. During development at http://localhost:8080/, sending a request to , I was able to resolve the CORS problem using the following code snippet: vue.config.js module.exports ...

Utilize FormData by passing it to a separate function and then utilizing it

I have encountered a perplexing issue with my Flask app that involves submitting a form to upload an image to the server. Despite my efforts, I have been unable to find a solution on my own. When I submit the form, I use FormData to create the necessary o ...

Object with a specific name sitting within an array nested within another object

I have a node.js model that includes an array called keys containing multiple objects. I am looking to display these named objects in the view. Below is the model: var mongoose = require('mongoose'); var website = require('./website' ...

Exploring custom JavaScript with Construct 2's generated code

How can I access the score of a game user in Construct2 Engine using external JavaScript? Is there a method to achieve this? Appreciate any guidance on this matter. ...

Troubleshooting React-Redux: Button click not triggering action dispatch

I am facing an issue where my action is not being dispatched on button click. I have checked all the relevant files including action, reducer, root reducer, configStore, Index, and Component to find the problem. If anyone can help me troubleshoot why my a ...

Exploring Angular: How does Number.isNaN handle non-empty strings?

Within my component, there is a dropdown menu that allows users to choose a value. Upon selecting an item from the dropdown, a function called onDropdownChange is triggered. The parameter passed to this function can either be a string ("Please select an op ...

Cease running code post while loop (do not use break)

I need help with my code that checks if a user is already in a Database. Once the while Loop runs, it verifies the presence of the MC Player in their Database through the Mojang API. However, if the user is already in my Database, I want to skip the Mojang ...

Utilizing AJAX to send RSS feeds to a Django view

I'm fairly new to using ajax. Here's the scenario I'm dealing with: I'm working on a side project that involves displaying news and scores for various sports. To achieve this, I'm utilizing rss feeds from different sources. In my D ...

Toggle the backgroundImage visibility by setting it to either hidden or displayed using jquery

$('.arrow').css("background-image", "url('../img/arrow.png')").hide(); I have implemented a custom solution using CSS and jQuery to hide the downward arrow when scrolling down on my webpage. `$( document ).ready(function() {
 co ...

Ensuring Input Integrity: Utilizing HTML and Javascript to Block Unfilled Form Submissions

Currently, I am working on developing a registration page using HTML and JavaScript. Although I have added the 'required' tag in HTML to prevent users from submitting empty input fields, I noticed that users can bypass this restriction by simply ...

Is Jade monitoring *.jade files?

Though I am not sure of the internal workings of Jade, my best guess is that it compiles each template file once and then employs a compiled and cached version for subsequent HTTP requests. One intriguing observation I have made while running my Express a ...

Align dropdown navigation menu/sorting dropdown in the same position as the button

Exploring the world of dropdown menus in CSS has led me to encounter some challenges. I am striving to ensure that the dropdown boxes appear on the same line as the button that triggers them. Below is the CSS code I have been working with: /* global style ...

How can you effectively use asynchronous functions?

I'm currently exploring Express and asynchronous/functional programming. app.get('/users/:id', (req, res) => { let id = req.params.id; let User = require('../models/user') User.is_complete(id, (validate) => { conso ...

Clicking two times changes the background

I am facing an issue with three boxes on my website. Each box is associated with a corresponding div. When I click on any box, the div displays and the background color turns red. However, when I click on the same box again, the div disappears but the back ...